By moving the call to Load() up in SearchProvider::Start(), we are giving a chance...
[chromium-blink-merge.git] / third_party / sqlite / amalgamation / sqlite3.c
blobb9088a522a4a147600ce3db65ef7870c10be6e73
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.7.6.3. By combining all the individual C code files into this
4 ** single large file, the entire code can be compiled as a single translation
5 ** unit. This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately. Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite. To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library. (If you do not have
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file. Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 #ifndef SQLITE_API
26 # define SQLITE_API
27 #endif
28 /************** Begin file sqliteInt.h ***************************************/
30 ** 2001 September 15
32 ** The author disclaims copyright to this source code. In place of
33 ** a legal notice, here is a blessing:
35 ** May you do good and not evil.
36 ** May you find forgiveness for yourself and forgive others.
37 ** May you share freely, never taking more than you give.
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
47 ** These #defines should enable >2GB file support on POSIX if the
48 ** underlying operating system supports it. If the OS lacks
49 ** large file support, or if the OS is windows, these should be no-ops.
51 ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
52 ** system #includes. Hence, this block of code must be the very first
53 ** code in all source files.
55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56 ** on the compiler command line. This is necessary if you are compiling
57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58 ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
59 ** without this option, LFS is enable. But LFS does not exist in the kernel
60 ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
61 ** portability you should omit LFS.
63 ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
65 #ifndef SQLITE_DISABLE_LFS
66 # define _LARGE_FILE 1
67 # ifndef _FILE_OFFSET_BITS
68 # define _FILE_OFFSET_BITS 64
69 # endif
70 # define _LARGEFILE_SOURCE 1
71 #endif
74 ** Include the configuration header output by 'configure' if we're using the
75 ** autoconf-based build
77 #ifdef _HAVE_SQLITE_CONFIG_H
78 #include "config.h"
79 #endif
81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82 /************** Begin file sqliteLimit.h *************************************/
84 ** 2007 May 7
86 ** The author disclaims copyright to this source code. In place of
87 ** a legal notice, here is a blessing:
89 ** May you do good and not evil.
90 ** May you find forgiveness for yourself and forgive others.
91 ** May you share freely, never taking more than you give.
93 *************************************************************************
94 **
95 ** This file defines various limits of what SQLite can process.
99 ** The maximum length of a TEXT or BLOB in bytes. This also
100 ** limits the size of a row in a table or index.
102 ** The hard limit is the ability of a 32-bit signed integer
103 ** to count the size: 2^31-1 or 2147483647.
105 #ifndef SQLITE_MAX_LENGTH
106 # define SQLITE_MAX_LENGTH 1000000000
107 #endif
110 ** This is the maximum number of
112 ** * Columns in a table
113 ** * Columns in an index
114 ** * Columns in a view
115 ** * Terms in the SET clause of an UPDATE statement
116 ** * Terms in the result set of a SELECT statement
117 ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118 ** * Terms in the VALUES clause of an INSERT statement
120 ** The hard upper limit here is 32676. Most database people will
121 ** tell you that in a well-normalized database, you usually should
122 ** not have more than a dozen or so columns in any table. And if
123 ** that is the case, there is no point in having more than a few
124 ** dozen values in any of the other situations described above.
126 #ifndef SQLITE_MAX_COLUMN
127 # define SQLITE_MAX_COLUMN 2000
128 #endif
131 ** The maximum length of a single SQL statement in bytes.
133 ** It used to be the case that setting this value to zero would
134 ** turn the limit off. That is no longer true. It is not possible
135 ** to turn this limit off.
137 #ifndef SQLITE_MAX_SQL_LENGTH
138 # define SQLITE_MAX_SQL_LENGTH 1000000000
139 #endif
142 ** The maximum depth of an expression tree. This is limited to
143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
144 ** want to place more severe limits on the complexity of an
145 ** expression.
147 ** A value of 0 used to mean that the limit was not enforced.
148 ** But that is no longer true. The limit is now strictly enforced
149 ** at all times.
151 #ifndef SQLITE_MAX_EXPR_DEPTH
152 # define SQLITE_MAX_EXPR_DEPTH 1000
153 #endif
156 ** The maximum number of terms in a compound SELECT statement.
157 ** The code generator for compound SELECT statements does one
158 ** level of recursion for each term. A stack overflow can result
159 ** if the number of terms is too large. In practice, most SQL
160 ** never has more than 3 or 4 terms. Use a value of 0 to disable
161 ** any limit on the number of terms in a compount SELECT.
163 #ifndef SQLITE_MAX_COMPOUND_SELECT
164 # define SQLITE_MAX_COMPOUND_SELECT 500
165 #endif
168 ** The maximum number of opcodes in a VDBE program.
169 ** Not currently enforced.
171 #ifndef SQLITE_MAX_VDBE_OP
172 # define SQLITE_MAX_VDBE_OP 25000
173 #endif
176 ** The maximum number of arguments to an SQL function.
178 #ifndef SQLITE_MAX_FUNCTION_ARG
179 # define SQLITE_MAX_FUNCTION_ARG 127
180 #endif
183 ** The maximum number of in-memory pages to use for the main database
184 ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
187 # define SQLITE_DEFAULT_CACHE_SIZE 2000
188 #endif
189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
191 #endif
194 ** The default number of frames to accumulate in the log file before
195 ** checkpointing the database in WAL mode.
197 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
199 #endif
202 ** The maximum number of attached databases. This must be between 0
203 ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
204 ** is used internally to track attached databases.
206 #ifndef SQLITE_MAX_ATTACHED
207 # define SQLITE_MAX_ATTACHED 10
208 #endif
212 ** The maximum value of a ?nnn wildcard that the parser will accept.
214 #ifndef SQLITE_MAX_VARIABLE_NUMBER
215 # define SQLITE_MAX_VARIABLE_NUMBER 999
216 #endif
218 /* Maximum page size. The upper bound on this value is 65536. This a limit
219 ** imposed by the use of 16-bit offsets within each page.
221 ** Earlier versions of SQLite allowed the user to change this value at
222 ** compile time. This is no longer permitted, on the grounds that it creates
223 ** a library that is technically incompatible with an SQLite library
224 ** compiled with a different limit. If a process operating on a database
225 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
226 ** compiled with the default page-size limit will not be able to rollback
227 ** the aborted transaction. This could lead to database corruption.
229 #ifdef SQLITE_MAX_PAGE_SIZE
230 # undef SQLITE_MAX_PAGE_SIZE
231 #endif
232 #define SQLITE_MAX_PAGE_SIZE 65536
236 ** The default size of a database page.
238 #ifndef SQLITE_DEFAULT_PAGE_SIZE
239 # define SQLITE_DEFAULT_PAGE_SIZE 1024
240 #endif
241 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
242 # undef SQLITE_DEFAULT_PAGE_SIZE
243 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
244 #endif
247 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
248 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
249 ** device characteristics (sector-size and atomic write() support),
250 ** SQLite may choose a larger value. This constant is the maximum value
251 ** SQLite will choose on its own.
253 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
254 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
255 #endif
256 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
257 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
258 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
259 #endif
263 ** Maximum number of pages in one database file.
265 ** This is really just the default value for the max_page_count pragma.
266 ** This value can be lowered (or raised) at run-time using that the
267 ** max_page_count macro.
269 #ifndef SQLITE_MAX_PAGE_COUNT
270 # define SQLITE_MAX_PAGE_COUNT 1073741823
271 #endif
274 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275 ** operator.
277 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279 #endif
282 ** Maximum depth of recursion for triggers.
284 ** A value of 1 means that a trigger program will not be able to itself
285 ** fire any triggers. A value of 0 means that no trigger programs at all
286 ** may be executed.
288 #ifndef SQLITE_MAX_TRIGGER_DEPTH
289 # define SQLITE_MAX_TRIGGER_DEPTH 1000
290 #endif
292 /************** End of sqliteLimit.h *****************************************/
293 /************** Continuing where we left off in sqliteInt.h ******************/
295 /* Disable nuisance warnings on Borland compilers */
296 #if defined(__BORLANDC__)
297 #pragma warn -rch /* unreachable code */
298 #pragma warn -ccc /* Condition is always true or false */
299 #pragma warn -aus /* Assigned value is never used */
300 #pragma warn -csu /* Comparing signed and unsigned */
301 #pragma warn -spa /* Suspicious pointer arithmetic */
302 #endif
304 /* Needed for various definitions... */
305 #ifndef _GNU_SOURCE
306 # define _GNU_SOURCE
307 #endif
310 ** Include standard header files as necessary
312 #ifdef HAVE_STDINT_H
313 #include <stdint.h>
314 #endif
315 #ifdef HAVE_INTTYPES_H
316 #include <inttypes.h>
317 #endif
320 ** The number of samples of an index that SQLite takes in order to
321 ** construct a histogram of the table content when running ANALYZE
322 ** and with SQLITE_ENABLE_STAT2
324 #define SQLITE_INDEX_SAMPLES 10
327 ** The following macros are used to cast pointers to integers and
328 ** integers to pointers. The way you do this varies from one compiler
329 ** to the next, so we have developed the following set of #if statements
330 ** to generate appropriate macros for a wide range of compilers.
332 ** The correct "ANSI" way to do this is to use the intptr_t type.
333 ** Unfortunately, that typedef is not available on all compilers, or
334 ** if it is available, it requires an #include of specific headers
335 ** that vary from one machine to the next.
337 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
338 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
339 ** So we have to define the macros in different ways depending on the
340 ** compiler.
342 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
343 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
344 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
345 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
346 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
347 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
348 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
349 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
350 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
351 #else /* Generates a warning - but it always works */
352 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
353 # define SQLITE_PTR_TO_INT(X) ((int)(X))
354 #endif
357 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
358 ** 0 means mutexes are permanently disable and the library is never
359 ** threadsafe. 1 means the library is serialized which is the highest
360 ** level of threadsafety. 2 means the libary is multithreaded - multiple
361 ** threads can use SQLite as long as no two threads try to use the same
362 ** database connection at the same time.
364 ** Older versions of SQLite used an optional THREADSAFE macro.
365 ** We support that for legacy.
367 #if !defined(SQLITE_THREADSAFE)
368 #if defined(THREADSAFE)
369 # define SQLITE_THREADSAFE THREADSAFE
370 #else
371 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
372 #endif
373 #endif
376 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
377 ** It determines whether or not the features related to
378 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
379 ** be overridden at runtime using the sqlite3_config() API.
381 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
382 # define SQLITE_DEFAULT_MEMSTATUS 1
383 #endif
386 ** Exactly one of the following macros must be defined in order to
387 ** specify which memory allocation subsystem to use.
389 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
390 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
392 ** (Historical note: There used to be several other options, but we've
393 ** pared it down to just these two.)
395 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
396 ** the default.
398 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
399 # error "At most one of the following compile-time configuration options\
400 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
401 #endif
402 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
403 # define SQLITE_SYSTEM_MALLOC 1
404 #endif
407 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
408 ** sizes of memory allocations below this value where possible.
410 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
411 # define SQLITE_MALLOC_SOFT_LIMIT 1024
412 #endif
415 ** We need to define _XOPEN_SOURCE as follows in order to enable
416 ** recursive mutexes on most Unix systems. But Mac OS X is different.
417 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
418 ** so it is omitted there. See ticket #2673.
420 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
421 ** implemented on some systems. So we avoid defining it at all
422 ** if it is already defined or if it is unneeded because we are
423 ** not doing a threadsafe build. Ticket #2681.
425 ** See also ticket #2741.
427 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
428 # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
429 #endif
432 ** The TCL headers are only needed when compiling the TCL bindings.
434 #if defined(SQLITE_TCL) || defined(TCLSH)
435 # include <tcl.h>
436 #endif
439 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
440 ** Setting NDEBUG makes the code smaller and run faster. So the following
441 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
442 ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out
443 ** feature.
445 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
446 # define NDEBUG 1
447 #endif
450 ** The testcase() macro is used to aid in coverage testing. When
451 ** doing coverage testing, the condition inside the argument to
452 ** testcase() must be evaluated both true and false in order to
453 ** get full branch coverage. The testcase() macro is inserted
454 ** to help ensure adequate test coverage in places where simple
455 ** condition/decision coverage is inadequate. For example, testcase()
456 ** can be used to make sure boundary values are tested. For
457 ** bitmask tests, testcase() can be used to make sure each bit
458 ** is significant and used at least once. On switch statements
459 ** where multiple cases go to the same block of code, testcase()
460 ** can insure that all cases are evaluated.
463 #ifdef SQLITE_COVERAGE_TEST
464 SQLITE_PRIVATE void sqlite3Coverage(int);
465 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
466 #else
467 # define testcase(X)
468 #endif
471 ** The TESTONLY macro is used to enclose variable declarations or
472 ** other bits of code that are needed to support the arguments
473 ** within testcase() and assert() macros.
475 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
476 # define TESTONLY(X) X
477 #else
478 # define TESTONLY(X)
479 #endif
482 ** Sometimes we need a small amount of code such as a variable initialization
483 ** to setup for a later assert() statement. We do not want this code to
484 ** appear when assert() is disabled. The following macro is therefore
485 ** used to contain that setup code. The "VVA" acronym stands for
486 ** "Verification, Validation, and Accreditation". In other words, the
487 ** code within VVA_ONLY() will only run during verification processes.
489 #ifndef NDEBUG
490 # define VVA_ONLY(X) X
491 #else
492 # define VVA_ONLY(X)
493 #endif
496 ** The ALWAYS and NEVER macros surround boolean expressions which
497 ** are intended to always be true or false, respectively. Such
498 ** expressions could be omitted from the code completely. But they
499 ** are included in a few cases in order to enhance the resilience
500 ** of SQLite to unexpected behavior - to make the code "self-healing"
501 ** or "ductile" rather than being "brittle" and crashing at the first
502 ** hint of unplanned behavior.
504 ** In other words, ALWAYS and NEVER are added for defensive code.
506 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
507 ** be true and false so that the unreachable code then specify will
508 ** not be counted as untested code.
510 #if defined(SQLITE_COVERAGE_TEST)
511 # define ALWAYS(X) (1)
512 # define NEVER(X) (0)
513 #elif !defined(NDEBUG)
514 # define ALWAYS(X) ((X)?1:(assert(0),0))
515 # define NEVER(X) ((X)?(assert(0),1):0)
516 #else
517 # define ALWAYS(X) (X)
518 # define NEVER(X) (X)
519 #endif
522 ** Return true (non-zero) if the input is a integer that is too large
523 ** to fit in 32-bits. This macro is used inside of various testcase()
524 ** macros to verify that we have tested SQLite for large-file support.
526 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
529 ** The macro unlikely() is a hint that surrounds a boolean
530 ** expression that is usually false. Macro likely() surrounds
531 ** a boolean expression that is usually true. GCC is able to
532 ** use these hints to generate better code, sometimes.
534 #if defined(__GNUC__) && 0
535 # define likely(X) __builtin_expect((X),1)
536 # define unlikely(X) __builtin_expect((X),0)
537 #else
538 # define likely(X) !!(X)
539 # define unlikely(X) !!(X)
540 #endif
542 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
543 /************** Begin file sqlite3.h *****************************************/
545 ** 2001 September 15
547 ** The author disclaims copyright to this source code. In place of
548 ** a legal notice, here is a blessing:
550 ** May you do good and not evil.
551 ** May you find forgiveness for yourself and forgive others.
552 ** May you share freely, never taking more than you give.
554 *************************************************************************
555 ** This header file defines the interface that the SQLite library
556 ** presents to client programs. If a C-function, structure, datatype,
557 ** or constant definition does not appear in this file, then it is
558 ** not a published API of SQLite, is subject to change without
559 ** notice, and should not be referenced by programs that use SQLite.
561 ** Some of the definitions that are in this file are marked as
562 ** "experimental". Experimental interfaces are normally new
563 ** features recently added to SQLite. We do not anticipate changes
564 ** to experimental interfaces but reserve the right to make minor changes
565 ** if experience from use "in the wild" suggest such changes are prudent.
567 ** The official C-language API documentation for SQLite is derived
568 ** from comments in this file. This file is the authoritative source
569 ** on how SQLite interfaces are suppose to operate.
571 ** The name of this file under configuration management is "sqlite.h.in".
572 ** The makefile makes some minor changes to this file (such as inserting
573 ** the version number) and changes its name to "sqlite3.h" as
574 ** part of the build process.
576 #ifndef _SQLITE3_H_
577 #define _SQLITE3_H_
578 #include <stdarg.h> /* Needed for the definition of va_list */
581 ** Make sure we can call this stuff from C++.
583 #if 0
584 extern "C" {
585 #endif
589 ** Add the ability to override 'extern'
591 #ifndef SQLITE_EXTERN
592 # define SQLITE_EXTERN extern
593 #endif
595 #ifndef SQLITE_API
596 # define SQLITE_API
597 #endif
601 ** These no-op macros are used in front of interfaces to mark those
602 ** interfaces as either deprecated or experimental. New applications
603 ** should not use deprecated interfaces - they are support for backwards
604 ** compatibility only. Application writers should be aware that
605 ** experimental interfaces are subject to change in point releases.
607 ** These macros used to resolve to various kinds of compiler magic that
608 ** would generate warning messages when they were used. But that
609 ** compiler magic ended up generating such a flurry of bug reports
610 ** that we have taken it all out and gone back to using simple
611 ** noop macros.
613 #define SQLITE_DEPRECATED
614 #define SQLITE_EXPERIMENTAL
617 ** Ensure these symbols were not defined by some previous header file.
619 #ifdef SQLITE_VERSION
620 # undef SQLITE_VERSION
621 #endif
622 #ifdef SQLITE_VERSION_NUMBER
623 # undef SQLITE_VERSION_NUMBER
624 #endif
627 ** CAPI3REF: Compile-Time Library Version Numbers
629 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
630 ** evaluates to a string literal that is the SQLite version in the
631 ** format "X.Y.Z" where X is the major version number (always 3 for
632 ** SQLite3) and Y is the minor version number and Z is the release number.)^
633 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
634 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
635 ** numbers used in [SQLITE_VERSION].)^
636 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
637 ** be larger than the release from which it is derived. Either Y will
638 ** be held constant and Z will be incremented or else Y will be incremented
639 ** and Z will be reset to zero.
641 ** Since version 3.6.18, SQLite source code has been stored in the
642 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
643 ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
644 ** a string which identifies a particular check-in of SQLite
645 ** within its configuration management system. ^The SQLITE_SOURCE_ID
646 ** string contains the date and time of the check-in (UTC) and an SHA1
647 ** hash of the entire source tree.
649 ** See also: [sqlite3_libversion()],
650 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
651 ** [sqlite_version()] and [sqlite_source_id()].
653 #define SQLITE_VERSION "3.7.6.3"
654 #define SQLITE_VERSION_NUMBER 3007006
655 #define SQLITE_SOURCE_ID "2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e"
658 ** CAPI3REF: Run-Time Library Version Numbers
659 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
661 ** These interfaces provide the same information as the [SQLITE_VERSION],
662 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
663 ** but are associated with the library instead of the header file. ^(Cautious
664 ** programmers might include assert() statements in their application to
665 ** verify that values returned by these interfaces match the macros in
666 ** the header, and thus insure that the application is
667 ** compiled with matching library and header files.
669 ** <blockquote><pre>
670 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
671 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
672 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
673 ** </pre></blockquote>)^
675 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
676 ** macro. ^The sqlite3_libversion() function returns a pointer to the
677 ** to the sqlite3_version[] string constant. The sqlite3_libversion()
678 ** function is provided for use in DLLs since DLL users usually do not have
679 ** direct access to string constants within the DLL. ^The
680 ** sqlite3_libversion_number() function returns an integer equal to
681 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
682 ** a pointer to a string constant whose value is the same as the
683 ** [SQLITE_SOURCE_ID] C preprocessor macro.
685 ** See also: [sqlite_version()] and [sqlite_source_id()].
687 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
688 SQLITE_API const char *sqlite3_libversion(void);
689 SQLITE_API const char *sqlite3_sourceid(void);
690 SQLITE_API int sqlite3_libversion_number(void);
693 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
695 ** ^The sqlite3_compileoption_used() function returns 0 or 1
696 ** indicating whether the specified option was defined at
697 ** compile time. ^The SQLITE_ prefix may be omitted from the
698 ** option name passed to sqlite3_compileoption_used().
700 ** ^The sqlite3_compileoption_get() function allows iterating
701 ** over the list of options that were defined at compile time by
702 ** returning the N-th compile time option string. ^If N is out of range,
703 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
704 ** prefix is omitted from any strings returned by
705 ** sqlite3_compileoption_get().
707 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
708 ** and sqlite3_compileoption_get() may be omitted by specifying the
709 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
711 ** See also: SQL functions [sqlite_compileoption_used()] and
712 ** [sqlite_compileoption_get()] and the [compile_options pragma].
714 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
715 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
716 SQLITE_API const char *sqlite3_compileoption_get(int N);
717 #endif
720 ** CAPI3REF: Test To See If The Library Is Threadsafe
722 ** ^The sqlite3_threadsafe() function returns zero if and only if
723 ** SQLite was compiled mutexing code omitted due to the
724 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
726 ** SQLite can be compiled with or without mutexes. When
727 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
728 ** are enabled and SQLite is threadsafe. When the
729 ** [SQLITE_THREADSAFE] macro is 0,
730 ** the mutexes are omitted. Without the mutexes, it is not safe
731 ** to use SQLite concurrently from more than one thread.
733 ** Enabling mutexes incurs a measurable performance penalty.
734 ** So if speed is of utmost importance, it makes sense to disable
735 ** the mutexes. But for maximum safety, mutexes should be enabled.
736 ** ^The default behavior is for mutexes to be enabled.
738 ** This interface can be used by an application to make sure that the
739 ** version of SQLite that it is linking against was compiled with
740 ** the desired setting of the [SQLITE_THREADSAFE] macro.
742 ** This interface only reports on the compile-time mutex setting
743 ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
744 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
745 ** can be fully or partially disabled using a call to [sqlite3_config()]
746 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
747 ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
748 ** sqlite3_threadsafe() function shows only the compile-time setting of
749 ** thread safety, not any run-time changes to that setting made by
750 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
751 ** is unchanged by calls to sqlite3_config().)^
753 ** See the [threading mode] documentation for additional information.
755 SQLITE_API int sqlite3_threadsafe(void);
758 ** CAPI3REF: Database Connection Handle
759 ** KEYWORDS: {database connection} {database connections}
761 ** Each open SQLite database is represented by a pointer to an instance of
762 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
763 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
764 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
765 ** is its destructor. There are many other interfaces (such as
766 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
767 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
768 ** sqlite3 object.
770 typedef struct sqlite3 sqlite3;
773 ** CAPI3REF: 64-Bit Integer Types
774 ** KEYWORDS: sqlite_int64 sqlite_uint64
776 ** Because there is no cross-platform way to specify 64-bit integer types
777 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
779 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
780 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
781 ** compatibility only.
783 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
784 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
785 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
786 ** between 0 and +18446744073709551615 inclusive.
788 #ifdef SQLITE_INT64_TYPE
789 typedef SQLITE_INT64_TYPE sqlite_int64;
790 typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
791 #elif defined(_MSC_VER) || defined(__BORLANDC__)
792 typedef __int64 sqlite_int64;
793 typedef unsigned __int64 sqlite_uint64;
794 #else
795 typedef long long int sqlite_int64;
796 typedef unsigned long long int sqlite_uint64;
797 #endif
798 typedef sqlite_int64 sqlite3_int64;
799 typedef sqlite_uint64 sqlite3_uint64;
802 ** If compiling for a processor that lacks floating point support,
803 ** substitute integer for floating-point.
805 #ifdef SQLITE_OMIT_FLOATING_POINT
806 # define double sqlite3_int64
807 #endif
810 ** CAPI3REF: Closing A Database Connection
812 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
813 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
814 ** successfully destroyed and all associated resources are deallocated.
816 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
817 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
818 ** the [sqlite3] object prior to attempting to close the object. ^If
819 ** sqlite3_close() is called on a [database connection] that still has
820 ** outstanding [prepared statements] or [BLOB handles], then it returns
821 ** SQLITE_BUSY.
823 ** ^If [sqlite3_close()] is invoked while a transaction is open,
824 ** the transaction is automatically rolled back.
826 ** The C parameter to [sqlite3_close(C)] must be either a NULL
827 ** pointer or an [sqlite3] object pointer obtained
828 ** from [sqlite3_open()], [sqlite3_open16()], or
829 ** [sqlite3_open_v2()], and not previously closed.
830 ** ^Calling sqlite3_close() with a NULL pointer argument is a
831 ** harmless no-op.
833 SQLITE_API int sqlite3_close(sqlite3 *);
836 ** The type for a callback function.
837 ** This is legacy and deprecated. It is included for historical
838 ** compatibility and is not documented.
840 typedef int (*sqlite3_callback)(void*,int,char**, char**);
843 ** CAPI3REF: One-Step Query Execution Interface
845 ** The sqlite3_exec() interface is a convenience wrapper around
846 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
847 ** that allows an application to run multiple statements of SQL
848 ** without having to use a lot of C code.
850 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
851 ** semicolon-separate SQL statements passed into its 2nd argument,
852 ** in the context of the [database connection] passed in as its 1st
853 ** argument. ^If the callback function of the 3rd argument to
854 ** sqlite3_exec() is not NULL, then it is invoked for each result row
855 ** coming out of the evaluated SQL statements. ^The 4th argument to
856 ** to sqlite3_exec() is relayed through to the 1st argument of each
857 ** callback invocation. ^If the callback pointer to sqlite3_exec()
858 ** is NULL, then no callback is ever invoked and result rows are
859 ** ignored.
861 ** ^If an error occurs while evaluating the SQL statements passed into
862 ** sqlite3_exec(), then execution of the current statement stops and
863 ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
864 ** is not NULL then any error message is written into memory obtained
865 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
866 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
867 ** on error message strings returned through the 5th parameter of
868 ** of sqlite3_exec() after the error message string is no longer needed.
869 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
870 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
871 ** NULL before returning.
873 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
874 ** routine returns SQLITE_ABORT without invoking the callback again and
875 ** without running any subsequent SQL statements.
877 ** ^The 2nd argument to the sqlite3_exec() callback function is the
878 ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
879 ** callback is an array of pointers to strings obtained as if from
880 ** [sqlite3_column_text()], one for each column. ^If an element of a
881 ** result row is NULL then the corresponding string pointer for the
882 ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
883 ** sqlite3_exec() callback is an array of pointers to strings where each
884 ** entry represents the name of corresponding result column as obtained
885 ** from [sqlite3_column_name()].
887 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
888 ** to an empty string, or a pointer that contains only whitespace and/or
889 ** SQL comments, then no SQL statements are evaluated and the database
890 ** is not changed.
892 ** Restrictions:
894 ** <ul>
895 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
896 ** is a valid and open [database connection].
897 ** <li> The application must not close [database connection] specified by
898 ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
899 ** <li> The application must not modify the SQL statement text passed into
900 ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
901 ** </ul>
903 SQLITE_API int sqlite3_exec(
904 sqlite3*, /* An open database */
905 const char *sql, /* SQL to be evaluated */
906 int (*callback)(void*,int,char**,char**), /* Callback function */
907 void *, /* 1st argument to callback */
908 char **errmsg /* Error msg written here */
912 ** CAPI3REF: Result Codes
913 ** KEYWORDS: SQLITE_OK {error code} {error codes}
914 ** KEYWORDS: {result code} {result codes}
916 ** Many SQLite functions return an integer result code from the set shown
917 ** here in order to indicates success or failure.
919 ** New error codes may be added in future versions of SQLite.
921 ** See also: [SQLITE_IOERR_READ | extended result codes]
923 #define SQLITE_OK 0 /* Successful result */
924 /* beginning-of-error-codes */
925 #define SQLITE_ERROR 1 /* SQL error or missing database */
926 #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
927 #define SQLITE_PERM 3 /* Access permission denied */
928 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
929 #define SQLITE_BUSY 5 /* The database file is locked */
930 #define SQLITE_LOCKED 6 /* A table in the database is locked */
931 #define SQLITE_NOMEM 7 /* A malloc() failed */
932 #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
933 #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
934 #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
935 #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
936 #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
937 #define SQLITE_FULL 13 /* Insertion failed because database is full */
938 #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
939 #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
940 #define SQLITE_EMPTY 16 /* Database is empty */
941 #define SQLITE_SCHEMA 17 /* The database schema changed */
942 #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
943 #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
944 #define SQLITE_MISMATCH 20 /* Data type mismatch */
945 #define SQLITE_MISUSE 21 /* Library used incorrectly */
946 #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
947 #define SQLITE_AUTH 23 /* Authorization denied */
948 #define SQLITE_FORMAT 24 /* Auxiliary database format error */
949 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
950 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
951 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
952 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
953 /* end-of-error-codes */
956 ** CAPI3REF: Extended Result Codes
957 ** KEYWORDS: {extended error code} {extended error codes}
958 ** KEYWORDS: {extended result code} {extended result codes}
960 ** In its default configuration, SQLite API routines return one of 26 integer
961 ** [SQLITE_OK | result codes]. However, experience has shown that many of
962 ** these result codes are too coarse-grained. They do not provide as
963 ** much information about problems as programmers might like. In an effort to
964 ** address this, newer versions of SQLite (version 3.3.8 and later) include
965 ** support for additional result codes that provide more detailed information
966 ** about errors. The extended result codes are enabled or disabled
967 ** on a per database connection basis using the
968 ** [sqlite3_extended_result_codes()] API.
970 ** Some of the available extended result codes are listed here.
971 ** One may expect the number of extended result codes will be expand
972 ** over time. Software that uses extended result codes should expect
973 ** to see new result codes in future releases of SQLite.
975 ** The SQLITE_OK result code will never be extended. It will always
976 ** be exactly zero.
978 #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
979 #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
980 #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
981 #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
982 #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
983 #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
984 #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
985 #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
986 #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
987 #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
988 #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
989 #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
990 #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
991 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
992 #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
993 #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
994 #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
995 #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
996 #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
997 #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
998 #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
999 #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
1000 #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
1003 ** CAPI3REF: Flags For File Open Operations
1005 ** These bit values are intended for use in the
1006 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1007 ** in the 4th parameter to the xOpen method of the
1008 ** [sqlite3_vfs] object.
1010 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
1011 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
1012 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
1013 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
1014 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
1015 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
1016 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
1017 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
1018 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
1019 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
1020 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
1021 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
1022 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
1023 #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
1024 #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
1025 #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
1026 #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
1027 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
1029 /* Reserved: 0x00F00000 */
1032 ** CAPI3REF: Device Characteristics
1034 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1035 ** object returns an integer which is a vector of the these
1036 ** bit values expressing I/O characteristics of the mass storage
1037 ** device that holds the file that the [sqlite3_io_methods]
1038 ** refers to.
1040 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1041 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1042 ** mean that writes of blocks that are nnn bytes in size and
1043 ** are aligned to an address which is an integer multiple of
1044 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1045 ** that when data is appended to a file, the data is appended
1046 ** first then the size of the file is extended, never the other
1047 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1048 ** information is written to disk in the same order as calls
1049 ** to xWrite().
1051 #define SQLITE_IOCAP_ATOMIC 0x00000001
1052 #define SQLITE_IOCAP_ATOMIC512 0x00000002
1053 #define SQLITE_IOCAP_ATOMIC1K 0x00000004
1054 #define SQLITE_IOCAP_ATOMIC2K 0x00000008
1055 #define SQLITE_IOCAP_ATOMIC4K 0x00000010
1056 #define SQLITE_IOCAP_ATOMIC8K 0x00000020
1057 #define SQLITE_IOCAP_ATOMIC16K 0x00000040
1058 #define SQLITE_IOCAP_ATOMIC32K 0x00000080
1059 #define SQLITE_IOCAP_ATOMIC64K 0x00000100
1060 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
1061 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
1062 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
1065 ** CAPI3REF: File Locking Levels
1067 ** SQLite uses one of these integer values as the second
1068 ** argument to calls it makes to the xLock() and xUnlock() methods
1069 ** of an [sqlite3_io_methods] object.
1071 #define SQLITE_LOCK_NONE 0
1072 #define SQLITE_LOCK_SHARED 1
1073 #define SQLITE_LOCK_RESERVED 2
1074 #define SQLITE_LOCK_PENDING 3
1075 #define SQLITE_LOCK_EXCLUSIVE 4
1078 ** CAPI3REF: Synchronization Type Flags
1080 ** When SQLite invokes the xSync() method of an
1081 ** [sqlite3_io_methods] object it uses a combination of
1082 ** these integer values as the second argument.
1084 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1085 ** sync operation only needs to flush data to mass storage. Inode
1086 ** information need not be flushed. If the lower four bits of the flag
1087 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1088 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1089 ** to use Mac OS X style fullsync instead of fsync().
1091 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1092 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1093 ** settings. The [synchronous pragma] determines when calls to the
1094 ** xSync VFS method occur and applies uniformly across all platforms.
1095 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1096 ** energetic or rigorous or forceful the sync operations are and
1097 ** only make a difference on Mac OSX for the default SQLite code.
1098 ** (Third-party VFS implementations might also make the distinction
1099 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1100 ** operating systems natively supported by SQLite, only Mac OSX
1101 ** cares about the difference.)
1103 #define SQLITE_SYNC_NORMAL 0x00002
1104 #define SQLITE_SYNC_FULL 0x00003
1105 #define SQLITE_SYNC_DATAONLY 0x00010
1108 ** CAPI3REF: OS Interface Open File Handle
1110 ** An [sqlite3_file] object represents an open file in the
1111 ** [sqlite3_vfs | OS interface layer]. Individual OS interface
1112 ** implementations will
1113 ** want to subclass this object by appending additional fields
1114 ** for their own use. The pMethods entry is a pointer to an
1115 ** [sqlite3_io_methods] object that defines methods for performing
1116 ** I/O operations on the open file.
1118 typedef struct sqlite3_file sqlite3_file;
1119 struct sqlite3_file {
1120 const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
1124 ** CAPI3REF: OS Interface File Virtual Methods Object
1126 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1127 ** [sqlite3_file] object (or, more commonly, a subclass of the
1128 ** [sqlite3_file] object) with a pointer to an instance of this object.
1129 ** This object defines the methods used to perform various operations
1130 ** against the open file represented by the [sqlite3_file] object.
1132 ** If the xOpen method sets the sqlite3_file.pMethods element
1133 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1134 ** may be invoked even if the xOpen reported that it failed. The
1135 ** only way to prevent a call to xClose following a failed xOpen
1136 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1138 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1139 ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
1140 ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
1141 ** flag may be ORed in to indicate that only the data of the file
1142 ** and not its inode needs to be synced.
1144 ** The integer values to xLock() and xUnlock() are one of
1145 ** <ul>
1146 ** <li> [SQLITE_LOCK_NONE],
1147 ** <li> [SQLITE_LOCK_SHARED],
1148 ** <li> [SQLITE_LOCK_RESERVED],
1149 ** <li> [SQLITE_LOCK_PENDING], or
1150 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1151 ** </ul>
1152 ** xLock() increases the lock. xUnlock() decreases the lock.
1153 ** The xCheckReservedLock() method checks whether any database connection,
1154 ** either in this process or in some other process, is holding a RESERVED,
1155 ** PENDING, or EXCLUSIVE lock on the file. It returns true
1156 ** if such a lock exists and false otherwise.
1158 ** The xFileControl() method is a generic interface that allows custom
1159 ** VFS implementations to directly control an open file using the
1160 ** [sqlite3_file_control()] interface. The second "op" argument is an
1161 ** integer opcode. The third argument is a generic pointer intended to
1162 ** point to a structure that may contain arguments or space in which to
1163 ** write return values. Potential uses for xFileControl() might be
1164 ** functions to enable blocking locks with timeouts, to change the
1165 ** locking strategy (for example to use dot-file locks), to inquire
1166 ** about the status of a lock, or to break stale locks. The SQLite
1167 ** core reserves all opcodes less than 100 for its own use.
1168 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1169 ** Applications that define a custom xFileControl method should use opcodes
1170 ** greater than 100 to avoid conflicts. VFS implementations should
1171 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1172 ** recognize.
1174 ** The xSectorSize() method returns the sector size of the
1175 ** device that underlies the file. The sector size is the
1176 ** minimum write that can be performed without disturbing
1177 ** other bytes in the file. The xDeviceCharacteristics()
1178 ** method returns a bit vector describing behaviors of the
1179 ** underlying device:
1181 ** <ul>
1182 ** <li> [SQLITE_IOCAP_ATOMIC]
1183 ** <li> [SQLITE_IOCAP_ATOMIC512]
1184 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1185 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1186 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1187 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1188 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1189 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1190 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1191 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1192 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1193 ** </ul>
1195 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1196 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1197 ** mean that writes of blocks that are nnn bytes in size and
1198 ** are aligned to an address which is an integer multiple of
1199 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1200 ** that when data is appended to a file, the data is appended
1201 ** first then the size of the file is extended, never the other
1202 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1203 ** information is written to disk in the same order as calls
1204 ** to xWrite().
1206 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1207 ** in the unread portions of the buffer with zeros. A VFS that
1208 ** fails to zero-fill short reads might seem to work. However,
1209 ** failure to zero-fill short reads will eventually lead to
1210 ** database corruption.
1212 typedef struct sqlite3_io_methods sqlite3_io_methods;
1213 struct sqlite3_io_methods {
1214 int iVersion;
1215 int (*xClose)(sqlite3_file*);
1216 int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1217 int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1218 int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1219 int (*xSync)(sqlite3_file*, int flags);
1220 int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1221 int (*xLock)(sqlite3_file*, int);
1222 int (*xUnlock)(sqlite3_file*, int);
1223 int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1224 int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1225 int (*xSectorSize)(sqlite3_file*);
1226 int (*xDeviceCharacteristics)(sqlite3_file*);
1227 /* Methods above are valid for version 1 */
1228 int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1229 int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1230 void (*xShmBarrier)(sqlite3_file*);
1231 int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1232 /* Methods above are valid for version 2 */
1233 /* Additional methods may be added in future releases */
1237 ** CAPI3REF: Standard File Control Opcodes
1239 ** These integer constants are opcodes for the xFileControl method
1240 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1241 ** interface.
1243 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1244 ** opcode causes the xFileControl method to write the current state of
1245 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1246 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1247 ** into an integer that the pArg argument points to. This capability
1248 ** is used during testing and only needs to be supported when SQLITE_TEST
1249 ** is defined.
1251 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1252 ** layer a hint of how large the database file will grow to be during the
1253 ** current transaction. This hint is not guaranteed to be accurate but it
1254 ** is often close. The underlying VFS might choose to preallocate database
1255 ** file space based on this hint in order to help writes to the database
1256 ** file run faster.
1258 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1259 ** extends and truncates the database file in chunks of a size specified
1260 ** by the user. The fourth argument to [sqlite3_file_control()] should
1261 ** point to an integer (type int) containing the new chunk-size to use
1262 ** for the nominated database. Allocating database file space in large
1263 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1264 ** improve performance on some systems.
1266 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1267 ** to the [sqlite3_file] object associated with a particular database
1268 ** connection. See the [sqlite3_file_control()] documentation for
1269 ** additional information.
1271 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1272 ** SQLite and sent to all VFSes in place of a call to the xSync method
1273 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1274 ** Some specialized VFSes need this signal in order to operate correctly
1275 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
1276 ** VFSes do not need this signal and should silently ignore this opcode.
1277 ** Applications should not call [sqlite3_file_control()] with this
1278 ** opcode as doing so may disrupt the operation of the specialized VFSes
1279 ** that do require it.
1281 #define SQLITE_FCNTL_LOCKSTATE 1
1282 #define SQLITE_GET_LOCKPROXYFILE 2
1283 #define SQLITE_SET_LOCKPROXYFILE 3
1284 #define SQLITE_LAST_ERRNO 4
1285 #define SQLITE_FCNTL_SIZE_HINT 5
1286 #define SQLITE_FCNTL_CHUNK_SIZE 6
1287 #define SQLITE_FCNTL_FILE_POINTER 7
1288 #define SQLITE_FCNTL_SYNC_OMITTED 8
1292 ** CAPI3REF: Mutex Handle
1294 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1295 ** abstract type for a mutex object. The SQLite core never looks
1296 ** at the internal representation of an [sqlite3_mutex]. It only
1297 ** deals with pointers to the [sqlite3_mutex] object.
1299 ** Mutexes are created using [sqlite3_mutex_alloc()].
1301 typedef struct sqlite3_mutex sqlite3_mutex;
1304 ** CAPI3REF: OS Interface Object
1306 ** An instance of the sqlite3_vfs object defines the interface between
1307 ** the SQLite core and the underlying operating system. The "vfs"
1308 ** in the name of the object stands for "virtual file system".
1310 ** The value of the iVersion field is initially 1 but may be larger in
1311 ** future versions of SQLite. Additional fields may be appended to this
1312 ** object when the iVersion value is increased. Note that the structure
1313 ** of the sqlite3_vfs object changes in the transaction between
1314 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1315 ** modified.
1317 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1318 ** structure used by this VFS. mxPathname is the maximum length of
1319 ** a pathname in this VFS.
1321 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1322 ** the pNext pointer. The [sqlite3_vfs_register()]
1323 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1324 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1325 ** searches the list. Neither the application code nor the VFS
1326 ** implementation should use the pNext pointer.
1328 ** The pNext field is the only field in the sqlite3_vfs
1329 ** structure that SQLite will ever modify. SQLite will only access
1330 ** or modify this field while holding a particular static mutex.
1331 ** The application should never modify anything within the sqlite3_vfs
1332 ** object once the object has been registered.
1334 ** The zName field holds the name of the VFS module. The name must
1335 ** be unique across all VFS modules.
1337 ** ^SQLite guarantees that the zFilename parameter to xOpen
1338 ** is either a NULL pointer or string obtained
1339 ** from xFullPathname() with an optional suffix added.
1340 ** ^If a suffix is added to the zFilename parameter, it will
1341 ** consist of a single "-" character followed by no more than
1342 ** 10 alphanumeric and/or "-" characters.
1343 ** ^SQLite further guarantees that
1344 ** the string will be valid and unchanged until xClose() is
1345 ** called. Because of the previous sentence,
1346 ** the [sqlite3_file] can safely store a pointer to the
1347 ** filename if it needs to remember the filename for some reason.
1348 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1349 ** must invent its own temporary name for the file. ^Whenever the
1350 ** xFilename parameter is NULL it will also be the case that the
1351 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1353 ** The flags argument to xOpen() includes all bits set in
1354 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1355 ** or [sqlite3_open16()] is used, then flags includes at least
1356 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1357 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1358 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1360 ** ^(SQLite will also add one of the following flags to the xOpen()
1361 ** call, depending on the object being opened:
1363 ** <ul>
1364 ** <li> [SQLITE_OPEN_MAIN_DB]
1365 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1366 ** <li> [SQLITE_OPEN_TEMP_DB]
1367 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1368 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1369 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1370 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1371 ** <li> [SQLITE_OPEN_WAL]
1372 ** </ul>)^
1374 ** The file I/O implementation can use the object type flags to
1375 ** change the way it deals with files. For example, an application
1376 ** that does not care about crash recovery or rollback might make
1377 ** the open of a journal file a no-op. Writes to this journal would
1378 ** also be no-ops, and any attempt to read the journal would return
1379 ** SQLITE_IOERR. Or the implementation might recognize that a database
1380 ** file will be doing page-aligned sector reads and writes in a random
1381 ** order and set up its I/O subsystem accordingly.
1383 ** SQLite might also add one of the following flags to the xOpen method:
1385 ** <ul>
1386 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1387 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1388 ** </ul>
1390 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1391 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1392 ** will be set for TEMP databases and their journals, transient
1393 ** databases, and subjournals.
1395 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1396 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1397 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1398 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1399 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1400 ** be created, and that it is an error if it already exists.
1401 ** It is <i>not</i> used to indicate the file should be opened
1402 ** for exclusive access.
1404 ** ^At least szOsFile bytes of memory are allocated by SQLite
1405 ** to hold the [sqlite3_file] structure passed as the third
1406 ** argument to xOpen. The xOpen method does not have to
1407 ** allocate the structure; it should just fill it in. Note that
1408 ** the xOpen method must set the sqlite3_file.pMethods to either
1409 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1410 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1411 ** element will be valid after xOpen returns regardless of the success
1412 ** or failure of the xOpen call.
1414 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1415 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1416 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1417 ** to test whether a file is at least readable. The file can be a
1418 ** directory.
1420 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1421 ** output buffer xFullPathname. The exact size of the output buffer
1422 ** is also passed as a parameter to both methods. If the output buffer
1423 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1424 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1425 ** to prevent this by setting mxPathname to a sufficiently large value.
1427 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1428 ** interfaces are not strictly a part of the filesystem, but they are
1429 ** included in the VFS structure for completeness.
1430 ** The xRandomness() function attempts to return nBytes bytes
1431 ** of good-quality randomness into zOut. The return value is
1432 ** the actual number of bytes of randomness obtained.
1433 ** The xSleep() method causes the calling thread to sleep for at
1434 ** least the number of microseconds given. ^The xCurrentTime()
1435 ** method returns a Julian Day Number for the current date and time as
1436 ** a floating point value.
1437 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1438 ** Day Number multipled by 86400000 (the number of milliseconds in
1439 ** a 24-hour day).
1440 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1441 ** date and time if that method is available (if iVersion is 2 or
1442 ** greater and the function pointer is not NULL) and will fall back
1443 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1445 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1446 ** are not used by the SQLite core. These optional interfaces are provided
1447 ** by some VFSes to facilitate testing of the VFS code. By overriding
1448 ** system calls with functions under its control, a test program can
1449 ** simulate faults and error conditions that would otherwise be difficult
1450 ** or impossible to induce. The set of system calls that can be overridden
1451 ** varies from one VFS to another, and from one version of the same VFS to the
1452 ** next. Applications that use these interfaces must be prepared for any
1453 ** or all of these interfaces to be NULL or for their behavior to change
1454 ** from one release to the next. Applications must not attempt to access
1455 ** any of these methods if the iVersion of the VFS is less than 3.
1457 typedef struct sqlite3_vfs sqlite3_vfs;
1458 typedef void (*sqlite3_syscall_ptr)(void);
1459 struct sqlite3_vfs {
1460 int iVersion; /* Structure version number (currently 3) */
1461 int szOsFile; /* Size of subclassed sqlite3_file */
1462 int mxPathname; /* Maximum file pathname length */
1463 sqlite3_vfs *pNext; /* Next registered VFS */
1464 const char *zName; /* Name of this virtual file system */
1465 void *pAppData; /* Pointer to application-specific data */
1466 int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1467 int flags, int *pOutFlags);
1468 int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1469 int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1470 int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1471 void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1472 void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1473 void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1474 void (*xDlClose)(sqlite3_vfs*, void*);
1475 int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1476 int (*xSleep)(sqlite3_vfs*, int microseconds);
1477 int (*xCurrentTime)(sqlite3_vfs*, double*);
1478 int (*xGetLastError)(sqlite3_vfs*, int, char *);
1480 ** The methods above are in version 1 of the sqlite_vfs object
1481 ** definition. Those that follow are added in version 2 or later
1483 int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1485 ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1486 ** Those below are for version 3 and greater.
1488 int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1489 sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1490 const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1492 ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1493 ** New fields may be appended in figure versions. The iVersion
1494 ** value will increment whenever this happens.
1499 ** CAPI3REF: Flags for the xAccess VFS method
1501 ** These integer constants can be used as the third parameter to
1502 ** the xAccess method of an [sqlite3_vfs] object. They determine
1503 ** what kind of permissions the xAccess method is looking for.
1504 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1505 ** simply checks whether the file exists.
1506 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1507 ** checks whether the named directory is both readable and writable
1508 ** (in other words, if files can be added, removed, and renamed within
1509 ** the directory).
1510 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1511 ** [temp_store_directory pragma], though this could change in a future
1512 ** release of SQLite.
1513 ** With SQLITE_ACCESS_READ, the xAccess method
1514 ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1515 ** currently unused, though it might be used in a future release of
1516 ** SQLite.
1518 #define SQLITE_ACCESS_EXISTS 0
1519 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
1520 #define SQLITE_ACCESS_READ 2 /* Unused */
1523 ** CAPI3REF: Flags for the xShmLock VFS method
1525 ** These integer constants define the various locking operations
1526 ** allowed by the xShmLock method of [sqlite3_io_methods]. The
1527 ** following are the only legal combinations of flags to the
1528 ** xShmLock method:
1530 ** <ul>
1531 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1532 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1533 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1534 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1535 ** </ul>
1537 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1538 ** was given no the corresponding lock.
1540 ** The xShmLock method can transition between unlocked and SHARED or
1541 ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1542 ** and EXCLUSIVE.
1544 #define SQLITE_SHM_UNLOCK 1
1545 #define SQLITE_SHM_LOCK 2
1546 #define SQLITE_SHM_SHARED 4
1547 #define SQLITE_SHM_EXCLUSIVE 8
1550 ** CAPI3REF: Maximum xShmLock index
1552 ** The xShmLock method on [sqlite3_io_methods] may use values
1553 ** between 0 and this upper bound as its "offset" argument.
1554 ** The SQLite core will never attempt to acquire or release a
1555 ** lock outside of this range
1557 #define SQLITE_SHM_NLOCK 8
1561 ** CAPI3REF: Initialize The SQLite Library
1563 ** ^The sqlite3_initialize() routine initializes the
1564 ** SQLite library. ^The sqlite3_shutdown() routine
1565 ** deallocates any resources that were allocated by sqlite3_initialize().
1566 ** These routines are designed to aid in process initialization and
1567 ** shutdown on embedded systems. Workstation applications using
1568 ** SQLite normally do not need to invoke either of these routines.
1570 ** A call to sqlite3_initialize() is an "effective" call if it is
1571 ** the first time sqlite3_initialize() is invoked during the lifetime of
1572 ** the process, or if it is the first time sqlite3_initialize() is invoked
1573 ** following a call to sqlite3_shutdown(). ^(Only an effective call
1574 ** of sqlite3_initialize() does any initialization. All other calls
1575 ** are harmless no-ops.)^
1577 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1578 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1579 ** an effective call to sqlite3_shutdown() does any deinitialization.
1580 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1582 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1583 ** is not. The sqlite3_shutdown() interface must only be called from a
1584 ** single thread. All open [database connections] must be closed and all
1585 ** other SQLite resources must be deallocated prior to invoking
1586 ** sqlite3_shutdown().
1588 ** Among other things, ^sqlite3_initialize() will invoke
1589 ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1590 ** will invoke sqlite3_os_end().
1592 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1593 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1594 ** the library (perhaps it is unable to allocate a needed resource such
1595 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1597 ** ^The sqlite3_initialize() routine is called internally by many other
1598 ** SQLite interfaces so that an application usually does not need to
1599 ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1600 ** calls sqlite3_initialize() so the SQLite library will be automatically
1601 ** initialized when [sqlite3_open()] is called if it has not be initialized
1602 ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1603 ** compile-time option, then the automatic calls to sqlite3_initialize()
1604 ** are omitted and the application must call sqlite3_initialize() directly
1605 ** prior to using any other SQLite interface. For maximum portability,
1606 ** it is recommended that applications always invoke sqlite3_initialize()
1607 ** directly prior to using any other SQLite interface. Future releases
1608 ** of SQLite may require this. In other words, the behavior exhibited
1609 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1610 ** default behavior in some future release of SQLite.
1612 ** The sqlite3_os_init() routine does operating-system specific
1613 ** initialization of the SQLite library. The sqlite3_os_end()
1614 ** routine undoes the effect of sqlite3_os_init(). Typical tasks
1615 ** performed by these routines include allocation or deallocation
1616 ** of static resources, initialization of global variables,
1617 ** setting up a default [sqlite3_vfs] module, or setting up
1618 ** a default configuration using [sqlite3_config()].
1620 ** The application should never invoke either sqlite3_os_init()
1621 ** or sqlite3_os_end() directly. The application should only invoke
1622 ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1623 ** interface is called automatically by sqlite3_initialize() and
1624 ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1625 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1626 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1627 ** When [custom builds | built for other platforms]
1628 ** (using the [SQLITE_OS_OTHER=1] compile-time
1629 ** option) the application must supply a suitable implementation for
1630 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1631 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1632 ** must return [SQLITE_OK] on success and some other [error code] upon
1633 ** failure.
1635 SQLITE_API int sqlite3_initialize(void);
1636 SQLITE_API int sqlite3_shutdown(void);
1637 SQLITE_API int sqlite3_os_init(void);
1638 SQLITE_API int sqlite3_os_end(void);
1641 ** CAPI3REF: Configuring The SQLite Library
1643 ** The sqlite3_config() interface is used to make global configuration
1644 ** changes to SQLite in order to tune SQLite to the specific needs of
1645 ** the application. The default configuration is recommended for most
1646 ** applications and so this routine is usually not necessary. It is
1647 ** provided to support rare applications with unusual needs.
1649 ** The sqlite3_config() interface is not threadsafe. The application
1650 ** must insure that no other SQLite interfaces are invoked by other
1651 ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
1652 ** may only be invoked prior to library initialization using
1653 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1654 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1655 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1656 ** Note, however, that ^sqlite3_config() can be called as part of the
1657 ** implementation of an application-defined [sqlite3_os_init()].
1659 ** The first argument to sqlite3_config() is an integer
1660 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1661 ** what property of SQLite is to be configured. Subsequent arguments
1662 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1663 ** in the first argument.
1665 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1666 ** ^If the option is unknown or SQLite is unable to set the option
1667 ** then this routine returns a non-zero [error code].
1669 SQLITE_API int sqlite3_config(int, ...);
1672 ** CAPI3REF: Configure database connections
1674 ** The sqlite3_db_config() interface is used to make configuration
1675 ** changes to a [database connection]. The interface is similar to
1676 ** [sqlite3_config()] except that the changes apply to a single
1677 ** [database connection] (specified in the first argument).
1679 ** The second argument to sqlite3_db_config(D,V,...) is the
1680 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1681 ** that indicates what aspect of the [database connection] is being configured.
1682 ** Subsequent arguments vary depending on the configuration verb.
1684 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1685 ** the call is considered successful.
1687 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1690 ** CAPI3REF: Memory Allocation Routines
1692 ** An instance of this object defines the interface between SQLite
1693 ** and low-level memory allocation routines.
1695 ** This object is used in only one place in the SQLite interface.
1696 ** A pointer to an instance of this object is the argument to
1697 ** [sqlite3_config()] when the configuration option is
1698 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1699 ** By creating an instance of this object
1700 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1701 ** during configuration, an application can specify an alternative
1702 ** memory allocation subsystem for SQLite to use for all of its
1703 ** dynamic memory needs.
1705 ** Note that SQLite comes with several [built-in memory allocators]
1706 ** that are perfectly adequate for the overwhelming majority of applications
1707 ** and that this object is only useful to a tiny minority of applications
1708 ** with specialized memory allocation requirements. This object is
1709 ** also used during testing of SQLite in order to specify an alternative
1710 ** memory allocator that simulates memory out-of-memory conditions in
1711 ** order to verify that SQLite recovers gracefully from such
1712 ** conditions.
1714 ** The xMalloc and xFree methods must work like the
1715 ** malloc() and free() functions from the standard C library.
1716 ** The xRealloc method must work like realloc() from the standard C library
1717 ** with the exception that if the second argument to xRealloc is zero,
1718 ** xRealloc must be a no-op - it must not perform any allocation or
1719 ** deallocation. ^SQLite guarantees that the second argument to
1720 ** xRealloc is always a value returned by a prior call to xRoundup.
1721 ** And so in cases where xRoundup always returns a positive number,
1722 ** xRealloc can perform exactly as the standard library realloc() and
1723 ** still be in compliance with this specification.
1725 ** xSize should return the allocated size of a memory allocation
1726 ** previously obtained from xMalloc or xRealloc. The allocated size
1727 ** is always at least as big as the requested size but may be larger.
1729 ** The xRoundup method returns what would be the allocated size of
1730 ** a memory allocation given a particular requested size. Most memory
1731 ** allocators round up memory allocations at least to the next multiple
1732 ** of 8. Some allocators round up to a larger multiple or to a power of 2.
1733 ** Every memory allocation request coming in through [sqlite3_malloc()]
1734 ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
1735 ** that causes the corresponding memory allocation to fail.
1737 ** The xInit method initializes the memory allocator. (For example,
1738 ** it might allocate any require mutexes or initialize internal data
1739 ** structures. The xShutdown method is invoked (indirectly) by
1740 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1741 ** by xInit. The pAppData pointer is used as the only parameter to
1742 ** xInit and xShutdown.
1744 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1745 ** the xInit method, so the xInit method need not be threadsafe. The
1746 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1747 ** not need to be threadsafe either. For all other methods, SQLite
1748 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1749 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1750 ** it is by default) and so the methods are automatically serialized.
1751 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1752 ** methods must be threadsafe or else make their own arrangements for
1753 ** serialization.
1755 ** SQLite will never invoke xInit() more than once without an intervening
1756 ** call to xShutdown().
1758 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1759 struct sqlite3_mem_methods {
1760 void *(*xMalloc)(int); /* Memory allocation function */
1761 void (*xFree)(void*); /* Free a prior allocation */
1762 void *(*xRealloc)(void*,int); /* Resize an allocation */
1763 int (*xSize)(void*); /* Return the size of an allocation */
1764 int (*xRoundup)(int); /* Round up request size to allocation size */
1765 int (*xInit)(void*); /* Initialize the memory allocator */
1766 void (*xShutdown)(void*); /* Deinitialize the memory allocator */
1767 void *pAppData; /* Argument to xInit() and xShutdown() */
1771 ** CAPI3REF: Configuration Options
1773 ** These constants are the available integer configuration options that
1774 ** can be passed as the first argument to the [sqlite3_config()] interface.
1776 ** New configuration options may be added in future releases of SQLite.
1777 ** Existing configuration options might be discontinued. Applications
1778 ** should check the return code from [sqlite3_config()] to make sure that
1779 ** the call worked. The [sqlite3_config()] interface will return a
1780 ** non-zero [error code] if a discontinued or unsupported configuration option
1781 ** is invoked.
1783 ** <dl>
1784 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1785 ** <dd>There are no arguments to this option. ^This option sets the
1786 ** [threading mode] to Single-thread. In other words, it disables
1787 ** all mutexing and puts SQLite into a mode where it can only be used
1788 ** by a single thread. ^If SQLite is compiled with
1789 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1790 ** it is not possible to change the [threading mode] from its default
1791 ** value of Single-thread and so [sqlite3_config()] will return
1792 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1793 ** configuration option.</dd>
1795 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1796 ** <dd>There are no arguments to this option. ^This option sets the
1797 ** [threading mode] to Multi-thread. In other words, it disables
1798 ** mutexing on [database connection] and [prepared statement] objects.
1799 ** The application is responsible for serializing access to
1800 ** [database connections] and [prepared statements]. But other mutexes
1801 ** are enabled so that SQLite will be safe to use in a multi-threaded
1802 ** environment as long as no two threads attempt to use the same
1803 ** [database connection] at the same time. ^If SQLite is compiled with
1804 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1805 ** it is not possible to set the Multi-thread [threading mode] and
1806 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1807 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1809 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1810 ** <dd>There are no arguments to this option. ^This option sets the
1811 ** [threading mode] to Serialized. In other words, this option enables
1812 ** all mutexes including the recursive
1813 ** mutexes on [database connection] and [prepared statement] objects.
1814 ** In this mode (which is the default when SQLite is compiled with
1815 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1816 ** to [database connections] and [prepared statements] so that the
1817 ** application is free to use the same [database connection] or the
1818 ** same [prepared statement] in different threads at the same time.
1819 ** ^If SQLite is compiled with
1820 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1821 ** it is not possible to set the Serialized [threading mode] and
1822 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1823 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1825 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1826 ** <dd> ^(This option takes a single argument which is a pointer to an
1827 ** instance of the [sqlite3_mem_methods] structure. The argument specifies
1828 ** alternative low-level memory allocation routines to be used in place of
1829 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1830 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1831 ** before the [sqlite3_config()] call returns.</dd>
1833 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1834 ** <dd> ^(This option takes a single argument which is a pointer to an
1835 ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
1836 ** structure is filled with the currently defined memory allocation routines.)^
1837 ** This option can be used to overload the default memory allocation
1838 ** routines with a wrapper that simulations memory allocation failure or
1839 ** tracks memory usage, for example. </dd>
1841 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1842 ** <dd> ^This option takes single argument of type int, interpreted as a
1843 ** boolean, which enables or disables the collection of memory allocation
1844 ** statistics. ^(When memory allocation statistics are disabled, the
1845 ** following SQLite interfaces become non-operational:
1846 ** <ul>
1847 ** <li> [sqlite3_memory_used()]
1848 ** <li> [sqlite3_memory_highwater()]
1849 ** <li> [sqlite3_soft_heap_limit64()]
1850 ** <li> [sqlite3_status()]
1851 ** </ul>)^
1852 ** ^Memory allocation statistics are enabled by default unless SQLite is
1853 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1854 ** allocation statistics are disabled by default.
1855 ** </dd>
1857 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1858 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1859 ** scratch memory. There are three arguments: A pointer an 8-byte
1860 ** aligned memory buffer from which the scratch allocations will be
1861 ** drawn, the size of each scratch allocation (sz),
1862 ** and the maximum number of scratch allocations (N). The sz
1863 ** argument must be a multiple of 16.
1864 ** The first argument must be a pointer to an 8-byte aligned buffer
1865 ** of at least sz*N bytes of memory.
1866 ** ^SQLite will use no more than two scratch buffers per thread. So
1867 ** N should be set to twice the expected maximum number of threads.
1868 ** ^SQLite will never require a scratch buffer that is more than 6
1869 ** times the database page size. ^If SQLite needs needs additional
1870 ** scratch memory beyond what is provided by this configuration option, then
1871 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1873 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1874 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1875 ** the database page cache with the default page cache implemenation.
1876 ** This configuration should not be used if an application-define page
1877 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1878 ** There are three arguments to this option: A pointer to 8-byte aligned
1879 ** memory, the size of each page buffer (sz), and the number of pages (N).
1880 ** The sz argument should be the size of the largest database page
1881 ** (a power of two between 512 and 32768) plus a little extra for each
1882 ** page header. ^The page header size is 20 to 40 bytes depending on
1883 ** the host architecture. ^It is harmless, apart from the wasted memory,
1884 ** to make sz a little too large. The first
1885 ** argument should point to an allocation of at least sz*N bytes of memory.
1886 ** ^SQLite will use the memory provided by the first argument to satisfy its
1887 ** memory needs for the first N pages that it adds to cache. ^If additional
1888 ** page cache memory is needed beyond what is provided by this option, then
1889 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1890 ** The pointer in the first argument must
1891 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1892 ** will be undefined.</dd>
1894 ** <dt>SQLITE_CONFIG_HEAP</dt>
1895 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1896 ** for all of its dynamic memory allocation needs beyond those provided
1897 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1898 ** There are three arguments: An 8-byte aligned pointer to the memory,
1899 ** the number of bytes in the memory buffer, and the minimum allocation size.
1900 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1901 ** to using its default memory allocator (the system malloc() implementation),
1902 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
1903 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1904 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1905 ** allocator is engaged to handle all of SQLites memory allocation needs.
1906 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1907 ** boundary or subsequent behavior of SQLite will be undefined.
1908 ** The minimum allocation size is capped at 2^12. Reasonable values
1909 ** for the minimum allocation size are 2^5 through 2^8.</dd>
1911 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1912 ** <dd> ^(This option takes a single argument which is a pointer to an
1913 ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
1914 ** alternative low-level mutex routines to be used in place
1915 ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
1916 ** content of the [sqlite3_mutex_methods] structure before the call to
1917 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1918 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1919 ** the entire mutexing subsystem is omitted from the build and hence calls to
1920 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1921 ** return [SQLITE_ERROR].</dd>
1923 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1924 ** <dd> ^(This option takes a single argument which is a pointer to an
1925 ** instance of the [sqlite3_mutex_methods] structure. The
1926 ** [sqlite3_mutex_methods]
1927 ** structure is filled with the currently defined mutex routines.)^
1928 ** This option can be used to overload the default mutex allocation
1929 ** routines with a wrapper used to track mutex usage for performance
1930 ** profiling or testing, for example. ^If SQLite is compiled with
1931 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1932 ** the entire mutexing subsystem is omitted from the build and hence calls to
1933 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1934 ** return [SQLITE_ERROR].</dd>
1936 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1937 ** <dd> ^(This option takes two arguments that determine the default
1938 ** memory allocation for the lookaside memory allocator on each
1939 ** [database connection]. The first argument is the
1940 ** size of each lookaside buffer slot and the second is the number of
1941 ** slots allocated to each database connection.)^ ^(This option sets the
1942 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1943 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1944 ** configuration on individual connections.)^ </dd>
1946 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1947 ** <dd> ^(This option takes a single argument which is a pointer to
1948 ** an [sqlite3_pcache_methods] object. This object specifies the interface
1949 ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
1950 ** object and uses it for page cache memory allocations.</dd>
1952 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1953 ** <dd> ^(This option takes a single argument which is a pointer to an
1954 ** [sqlite3_pcache_methods] object. SQLite copies of the current
1955 ** page cache implementation into that object.)^ </dd>
1957 ** <dt>SQLITE_CONFIG_LOG</dt>
1958 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1959 ** function with a call signature of void(*)(void*,int,const char*),
1960 ** and a pointer to void. ^If the function pointer is not NULL, it is
1961 ** invoked by [sqlite3_log()] to process each logging event. ^If the
1962 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1963 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1964 ** passed through as the first parameter to the application-defined logger
1965 ** function whenever that function is invoked. ^The second parameter to
1966 ** the logger function is a copy of the first parameter to the corresponding
1967 ** [sqlite3_log()] call and is intended to be a [result code] or an
1968 ** [extended result code]. ^The third parameter passed to the logger is
1969 ** log message after formatting via [sqlite3_snprintf()].
1970 ** The SQLite logging interface is not reentrant; the logger function
1971 ** supplied by the application must not invoke any SQLite interface.
1972 ** In a multi-threaded application, the application-defined logger
1973 ** function must be threadsafe. </dd>
1975 ** </dl>
1977 #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
1978 #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
1979 #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
1980 #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
1981 #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
1982 #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
1983 #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
1984 #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
1985 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
1986 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
1987 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
1988 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1989 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
1990 #define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */
1991 #define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */
1992 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
1995 ** CAPI3REF: Database Connection Configuration Options
1997 ** These constants are the available integer configuration options that
1998 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2000 ** New configuration options may be added in future releases of SQLite.
2001 ** Existing configuration options might be discontinued. Applications
2002 ** should check the return code from [sqlite3_db_config()] to make sure that
2003 ** the call worked. ^The [sqlite3_db_config()] interface will return a
2004 ** non-zero [error code] if a discontinued or unsupported configuration option
2005 ** is invoked.
2007 ** <dl>
2008 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2009 ** <dd> ^This option takes three additional arguments that determine the
2010 ** [lookaside memory allocator] configuration for the [database connection].
2011 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2012 ** pointer to a memory buffer to use for lookaside memory.
2013 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2014 ** may be NULL in which case SQLite will allocate the
2015 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2016 ** size of each lookaside buffer slot. ^The third argument is the number of
2017 ** slots. The size of the buffer in the first argument must be greater than
2018 ** or equal to the product of the second and third arguments. The buffer
2019 ** must be aligned to an 8-byte boundary. ^If the second argument to
2020 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2021 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
2022 ** configuration for a database connection can only be changed when that
2023 ** connection is not currently using lookaside memory, or in other words
2024 ** when the "current value" returned by
2025 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2026 ** Any attempt to change the lookaside memory configuration when lookaside
2027 ** memory is in use leaves the configuration unchanged and returns
2028 ** [SQLITE_BUSY].)^</dd>
2030 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2031 ** <dd> ^This option is used to enable or disable the enforcement of
2032 ** [foreign key constraints]. There should be two additional arguments.
2033 ** The first argument is an integer which is 0 to disable FK enforcement,
2034 ** positive to enable FK enforcement or negative to leave FK enforcement
2035 ** unchanged. The second parameter is a pointer to an integer into which
2036 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2037 ** following this call. The second parameter may be a NULL pointer, in
2038 ** which case the FK enforcement setting is not reported back. </dd>
2040 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2041 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2042 ** There should be two additional arguments.
2043 ** The first argument is an integer which is 0 to disable triggers,
2044 ** positive to enable triggers or negative to leave the setting unchanged.
2045 ** The second parameter is a pointer to an integer into which
2046 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2047 ** following this call. The second parameter may be a NULL pointer, in
2048 ** which case the trigger setting is not reported back. </dd>
2050 ** </dl>
2052 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
2053 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
2054 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
2058 ** CAPI3REF: Enable Or Disable Extended Result Codes
2060 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2061 ** [extended result codes] feature of SQLite. ^The extended result
2062 ** codes are disabled by default for historical compatibility.
2064 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2067 ** CAPI3REF: Last Insert Rowid
2069 ** ^Each entry in an SQLite table has a unique 64-bit signed
2070 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2071 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2072 ** names are not also used by explicitly declared columns. ^If
2073 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2074 ** is another alias for the rowid.
2076 ** ^This routine returns the [rowid] of the most recent
2077 ** successful [INSERT] into the database from the [database connection]
2078 ** in the first argument. ^If no successful [INSERT]s
2079 ** have ever occurred on that database connection, zero is returned.
2081 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
2082 ** row is returned by this routine as long as the trigger is running.
2083 ** But once the trigger terminates, the value returned by this routine
2084 ** reverts to the last value inserted before the trigger fired.)^
2086 ** ^An [INSERT] that fails due to a constraint violation is not a
2087 ** successful [INSERT] and does not change the value returned by this
2088 ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2089 ** and INSERT OR ABORT make no changes to the return value of this
2090 ** routine when their insertion fails. ^(When INSERT OR REPLACE
2091 ** encounters a constraint violation, it does not fail. The
2092 ** INSERT continues to completion after deleting rows that caused
2093 ** the constraint problem so INSERT OR REPLACE will always change
2094 ** the return value of this interface.)^
2096 ** ^For the purposes of this routine, an [INSERT] is considered to
2097 ** be successful even if it is subsequently rolled back.
2099 ** This function is accessible to SQL statements via the
2100 ** [last_insert_rowid() SQL function].
2102 ** If a separate thread performs a new [INSERT] on the same
2103 ** database connection while the [sqlite3_last_insert_rowid()]
2104 ** function is running and thus changes the last insert [rowid],
2105 ** then the value returned by [sqlite3_last_insert_rowid()] is
2106 ** unpredictable and might not equal either the old or the new
2107 ** last insert [rowid].
2109 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2112 ** CAPI3REF: Count The Number Of Rows Modified
2114 ** ^This function returns the number of database rows that were changed
2115 ** or inserted or deleted by the most recently completed SQL statement
2116 ** on the [database connection] specified by the first parameter.
2117 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2118 ** or [DELETE] statement are counted. Auxiliary changes caused by
2119 ** triggers or [foreign key actions] are not counted.)^ Use the
2120 ** [sqlite3_total_changes()] function to find the total number of changes
2121 ** including changes caused by triggers and foreign key actions.
2123 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2124 ** are not counted. Only real table changes are counted.
2126 ** ^(A "row change" is a change to a single row of a single table
2127 ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
2128 ** are changed as side effects of [REPLACE] constraint resolution,
2129 ** rollback, ABORT processing, [DROP TABLE], or by any other
2130 ** mechanisms do not count as direct row changes.)^
2132 ** A "trigger context" is a scope of execution that begins and
2133 ** ends with the script of a [CREATE TRIGGER | trigger].
2134 ** Most SQL statements are
2135 ** evaluated outside of any trigger. This is the "top level"
2136 ** trigger context. If a trigger fires from the top level, a
2137 ** new trigger context is entered for the duration of that one
2138 ** trigger. Subtriggers create subcontexts for their duration.
2140 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2141 ** not create a new trigger context.
2143 ** ^This function returns the number of direct row changes in the
2144 ** most recent INSERT, UPDATE, or DELETE statement within the same
2145 ** trigger context.
2147 ** ^Thus, when called from the top level, this function returns the
2148 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2149 ** that also occurred at the top level. ^(Within the body of a trigger,
2150 ** the sqlite3_changes() interface can be called to find the number of
2151 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2152 ** statement within the body of the same trigger.
2153 ** However, the number returned does not include changes
2154 ** caused by subtriggers since those have their own context.)^
2156 ** See also the [sqlite3_total_changes()] interface, the
2157 ** [count_changes pragma], and the [changes() SQL function].
2159 ** If a separate thread makes changes on the same database connection
2160 ** while [sqlite3_changes()] is running then the value returned
2161 ** is unpredictable and not meaningful.
2163 SQLITE_API int sqlite3_changes(sqlite3*);
2166 ** CAPI3REF: Total Number Of Rows Modified
2168 ** ^This function returns the number of row changes caused by [INSERT],
2169 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2170 ** ^(The count returned by sqlite3_total_changes() includes all changes
2171 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2172 ** [foreign key actions]. However,
2173 ** the count does not include changes used to implement [REPLACE] constraints,
2174 ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
2175 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2176 ** though if the INSTEAD OF trigger makes changes of its own, those changes
2177 ** are counted.)^
2178 ** ^The sqlite3_total_changes() function counts the changes as soon as
2179 ** the statement that makes them is completed (when the statement handle
2180 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2182 ** See also the [sqlite3_changes()] interface, the
2183 ** [count_changes pragma], and the [total_changes() SQL function].
2185 ** If a separate thread makes changes on the same database connection
2186 ** while [sqlite3_total_changes()] is running then the value
2187 ** returned is unpredictable and not meaningful.
2189 SQLITE_API int sqlite3_total_changes(sqlite3*);
2192 ** CAPI3REF: Interrupt A Long-Running Query
2194 ** ^This function causes any pending database operation to abort and
2195 ** return at its earliest opportunity. This routine is typically
2196 ** called in response to a user action such as pressing "Cancel"
2197 ** or Ctrl-C where the user wants a long query operation to halt
2198 ** immediately.
2200 ** ^It is safe to call this routine from a thread different from the
2201 ** thread that is currently running the database operation. But it
2202 ** is not safe to call this routine with a [database connection] that
2203 ** is closed or might close before sqlite3_interrupt() returns.
2205 ** ^If an SQL operation is very nearly finished at the time when
2206 ** sqlite3_interrupt() is called, then it might not have an opportunity
2207 ** to be interrupted and might continue to completion.
2209 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2210 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2211 ** that is inside an explicit transaction, then the entire transaction
2212 ** will be rolled back automatically.
2214 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2215 ** SQL statements on [database connection] D complete. ^Any new SQL statements
2216 ** that are started after the sqlite3_interrupt() call and before the
2217 ** running statements reaches zero are interrupted as if they had been
2218 ** running prior to the sqlite3_interrupt() call. ^New SQL statements
2219 ** that are started after the running statement count reaches zero are
2220 ** not effected by the sqlite3_interrupt().
2221 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2222 ** SQL statements is a no-op and has no effect on SQL statements
2223 ** that are started after the sqlite3_interrupt() call returns.
2225 ** If the database connection closes while [sqlite3_interrupt()]
2226 ** is running then bad things will likely happen.
2228 SQLITE_API void sqlite3_interrupt(sqlite3*);
2231 ** CAPI3REF: Determine If An SQL Statement Is Complete
2233 ** These routines are useful during command-line input to determine if the
2234 ** currently entered text seems to form a complete SQL statement or
2235 ** if additional input is needed before sending the text into
2236 ** SQLite for parsing. ^These routines return 1 if the input string
2237 ** appears to be a complete SQL statement. ^A statement is judged to be
2238 ** complete if it ends with a semicolon token and is not a prefix of a
2239 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
2240 ** string literals or quoted identifier names or comments are not
2241 ** independent tokens (they are part of the token in which they are
2242 ** embedded) and thus do not count as a statement terminator. ^Whitespace
2243 ** and comments that follow the final semicolon are ignored.
2245 ** ^These routines return 0 if the statement is incomplete. ^If a
2246 ** memory allocation fails, then SQLITE_NOMEM is returned.
2248 ** ^These routines do not parse the SQL statements thus
2249 ** will not detect syntactically incorrect SQL.
2251 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2252 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2253 ** automatically by sqlite3_complete16(). If that initialization fails,
2254 ** then the return value from sqlite3_complete16() will be non-zero
2255 ** regardless of whether or not the input SQL is complete.)^
2257 ** The input to [sqlite3_complete()] must be a zero-terminated
2258 ** UTF-8 string.
2260 ** The input to [sqlite3_complete16()] must be a zero-terminated
2261 ** UTF-16 string in native byte order.
2263 SQLITE_API int sqlite3_complete(const char *sql);
2264 SQLITE_API int sqlite3_complete16(const void *sql);
2267 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2269 ** ^This routine sets a callback function that might be invoked whenever
2270 ** an attempt is made to open a database table that another thread
2271 ** or process has locked.
2273 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2274 ** is returned immediately upon encountering the lock. ^If the busy callback
2275 ** is not NULL, then the callback might be invoked with two arguments.
2277 ** ^The first argument to the busy handler is a copy of the void* pointer which
2278 ** is the third argument to sqlite3_busy_handler(). ^The second argument to
2279 ** the busy handler callback is the number of times that the busy handler has
2280 ** been invoked for this locking event. ^If the
2281 ** busy callback returns 0, then no additional attempts are made to
2282 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2283 ** ^If the callback returns non-zero, then another attempt
2284 ** is made to open the database for reading and the cycle repeats.
2286 ** The presence of a busy handler does not guarantee that it will be invoked
2287 ** when there is lock contention. ^If SQLite determines that invoking the busy
2288 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2289 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2290 ** Consider a scenario where one process is holding a read lock that
2291 ** it is trying to promote to a reserved lock and
2292 ** a second process is holding a reserved lock that it is trying
2293 ** to promote to an exclusive lock. The first process cannot proceed
2294 ** because it is blocked by the second and the second process cannot
2295 ** proceed because it is blocked by the first. If both processes
2296 ** invoke the busy handlers, neither will make any progress. Therefore,
2297 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2298 ** will induce the first process to release its read lock and allow
2299 ** the second process to proceed.
2301 ** ^The default busy callback is NULL.
2303 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2304 ** when SQLite is in the middle of a large transaction where all the
2305 ** changes will not fit into the in-memory cache. SQLite will
2306 ** already hold a RESERVED lock on the database file, but it needs
2307 ** to promote this lock to EXCLUSIVE so that it can spill cache
2308 ** pages into the database file without harm to concurrent
2309 ** readers. ^If it is unable to promote the lock, then the in-memory
2310 ** cache will be left in an inconsistent state and so the error
2311 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2312 ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
2313 ** forces an automatic rollback of the changes. See the
2314 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2315 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2316 ** this is important.
2318 ** ^(There can only be a single busy handler defined for each
2319 ** [database connection]. Setting a new busy handler clears any
2320 ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
2321 ** will also set or clear the busy handler.
2323 ** The busy callback should not take any actions which modify the
2324 ** database connection that invoked the busy handler. Any such actions
2325 ** result in undefined behavior.
2327 ** A busy handler must not close the database connection
2328 ** or [prepared statement] that invoked the busy handler.
2330 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2333 ** CAPI3REF: Set A Busy Timeout
2335 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2336 ** for a specified amount of time when a table is locked. ^The handler
2337 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2338 ** have accumulated. ^After at least "ms" milliseconds of sleeping,
2339 ** the handler returns 0 which causes [sqlite3_step()] to return
2340 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2342 ** ^Calling this routine with an argument less than or equal to zero
2343 ** turns off all busy handlers.
2345 ** ^(There can only be a single busy handler for a particular
2346 ** [database connection] any any given moment. If another busy handler
2347 ** was defined (using [sqlite3_busy_handler()]) prior to calling
2348 ** this routine, that other busy handler is cleared.)^
2350 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2353 ** CAPI3REF: Convenience Routines For Running Queries
2355 ** This is a legacy interface that is preserved for backwards compatibility.
2356 ** Use of this interface is not recommended.
2358 ** Definition: A <b>result table</b> is memory data structure created by the
2359 ** [sqlite3_get_table()] interface. A result table records the
2360 ** complete query results from one or more queries.
2362 ** The table conceptually has a number of rows and columns. But
2363 ** these numbers are not part of the result table itself. These
2364 ** numbers are obtained separately. Let N be the number of rows
2365 ** and M be the number of columns.
2367 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2368 ** There are (N+1)*M elements in the array. The first M pointers point
2369 ** to zero-terminated strings that contain the names of the columns.
2370 ** The remaining entries all point to query results. NULL values result
2371 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
2372 ** string representation as returned by [sqlite3_column_text()].
2374 ** A result table might consist of one or more memory allocations.
2375 ** It is not safe to pass a result table directly to [sqlite3_free()].
2376 ** A result table should be deallocated using [sqlite3_free_table()].
2378 ** ^(As an example of the result table format, suppose a query result
2379 ** is as follows:
2381 ** <blockquote><pre>
2382 ** Name | Age
2383 ** -----------------------
2384 ** Alice | 43
2385 ** Bob | 28
2386 ** Cindy | 21
2387 ** </pre></blockquote>
2389 ** There are two column (M==2) and three rows (N==3). Thus the
2390 ** result table has 8 entries. Suppose the result table is stored
2391 ** in an array names azResult. Then azResult holds this content:
2393 ** <blockquote><pre>
2394 ** azResult&#91;0] = "Name";
2395 ** azResult&#91;1] = "Age";
2396 ** azResult&#91;2] = "Alice";
2397 ** azResult&#91;3] = "43";
2398 ** azResult&#91;4] = "Bob";
2399 ** azResult&#91;5] = "28";
2400 ** azResult&#91;6] = "Cindy";
2401 ** azResult&#91;7] = "21";
2402 ** </pre></blockquote>)^
2404 ** ^The sqlite3_get_table() function evaluates one or more
2405 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2406 ** string of its 2nd parameter and returns a result table to the
2407 ** pointer given in its 3rd parameter.
2409 ** After the application has finished with the result from sqlite3_get_table(),
2410 ** it must pass the result table pointer to sqlite3_free_table() in order to
2411 ** release the memory that was malloced. Because of the way the
2412 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2413 ** function must not try to call [sqlite3_free()] directly. Only
2414 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2416 ** The sqlite3_get_table() interface is implemented as a wrapper around
2417 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2418 ** to any internal data structures of SQLite. It uses only the public
2419 ** interface defined here. As a consequence, errors that occur in the
2420 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2421 ** reflected in subsequent calls to [sqlite3_errcode()] or
2422 ** [sqlite3_errmsg()].
2424 SQLITE_API int sqlite3_get_table(
2425 sqlite3 *db, /* An open database */
2426 const char *zSql, /* SQL to be evaluated */
2427 char ***pazResult, /* Results of the query */
2428 int *pnRow, /* Number of result rows written here */
2429 int *pnColumn, /* Number of result columns written here */
2430 char **pzErrmsg /* Error msg written here */
2432 SQLITE_API void sqlite3_free_table(char **result);
2435 ** CAPI3REF: Formatted String Printing Functions
2437 ** These routines are work-alikes of the "printf()" family of functions
2438 ** from the standard C library.
2440 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2441 ** results into memory obtained from [sqlite3_malloc()].
2442 ** The strings returned by these two routines should be
2443 ** released by [sqlite3_free()]. ^Both routines return a
2444 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2445 ** memory to hold the resulting string.
2447 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2448 ** the standard C library. The result is written into the
2449 ** buffer supplied as the second parameter whose size is given by
2450 ** the first parameter. Note that the order of the
2451 ** first two parameters is reversed from snprintf().)^ This is an
2452 ** historical accident that cannot be fixed without breaking
2453 ** backwards compatibility. ^(Note also that sqlite3_snprintf()
2454 ** returns a pointer to its buffer instead of the number of
2455 ** characters actually written into the buffer.)^ We admit that
2456 ** the number of characters written would be a more useful return
2457 ** value but we cannot change the implementation of sqlite3_snprintf()
2458 ** now without breaking compatibility.
2460 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2461 ** guarantees that the buffer is always zero-terminated. ^The first
2462 ** parameter "n" is the total size of the buffer, including space for
2463 ** the zero terminator. So the longest string that can be completely
2464 ** written will be n-1 characters.
2466 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2468 ** These routines all implement some additional formatting
2469 ** options that are useful for constructing SQL statements.
2470 ** All of the usual printf() formatting options apply. In addition, there
2471 ** is are "%q", "%Q", and "%z" options.
2473 ** ^(The %q option works like %s in that it substitutes a null-terminated
2474 ** string from the argument list. But %q also doubles every '\'' character.
2475 ** %q is designed for use inside a string literal.)^ By doubling each '\''
2476 ** character it escapes that character and allows it to be inserted into
2477 ** the string.
2479 ** For example, assume the string variable zText contains text as follows:
2481 ** <blockquote><pre>
2482 ** char *zText = "It's a happy day!";
2483 ** </pre></blockquote>
2485 ** One can use this text in an SQL statement as follows:
2487 ** <blockquote><pre>
2488 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2489 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2490 ** sqlite3_free(zSQL);
2491 ** </pre></blockquote>
2493 ** Because the %q format string is used, the '\'' character in zText
2494 ** is escaped and the SQL generated is as follows:
2496 ** <blockquote><pre>
2497 ** INSERT INTO table1 VALUES('It''s a happy day!')
2498 ** </pre></blockquote>
2500 ** This is correct. Had we used %s instead of %q, the generated SQL
2501 ** would have looked like this:
2503 ** <blockquote><pre>
2504 ** INSERT INTO table1 VALUES('It's a happy day!');
2505 ** </pre></blockquote>
2507 ** This second example is an SQL syntax error. As a general rule you should
2508 ** always use %q instead of %s when inserting text into a string literal.
2510 ** ^(The %Q option works like %q except it also adds single quotes around
2511 ** the outside of the total string. Additionally, if the parameter in the
2512 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2513 ** single quotes).)^ So, for example, one could say:
2515 ** <blockquote><pre>
2516 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2517 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2518 ** sqlite3_free(zSQL);
2519 ** </pre></blockquote>
2521 ** The code above will render a correct SQL statement in the zSQL
2522 ** variable even if the zText variable is a NULL pointer.
2524 ** ^(The "%z" formatting option works like "%s" but with the
2525 ** addition that after the string has been read and copied into
2526 ** the result, [sqlite3_free()] is called on the input string.)^
2528 SQLITE_API char *sqlite3_mprintf(const char*,...);
2529 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2530 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2531 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2534 ** CAPI3REF: Memory Allocation Subsystem
2536 ** The SQLite core uses these three routines for all of its own
2537 ** internal memory allocation needs. "Core" in the previous sentence
2538 ** does not include operating-system specific VFS implementation. The
2539 ** Windows VFS uses native malloc() and free() for some operations.
2541 ** ^The sqlite3_malloc() routine returns a pointer to a block
2542 ** of memory at least N bytes in length, where N is the parameter.
2543 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2544 ** memory, it returns a NULL pointer. ^If the parameter N to
2545 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2546 ** a NULL pointer.
2548 ** ^Calling sqlite3_free() with a pointer previously returned
2549 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2550 ** that it might be reused. ^The sqlite3_free() routine is
2551 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
2552 ** to sqlite3_free() is harmless. After being freed, memory
2553 ** should neither be read nor written. Even reading previously freed
2554 ** memory might result in a segmentation fault or other severe error.
2555 ** Memory corruption, a segmentation fault, or other severe error
2556 ** might result if sqlite3_free() is called with a non-NULL pointer that
2557 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2559 ** ^(The sqlite3_realloc() interface attempts to resize a
2560 ** prior memory allocation to be at least N bytes, where N is the
2561 ** second parameter. The memory allocation to be resized is the first
2562 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2563 ** is a NULL pointer then its behavior is identical to calling
2564 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2565 ** ^If the second parameter to sqlite3_realloc() is zero or
2566 ** negative then the behavior is exactly the same as calling
2567 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2568 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2569 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2570 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2571 ** of the prior allocation are copied into the beginning of buffer returned
2572 ** by sqlite3_realloc() and the prior allocation is freed.
2573 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2574 ** is not freed.
2576 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2577 ** is always aligned to at least an 8 byte boundary, or to a
2578 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2579 ** option is used.
2581 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2582 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2583 ** implementation of these routines to be omitted. That capability
2584 ** is no longer provided. Only built-in memory allocators can be used.
2586 ** The Windows OS interface layer calls
2587 ** the system malloc() and free() directly when converting
2588 ** filenames between the UTF-8 encoding used by SQLite
2589 ** and whatever filename encoding is used by the particular Windows
2590 ** installation. Memory allocation errors are detected, but
2591 ** they are reported back as [SQLITE_CANTOPEN] or
2592 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2594 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2595 ** must be either NULL or else pointers obtained from a prior
2596 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2597 ** not yet been released.
2599 ** The application must not read or write any part of
2600 ** a block of memory after it has been released using
2601 ** [sqlite3_free()] or [sqlite3_realloc()].
2603 SQLITE_API void *sqlite3_malloc(int);
2604 SQLITE_API void *sqlite3_realloc(void*, int);
2605 SQLITE_API void sqlite3_free(void*);
2608 ** CAPI3REF: Memory Allocator Statistics
2610 ** SQLite provides these two interfaces for reporting on the status
2611 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2612 ** routines, which form the built-in memory allocation subsystem.
2614 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2615 ** of memory currently outstanding (malloced but not freed).
2616 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2617 ** value of [sqlite3_memory_used()] since the high-water mark
2618 ** was last reset. ^The values returned by [sqlite3_memory_used()] and
2619 ** [sqlite3_memory_highwater()] include any overhead
2620 ** added by SQLite in its implementation of [sqlite3_malloc()],
2621 ** but not overhead added by the any underlying system library
2622 ** routines that [sqlite3_malloc()] may call.
2624 ** ^The memory high-water mark is reset to the current value of
2625 ** [sqlite3_memory_used()] if and only if the parameter to
2626 ** [sqlite3_memory_highwater()] is true. ^The value returned
2627 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2628 ** prior to the reset.
2630 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2631 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2634 ** CAPI3REF: Pseudo-Random Number Generator
2636 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2637 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2638 ** already uses the largest possible [ROWID]. The PRNG is also used for
2639 ** the build-in random() and randomblob() SQL functions. This interface allows
2640 ** applications to access the same PRNG for other purposes.
2642 ** ^A call to this routine stores N bytes of randomness into buffer P.
2644 ** ^The first time this routine is invoked (either internally or by
2645 ** the application) the PRNG is seeded using randomness obtained
2646 ** from the xRandomness method of the default [sqlite3_vfs] object.
2647 ** ^On all subsequent invocations, the pseudo-randomness is generated
2648 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2649 ** method.
2651 SQLITE_API void sqlite3_randomness(int N, void *P);
2654 ** CAPI3REF: Compile-Time Authorization Callbacks
2656 ** ^This routine registers an authorizer callback with a particular
2657 ** [database connection], supplied in the first argument.
2658 ** ^The authorizer callback is invoked as SQL statements are being compiled
2659 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2660 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
2661 ** points during the compilation process, as logic is being created
2662 ** to perform various actions, the authorizer callback is invoked to
2663 ** see if those actions are allowed. ^The authorizer callback should
2664 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2665 ** specific action but allow the SQL statement to continue to be
2666 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2667 ** rejected with an error. ^If the authorizer callback returns
2668 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2669 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2670 ** the authorizer will fail with an error message.
2672 ** When the callback returns [SQLITE_OK], that means the operation
2673 ** requested is ok. ^When the callback returns [SQLITE_DENY], the
2674 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2675 ** authorizer will fail with an error message explaining that
2676 ** access is denied.
2678 ** ^The first parameter to the authorizer callback is a copy of the third
2679 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2680 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2681 ** the particular action to be authorized. ^The third through sixth parameters
2682 ** to the callback are zero-terminated strings that contain additional
2683 ** details about the action to be authorized.
2685 ** ^If the action code is [SQLITE_READ]
2686 ** and the callback returns [SQLITE_IGNORE] then the
2687 ** [prepared statement] statement is constructed to substitute
2688 ** a NULL value in place of the table column that would have
2689 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2690 ** return can be used to deny an untrusted user access to individual
2691 ** columns of a table.
2692 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2693 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2694 ** [truncate optimization] is disabled and all rows are deleted individually.
2696 ** An authorizer is used when [sqlite3_prepare | preparing]
2697 ** SQL statements from an untrusted source, to ensure that the SQL statements
2698 ** do not try to access data they are not allowed to see, or that they do not
2699 ** try to execute malicious statements that damage the database. For
2700 ** example, an application may allow a user to enter arbitrary
2701 ** SQL queries for evaluation by a database. But the application does
2702 ** not want the user to be able to make arbitrary changes to the
2703 ** database. An authorizer could then be put in place while the
2704 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2705 ** disallows everything except [SELECT] statements.
2707 ** Applications that need to process SQL from untrusted sources
2708 ** might also consider lowering resource limits using [sqlite3_limit()]
2709 ** and limiting database size using the [max_page_count] [PRAGMA]
2710 ** in addition to using an authorizer.
2712 ** ^(Only a single authorizer can be in place on a database connection
2713 ** at a time. Each call to sqlite3_set_authorizer overrides the
2714 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
2715 ** The authorizer is disabled by default.
2717 ** The authorizer callback must not do anything that will modify
2718 ** the database connection that invoked the authorizer callback.
2719 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2720 ** database connections for the meaning of "modify" in this paragraph.
2722 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2723 ** statement might be re-prepared during [sqlite3_step()] due to a
2724 ** schema change. Hence, the application should ensure that the
2725 ** correct authorizer callback remains in place during the [sqlite3_step()].
2727 ** ^Note that the authorizer callback is invoked only during
2728 ** [sqlite3_prepare()] or its variants. Authorization is not
2729 ** performed during statement evaluation in [sqlite3_step()], unless
2730 ** as stated in the previous paragraph, sqlite3_step() invokes
2731 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2733 SQLITE_API int sqlite3_set_authorizer(
2734 sqlite3*,
2735 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2736 void *pUserData
2740 ** CAPI3REF: Authorizer Return Codes
2742 ** The [sqlite3_set_authorizer | authorizer callback function] must
2743 ** return either [SQLITE_OK] or one of these two constants in order
2744 ** to signal SQLite whether or not the action is permitted. See the
2745 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2746 ** information.
2748 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
2749 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
2752 ** CAPI3REF: Authorizer Action Codes
2754 ** The [sqlite3_set_authorizer()] interface registers a callback function
2755 ** that is invoked to authorize certain SQL statement actions. The
2756 ** second parameter to the callback is an integer code that specifies
2757 ** what action is being authorized. These are the integer action codes that
2758 ** the authorizer callback may be passed.
2760 ** These action code values signify what kind of operation is to be
2761 ** authorized. The 3rd and 4th parameters to the authorization
2762 ** callback function will be parameters or NULL depending on which of these
2763 ** codes is used as the second parameter. ^(The 5th parameter to the
2764 ** authorizer callback is the name of the database ("main", "temp",
2765 ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
2766 ** is the name of the inner-most trigger or view that is responsible for
2767 ** the access attempt or NULL if this access attempt is directly from
2768 ** top-level SQL code.
2770 /******************************************* 3rd ************ 4th ***********/
2771 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
2772 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
2773 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
2774 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
2775 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
2776 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
2777 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
2778 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
2779 #define SQLITE_DELETE 9 /* Table Name NULL */
2780 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
2781 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
2782 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
2783 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
2784 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
2785 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
2786 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
2787 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
2788 #define SQLITE_INSERT 18 /* Table Name NULL */
2789 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
2790 #define SQLITE_READ 20 /* Table Name Column Name */
2791 #define SQLITE_SELECT 21 /* NULL NULL */
2792 #define SQLITE_TRANSACTION 22 /* Operation NULL */
2793 #define SQLITE_UPDATE 23 /* Table Name Column Name */
2794 #define SQLITE_ATTACH 24 /* Filename NULL */
2795 #define SQLITE_DETACH 25 /* Database Name NULL */
2796 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
2797 #define SQLITE_REINDEX 27 /* Index Name NULL */
2798 #define SQLITE_ANALYZE 28 /* Table Name NULL */
2799 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
2800 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
2801 #define SQLITE_FUNCTION 31 /* NULL Function Name */
2802 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
2803 #define SQLITE_COPY 0 /* No longer used */
2806 ** CAPI3REF: Tracing And Profiling Functions
2808 ** These routines register callback functions that can be used for
2809 ** tracing and profiling the execution of SQL statements.
2811 ** ^The callback function registered by sqlite3_trace() is invoked at
2812 ** various times when an SQL statement is being run by [sqlite3_step()].
2813 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2814 ** SQL statement text as the statement first begins executing.
2815 ** ^(Additional sqlite3_trace() callbacks might occur
2816 ** as each triggered subprogram is entered. The callbacks for triggers
2817 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2819 ** ^The callback function registered by sqlite3_profile() is invoked
2820 ** as each SQL statement finishes. ^The profile callback contains
2821 ** the original statement text and an estimate of wall-clock time
2822 ** of how long that statement took to run. ^The profile callback
2823 ** time is in units of nanoseconds, however the current implementation
2824 ** is only capable of millisecond resolution so the six least significant
2825 ** digits in the time are meaningless. Future versions of SQLite
2826 ** might provide greater resolution on the profiler callback. The
2827 ** sqlite3_profile() function is considered experimental and is
2828 ** subject to change in future versions of SQLite.
2830 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2831 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2832 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2835 ** CAPI3REF: Query Progress Callbacks
2837 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2838 ** function X to be invoked periodically during long running calls to
2839 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2840 ** database connection D. An example use for this
2841 ** interface is to keep a GUI updated during a large query.
2843 ** ^The parameter P is passed through as the only parameter to the
2844 ** callback function X. ^The parameter N is the number of
2845 ** [virtual machine instructions] that are evaluated between successive
2846 ** invocations of the callback X.
2848 ** ^Only a single progress handler may be defined at one time per
2849 ** [database connection]; setting a new progress handler cancels the
2850 ** old one. ^Setting parameter X to NULL disables the progress handler.
2851 ** ^The progress handler is also disabled by setting N to a value less
2852 ** than 1.
2854 ** ^If the progress callback returns non-zero, the operation is
2855 ** interrupted. This feature can be used to implement a
2856 ** "Cancel" button on a GUI progress dialog box.
2858 ** The progress handler callback must not do anything that will modify
2859 ** the database connection that invoked the progress handler.
2860 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2861 ** database connections for the meaning of "modify" in this paragraph.
2864 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2867 ** CAPI3REF: Opening A New Database Connection
2869 ** ^These routines open an SQLite database file whose name is given by the
2870 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2871 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2872 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2873 ** returned in *ppDb, even if an error occurs. The only exception is that
2874 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2875 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2876 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2877 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
2878 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2879 ** an English language description of the error following a failure of any
2880 ** of the sqlite3_open() routines.
2882 ** ^The default encoding for the database will be UTF-8 if
2883 ** sqlite3_open() or sqlite3_open_v2() is called and
2884 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2886 ** Whether or not an error occurs when it is opened, resources
2887 ** associated with the [database connection] handle should be released by
2888 ** passing it to [sqlite3_close()] when it is no longer required.
2890 ** The sqlite3_open_v2() interface works like sqlite3_open()
2891 ** except that it accepts two additional parameters for additional control
2892 ** over the new database connection. ^(The flags parameter to
2893 ** sqlite3_open_v2() can take one of
2894 ** the following three values, optionally combined with the
2895 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2896 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2898 ** <dl>
2899 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2900 ** <dd>The database is opened in read-only mode. If the database does not
2901 ** already exist, an error is returned.</dd>)^
2903 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2904 ** <dd>The database is opened for reading and writing if possible, or reading
2905 ** only if the file is write protected by the operating system. In either
2906 ** case the database must already exist, otherwise an error is returned.</dd>)^
2908 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2909 ** <dd>The database is opened for reading and writing, and is created if
2910 ** it does not already exist. This is the behavior that is always used for
2911 ** sqlite3_open() and sqlite3_open16().</dd>)^
2912 ** </dl>
2914 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2915 ** combinations shown above or one of the combinations shown above combined
2916 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2917 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
2918 ** then the behavior is undefined.
2920 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2921 ** opens in the multi-thread [threading mode] as long as the single-thread
2922 ** mode has not been set at compile-time or start-time. ^If the
2923 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2924 ** in the serialized [threading mode] unless single-thread was
2925 ** previously selected at compile-time or start-time.
2926 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2927 ** eligible to use [shared cache mode], regardless of whether or not shared
2928 ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
2929 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2930 ** participate in [shared cache mode] even if it is enabled.
2932 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2933 ** is created for the connection. ^This in-memory database will vanish when
2934 ** the database connection is closed. Future versions of SQLite might
2935 ** make use of additional special filenames that begin with the ":" character.
2936 ** It is recommended that when a database filename actually does begin with
2937 ** a ":" character you should prefix the filename with a pathname such as
2938 ** "./" to avoid ambiguity.
2940 ** ^If the filename is an empty string, then a private, temporary
2941 ** on-disk database will be created. ^This private database will be
2942 ** automatically deleted as soon as the database connection is closed.
2944 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2945 ** [sqlite3_vfs] object that defines the operating system interface that
2946 ** the new database connection should use. ^If the fourth parameter is
2947 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2949 ** <b>Note to Windows users:</b> The encoding used for the filename argument
2950 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2951 ** codepage is currently defined. Filenames containing international
2952 ** characters must be converted to UTF-8 prior to passing them into
2953 ** sqlite3_open() or sqlite3_open_v2().
2955 SQLITE_API int sqlite3_open(
2956 const char *filename, /* Database filename (UTF-8) */
2957 sqlite3 **ppDb /* OUT: SQLite db handle */
2959 SQLITE_API int sqlite3_open16(
2960 const void *filename, /* Database filename (UTF-16) */
2961 sqlite3 **ppDb /* OUT: SQLite db handle */
2963 SQLITE_API int sqlite3_open_v2(
2964 const char *filename, /* Database filename (UTF-8) */
2965 sqlite3 **ppDb, /* OUT: SQLite db handle */
2966 int flags, /* Flags */
2967 const char *zVfs /* Name of VFS module to use */
2971 ** CAPI3REF: Error Codes And Messages
2973 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
2974 ** [extended result code] for the most recent failed sqlite3_* API call
2975 ** associated with a [database connection]. If a prior API call failed
2976 ** but the most recent API call succeeded, the return value from
2977 ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
2978 ** interface is the same except that it always returns the
2979 ** [extended result code] even when extended result codes are
2980 ** disabled.
2982 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2983 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2984 ** ^(Memory to hold the error message string is managed internally.
2985 ** The application does not need to worry about freeing the result.
2986 ** However, the error string might be overwritten or deallocated by
2987 ** subsequent calls to other SQLite interface functions.)^
2989 ** When the serialized [threading mode] is in use, it might be the
2990 ** case that a second error occurs on a separate thread in between
2991 ** the time of the first error and the call to these interfaces.
2992 ** When that happens, the second error will be reported since these
2993 ** interfaces always report the most recent result. To avoid
2994 ** this, each thread can obtain exclusive use of the [database connection] D
2995 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2996 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2997 ** all calls to the interfaces listed here are completed.
2999 ** If an interface fails with SQLITE_MISUSE, that means the interface
3000 ** was invoked incorrectly by the application. In that case, the
3001 ** error code and message may or may not be set.
3003 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3004 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3005 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3006 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3009 ** CAPI3REF: SQL Statement Object
3010 ** KEYWORDS: {prepared statement} {prepared statements}
3012 ** An instance of this object represents a single SQL statement.
3013 ** This object is variously known as a "prepared statement" or a
3014 ** "compiled SQL statement" or simply as a "statement".
3016 ** The life of a statement object goes something like this:
3018 ** <ol>
3019 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3020 ** function.
3021 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3022 ** interfaces.
3023 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3024 ** <li> Reset the statement using [sqlite3_reset()] then go back
3025 ** to step 2. Do this zero or more times.
3026 ** <li> Destroy the object using [sqlite3_finalize()].
3027 ** </ol>
3029 ** Refer to documentation on individual methods above for additional
3030 ** information.
3032 typedef struct sqlite3_stmt sqlite3_stmt;
3035 ** CAPI3REF: Run-time Limits
3037 ** ^(This interface allows the size of various constructs to be limited
3038 ** on a connection by connection basis. The first parameter is the
3039 ** [database connection] whose limit is to be set or queried. The
3040 ** second parameter is one of the [limit categories] that define a
3041 ** class of constructs to be size limited. The third parameter is the
3042 ** new limit for that construct.)^
3044 ** ^If the new limit is a negative number, the limit is unchanged.
3045 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3046 ** [limits | hard upper bound]
3047 ** set at compile-time by a C preprocessor macro called
3048 ** [limits | SQLITE_MAX_<i>NAME</i>].
3049 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3050 ** ^Attempts to increase a limit above its hard upper bound are
3051 ** silently truncated to the hard upper bound.
3053 ** ^Regardless of whether or not the limit was changed, the
3054 ** [sqlite3_limit()] interface returns the prior value of the limit.
3055 ** ^Hence, to find the current value of a limit without changing it,
3056 ** simply invoke this interface with the third parameter set to -1.
3058 ** Run-time limits are intended for use in applications that manage
3059 ** both their own internal database and also databases that are controlled
3060 ** by untrusted external sources. An example application might be a
3061 ** web browser that has its own databases for storing history and
3062 ** separate databases controlled by JavaScript applications downloaded
3063 ** off the Internet. The internal databases can be given the
3064 ** large, default limits. Databases managed by external sources can
3065 ** be given much smaller limits designed to prevent a denial of service
3066 ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
3067 ** interface to further control untrusted SQL. The size of the database
3068 ** created by an untrusted script can be contained using the
3069 ** [max_page_count] [PRAGMA].
3071 ** New run-time limit categories may be added in future releases.
3073 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3076 ** CAPI3REF: Run-Time Limit Categories
3077 ** KEYWORDS: {limit category} {*limit categories}
3079 ** These constants define various performance limits
3080 ** that can be lowered at run-time using [sqlite3_limit()].
3081 ** The synopsis of the meanings of the various limits is shown below.
3082 ** Additional information is available at [limits | Limits in SQLite].
3084 ** <dl>
3085 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3086 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3088 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3089 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3091 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3092 ** <dd>The maximum number of columns in a table definition or in the
3093 ** result set of a [SELECT] or the maximum number of columns in an index
3094 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3096 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3097 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3099 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3100 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3102 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3103 ** <dd>The maximum number of instructions in a virtual machine program
3104 ** used to implement an SQL statement. This limit is not currently
3105 ** enforced, though that might be added in some future release of
3106 ** SQLite.</dd>)^
3108 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3109 ** <dd>The maximum number of arguments on a function.</dd>)^
3111 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3112 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3114 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3115 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3116 ** [GLOB] operators.</dd>)^
3118 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3119 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3121 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3122 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3123 ** </dl>
3125 #define SQLITE_LIMIT_LENGTH 0
3126 #define SQLITE_LIMIT_SQL_LENGTH 1
3127 #define SQLITE_LIMIT_COLUMN 2
3128 #define SQLITE_LIMIT_EXPR_DEPTH 3
3129 #define SQLITE_LIMIT_COMPOUND_SELECT 4
3130 #define SQLITE_LIMIT_VDBE_OP 5
3131 #define SQLITE_LIMIT_FUNCTION_ARG 6
3132 #define SQLITE_LIMIT_ATTACHED 7
3133 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
3134 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
3135 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
3138 ** CAPI3REF: Compiling An SQL Statement
3139 ** KEYWORDS: {SQL statement compiler}
3141 ** To execute an SQL query, it must first be compiled into a byte-code
3142 ** program using one of these routines.
3144 ** The first argument, "db", is a [database connection] obtained from a
3145 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3146 ** [sqlite3_open16()]. The database connection must not have been closed.
3148 ** The second argument, "zSql", is the statement to be compiled, encoded
3149 ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
3150 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3151 ** use UTF-16.
3153 ** ^If the nByte argument is less than zero, then zSql is read up to the
3154 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3155 ** number of bytes read from zSql. ^When nByte is non-negative, the
3156 ** zSql string ends at either the first '\000' or '\u0000' character or
3157 ** the nByte-th byte, whichever comes first. If the caller knows
3158 ** that the supplied string is nul-terminated, then there is a small
3159 ** performance advantage to be gained by passing an nByte parameter that
3160 ** is equal to the number of bytes in the input string <i>including</i>
3161 ** the nul-terminator bytes.
3163 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3164 ** past the end of the first SQL statement in zSql. These routines only
3165 ** compile the first statement in zSql, so *pzTail is left pointing to
3166 ** what remains uncompiled.
3168 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3169 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
3170 ** to NULL. ^If the input text contains no SQL (if the input is an empty
3171 ** string or a comment) then *ppStmt is set to NULL.
3172 ** The calling procedure is responsible for deleting the compiled
3173 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3174 ** ppStmt may not be NULL.
3176 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3177 ** otherwise an [error code] is returned.
3179 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3180 ** recommended for all new programs. The two older interfaces are retained
3181 ** for backwards compatibility, but their use is discouraged.
3182 ** ^In the "v2" interfaces, the prepared statement
3183 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3184 ** original SQL text. This causes the [sqlite3_step()] interface to
3185 ** behave differently in three ways:
3187 ** <ol>
3188 ** <li>
3189 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3190 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3191 ** statement and try to run it again.
3192 ** </li>
3194 ** <li>
3195 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3196 ** [error codes] or [extended error codes]. ^The legacy behavior was that
3197 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3198 ** and the application would have to make a second call to [sqlite3_reset()]
3199 ** in order to find the underlying cause of the problem. With the "v2" prepare
3200 ** interfaces, the underlying reason for the error is returned immediately.
3201 ** </li>
3203 ** <li>
3204 ** ^If the specific value bound to [parameter | host parameter] in the
3205 ** WHERE clause might influence the choice of query plan for a statement,
3206 ** then the statement will be automatically recompiled, as if there had been
3207 ** a schema change, on the first [sqlite3_step()] call following any change
3208 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3209 ** ^The specific value of WHERE-clause [parameter] might influence the
3210 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3211 ** or [GLOB] operator or if the parameter is compared to an indexed column
3212 ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
3213 ** the
3214 ** </li>
3215 ** </ol>
3217 SQLITE_API int sqlite3_prepare(
3218 sqlite3 *db, /* Database handle */
3219 const char *zSql, /* SQL statement, UTF-8 encoded */
3220 int nByte, /* Maximum length of zSql in bytes. */
3221 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3222 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3224 SQLITE_API int sqlite3_prepare_v2(
3225 sqlite3 *db, /* Database handle */
3226 const char *zSql, /* SQL statement, UTF-8 encoded */
3227 int nByte, /* Maximum length of zSql in bytes. */
3228 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3229 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3231 SQLITE_API int sqlite3_prepare16(
3232 sqlite3 *db, /* Database handle */
3233 const void *zSql, /* SQL statement, UTF-16 encoded */
3234 int nByte, /* Maximum length of zSql in bytes. */
3235 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3236 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3238 SQLITE_API int sqlite3_prepare16_v2(
3239 sqlite3 *db, /* Database handle */
3240 const void *zSql, /* SQL statement, UTF-16 encoded */
3241 int nByte, /* Maximum length of zSql in bytes. */
3242 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3243 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3247 ** CAPI3REF: Retrieving Statement SQL
3249 ** ^This interface can be used to retrieve a saved copy of the original
3250 ** SQL text used to create a [prepared statement] if that statement was
3251 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3253 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3256 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3258 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3259 ** and only if the [prepared statement] X makes no direct changes to
3260 ** the content of the database file.
3262 ** Note that [application-defined SQL functions] or
3263 ** [virtual tables] might change the database indirectly as a side effect.
3264 ** ^(For example, if an application defines a function "eval()" that
3265 ** calls [sqlite3_exec()], then the following SQL statement would
3266 ** change the database file through side-effects:
3268 ** <blockquote><pre>
3269 ** SELECT eval('DELETE FROM t1') FROM t2;
3270 ** </pre></blockquote>
3272 ** But because the [SELECT] statement does not change the database file
3273 ** directly, sqlite3_stmt_readonly() would still return true.)^
3275 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3276 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3277 ** since the statements themselves do not actually modify the database but
3278 ** rather they control the timing of when other statements modify the
3279 ** database. ^The [ATTACH] and [DETACH] statements also cause
3280 ** sqlite3_stmt_readonly() to return true since, while those statements
3281 ** change the configuration of a database connection, they do not make
3282 ** changes to the content of the database files on disk.
3284 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3287 ** CAPI3REF: Dynamically Typed Value Object
3288 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3290 ** SQLite uses the sqlite3_value object to represent all values
3291 ** that can be stored in a database table. SQLite uses dynamic typing
3292 ** for the values it stores. ^Values stored in sqlite3_value objects
3293 ** can be integers, floating point values, strings, BLOBs, or NULL.
3295 ** An sqlite3_value object may be either "protected" or "unprotected".
3296 ** Some interfaces require a protected sqlite3_value. Other interfaces
3297 ** will accept either a protected or an unprotected sqlite3_value.
3298 ** Every interface that accepts sqlite3_value arguments specifies
3299 ** whether or not it requires a protected sqlite3_value.
3301 ** The terms "protected" and "unprotected" refer to whether or not
3302 ** a mutex is held. An internal mutex is held for a protected
3303 ** sqlite3_value object but no mutex is held for an unprotected
3304 ** sqlite3_value object. If SQLite is compiled to be single-threaded
3305 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3306 ** or if SQLite is run in one of reduced mutex modes
3307 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3308 ** then there is no distinction between protected and unprotected
3309 ** sqlite3_value objects and they can be used interchangeably. However,
3310 ** for maximum code portability it is recommended that applications
3311 ** still make the distinction between protected and unprotected
3312 ** sqlite3_value objects even when not strictly required.
3314 ** ^The sqlite3_value objects that are passed as parameters into the
3315 ** implementation of [application-defined SQL functions] are protected.
3316 ** ^The sqlite3_value object returned by
3317 ** [sqlite3_column_value()] is unprotected.
3318 ** Unprotected sqlite3_value objects may only be used with
3319 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3320 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3321 ** interfaces require protected sqlite3_value objects.
3323 typedef struct Mem sqlite3_value;
3326 ** CAPI3REF: SQL Function Context Object
3328 ** The context in which an SQL function executes is stored in an
3329 ** sqlite3_context object. ^A pointer to an sqlite3_context object
3330 ** is always first parameter to [application-defined SQL functions].
3331 ** The application-defined SQL function implementation will pass this
3332 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3333 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3334 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3335 ** and/or [sqlite3_set_auxdata()].
3337 typedef struct sqlite3_context sqlite3_context;
3340 ** CAPI3REF: Binding Values To Prepared Statements
3341 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3342 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3344 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3345 ** literals may be replaced by a [parameter] that matches one of following
3346 ** templates:
3348 ** <ul>
3349 ** <li> ?
3350 ** <li> ?NNN
3351 ** <li> :VVV
3352 ** <li> @VVV
3353 ** <li> $VVV
3354 ** </ul>
3356 ** In the templates above, NNN represents an integer literal,
3357 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
3358 ** parameters (also called "host parameter names" or "SQL parameters")
3359 ** can be set using the sqlite3_bind_*() routines defined here.
3361 ** ^The first argument to the sqlite3_bind_*() routines is always
3362 ** a pointer to the [sqlite3_stmt] object returned from
3363 ** [sqlite3_prepare_v2()] or its variants.
3365 ** ^The second argument is the index of the SQL parameter to be set.
3366 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
3367 ** SQL parameter is used more than once, second and subsequent
3368 ** occurrences have the same index as the first occurrence.
3369 ** ^The index for named parameters can be looked up using the
3370 ** [sqlite3_bind_parameter_index()] API if desired. ^The index
3371 ** for "?NNN" parameters is the value of NNN.
3372 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3373 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3375 ** ^The third argument is the value to bind to the parameter.
3377 ** ^(In those routines that have a fourth argument, its value is the
3378 ** number of bytes in the parameter. To be clear: the value is the
3379 ** number of <u>bytes</u> in the value, not the number of characters.)^
3380 ** ^If the fourth parameter is negative, the length of the string is
3381 ** the number of bytes up to the first zero terminator.
3383 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3384 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3385 ** string after SQLite has finished with it. ^The destructor is called
3386 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3387 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3388 ** ^If the fifth argument is
3389 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3390 ** information is in static, unmanaged space and does not need to be freed.
3391 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3392 ** SQLite makes its own private copy of the data immediately, before
3393 ** the sqlite3_bind_*() routine returns.
3395 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3396 ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
3397 ** (just an integer to hold its size) while it is being processed.
3398 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3399 ** content is later written using
3400 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3401 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3403 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3404 ** for the [prepared statement] or with a prepared statement for which
3405 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3406 ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
3407 ** routine is passed a [prepared statement] that has been finalized, the
3408 ** result is undefined and probably harmful.
3410 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3411 ** ^Unbound parameters are interpreted as NULL.
3413 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3414 ** [error code] if anything goes wrong.
3415 ** ^[SQLITE_RANGE] is returned if the parameter
3416 ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
3418 ** See also: [sqlite3_bind_parameter_count()],
3419 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3421 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3422 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3423 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3424 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3425 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3426 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3427 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3428 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3429 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3432 ** CAPI3REF: Number Of SQL Parameters
3434 ** ^This routine can be used to find the number of [SQL parameters]
3435 ** in a [prepared statement]. SQL parameters are tokens of the
3436 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3437 ** placeholders for values that are [sqlite3_bind_blob | bound]
3438 ** to the parameters at a later time.
3440 ** ^(This routine actually returns the index of the largest (rightmost)
3441 ** parameter. For all forms except ?NNN, this will correspond to the
3442 ** number of unique parameters. If parameters of the ?NNN form are used,
3443 ** there may be gaps in the list.)^
3445 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3446 ** [sqlite3_bind_parameter_name()], and
3447 ** [sqlite3_bind_parameter_index()].
3449 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3452 ** CAPI3REF: Name Of A Host Parameter
3454 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3455 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3456 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3457 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3458 ** respectively.
3459 ** In other words, the initial ":" or "$" or "@" or "?"
3460 ** is included as part of the name.)^
3461 ** ^Parameters of the form "?" without a following integer have no name
3462 ** and are referred to as "nameless" or "anonymous parameters".
3464 ** ^The first host parameter has an index of 1, not 0.
3466 ** ^If the value N is out of range or if the N-th parameter is
3467 ** nameless, then NULL is returned. ^The returned string is
3468 ** always in UTF-8 encoding even if the named parameter was
3469 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3470 ** [sqlite3_prepare16_v2()].
3472 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3473 ** [sqlite3_bind_parameter_count()], and
3474 ** [sqlite3_bind_parameter_index()].
3476 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3479 ** CAPI3REF: Index Of A Parameter With A Given Name
3481 ** ^Return the index of an SQL parameter given its name. ^The
3482 ** index value returned is suitable for use as the second
3483 ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
3484 ** is returned if no matching parameter is found. ^The parameter
3485 ** name must be given in UTF-8 even if the original statement
3486 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3488 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3489 ** [sqlite3_bind_parameter_count()], and
3490 ** [sqlite3_bind_parameter_index()].
3492 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3495 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3497 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3498 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3499 ** ^Use this routine to reset all host parameters to NULL.
3501 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3504 ** CAPI3REF: Number Of Columns In A Result Set
3506 ** ^Return the number of columns in the result set returned by the
3507 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3508 ** statement that does not return data (for example an [UPDATE]).
3510 ** See also: [sqlite3_data_count()]
3512 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3515 ** CAPI3REF: Column Names In A Result Set
3517 ** ^These routines return the name assigned to a particular column
3518 ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
3519 ** interface returns a pointer to a zero-terminated UTF-8 string
3520 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3521 ** UTF-16 string. ^The first parameter is the [prepared statement]
3522 ** that implements the [SELECT] statement. ^The second parameter is the
3523 ** column number. ^The leftmost column is number 0.
3525 ** ^The returned string pointer is valid until either the [prepared statement]
3526 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3527 ** reprepared by the first call to [sqlite3_step()] for a particular run
3528 ** or until the next call to
3529 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3531 ** ^If sqlite3_malloc() fails during the processing of either routine
3532 ** (for example during a conversion from UTF-8 to UTF-16) then a
3533 ** NULL pointer is returned.
3535 ** ^The name of a result column is the value of the "AS" clause for
3536 ** that column, if there is an AS clause. If there is no AS clause
3537 ** then the name of the column is unspecified and may change from
3538 ** one release of SQLite to the next.
3540 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3541 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3544 ** CAPI3REF: Source Of Data In A Query Result
3546 ** ^These routines provide a means to determine the database, table, and
3547 ** table column that is the origin of a particular result column in
3548 ** [SELECT] statement.
3549 ** ^The name of the database or table or column can be returned as
3550 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
3551 ** the database name, the _table_ routines return the table name, and
3552 ** the origin_ routines return the column name.
3553 ** ^The returned string is valid until the [prepared statement] is destroyed
3554 ** using [sqlite3_finalize()] or until the statement is automatically
3555 ** reprepared by the first call to [sqlite3_step()] for a particular run
3556 ** or until the same information is requested
3557 ** again in a different encoding.
3559 ** ^The names returned are the original un-aliased names of the
3560 ** database, table, and column.
3562 ** ^The first argument to these interfaces is a [prepared statement].
3563 ** ^These functions return information about the Nth result column returned by
3564 ** the statement, where N is the second function argument.
3565 ** ^The left-most column is column 0 for these routines.
3567 ** ^If the Nth column returned by the statement is an expression or
3568 ** subquery and is not a column value, then all of these functions return
3569 ** NULL. ^These routine might also return NULL if a memory allocation error
3570 ** occurs. ^Otherwise, they return the name of the attached database, table,
3571 ** or column that query result column was extracted from.
3573 ** ^As with all other SQLite APIs, those whose names end with "16" return
3574 ** UTF-16 encoded strings and the other functions return UTF-8.
3576 ** ^These APIs are only available if the library was compiled with the
3577 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3579 ** If two or more threads call one or more of these routines against the same
3580 ** prepared statement and column at the same time then the results are
3581 ** undefined.
3583 ** If two or more threads call one or more
3584 ** [sqlite3_column_database_name | column metadata interfaces]
3585 ** for the same [prepared statement] and result column
3586 ** at the same time then the results are undefined.
3588 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3589 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3590 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3591 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3592 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3593 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3596 ** CAPI3REF: Declared Datatype Of A Query Result
3598 ** ^(The first parameter is a [prepared statement].
3599 ** If this statement is a [SELECT] statement and the Nth column of the
3600 ** returned result set of that [SELECT] is a table column (not an
3601 ** expression or subquery) then the declared type of the table
3602 ** column is returned.)^ ^If the Nth column of the result set is an
3603 ** expression or subquery, then a NULL pointer is returned.
3604 ** ^The returned string is always UTF-8 encoded.
3606 ** ^(For example, given the database schema:
3608 ** CREATE TABLE t1(c1 VARIANT);
3610 ** and the following statement to be compiled:
3612 ** SELECT c1 + 1, c1 FROM t1;
3614 ** this routine would return the string "VARIANT" for the second result
3615 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3617 ** ^SQLite uses dynamic run-time typing. ^So just because a column
3618 ** is declared to contain a particular type does not mean that the
3619 ** data stored in that column is of the declared type. SQLite is
3620 ** strongly typed, but the typing is dynamic not static. ^Type
3621 ** is associated with individual values, not with the containers
3622 ** used to hold those values.
3624 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3625 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3628 ** CAPI3REF: Evaluate An SQL Statement
3630 ** After a [prepared statement] has been prepared using either
3631 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3632 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3633 ** must be called one or more times to evaluate the statement.
3635 ** The details of the behavior of the sqlite3_step() interface depend
3636 ** on whether the statement was prepared using the newer "v2" interface
3637 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3638 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
3639 ** new "v2" interface is recommended for new applications but the legacy
3640 ** interface will continue to be supported.
3642 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3643 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3644 ** ^With the "v2" interface, any of the other [result codes] or
3645 ** [extended result codes] might be returned as well.
3647 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3648 ** database locks it needs to do its job. ^If the statement is a [COMMIT]
3649 ** or occurs outside of an explicit transaction, then you can retry the
3650 ** statement. If the statement is not a [COMMIT] and occurs within a
3651 ** explicit transaction then you should rollback the transaction before
3652 ** continuing.
3654 ** ^[SQLITE_DONE] means that the statement has finished executing
3655 ** successfully. sqlite3_step() should not be called again on this virtual
3656 ** machine without first calling [sqlite3_reset()] to reset the virtual
3657 ** machine back to its initial state.
3659 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3660 ** is returned each time a new row of data is ready for processing by the
3661 ** caller. The values may be accessed using the [column access functions].
3662 ** sqlite3_step() is called again to retrieve the next row of data.
3664 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3665 ** violation) has occurred. sqlite3_step() should not be called again on
3666 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3667 ** ^With the legacy interface, a more specific error code (for example,
3668 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3669 ** can be obtained by calling [sqlite3_reset()] on the
3670 ** [prepared statement]. ^In the "v2" interface,
3671 ** the more specific error code is returned directly by sqlite3_step().
3673 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3674 ** Perhaps it was called on a [prepared statement] that has
3675 ** already been [sqlite3_finalize | finalized] or on one that had
3676 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
3677 ** be the case that the same database connection is being used by two or
3678 ** more threads at the same moment in time.
3680 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3681 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
3682 ** other than [SQLITE_ROW] before any subsequent invocation of
3683 ** sqlite3_step(). Failure to reset the prepared statement using
3684 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3685 ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
3686 ** calling [sqlite3_reset()] automatically in this circumstance rather
3687 ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
3688 ** break because any application that ever receives an SQLITE_MISUSE error
3689 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
3690 ** can be used to restore the legacy behavior.
3692 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3693 ** API always returns a generic error code, [SQLITE_ERROR], following any
3694 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
3695 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3696 ** specific [error codes] that better describes the error.
3697 ** We admit that this is a goofy design. The problem has been fixed
3698 ** with the "v2" interface. If you prepare all of your SQL statements
3699 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3700 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3701 ** then the more specific [error codes] are returned directly
3702 ** by sqlite3_step(). The use of the "v2" interface is recommended.
3704 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3707 ** CAPI3REF: Number of columns in a result set
3709 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3710 ** current row of the result set of [prepared statement] P.
3711 ** ^If prepared statement P does not have results ready to return
3712 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3713 ** interfaces) then sqlite3_data_count(P) returns 0.
3714 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3716 ** See also: [sqlite3_column_count()]
3718 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3721 ** CAPI3REF: Fundamental Datatypes
3722 ** KEYWORDS: SQLITE_TEXT
3724 ** ^(Every value in SQLite has one of five fundamental datatypes:
3726 ** <ul>
3727 ** <li> 64-bit signed integer
3728 ** <li> 64-bit IEEE floating point number
3729 ** <li> string
3730 ** <li> BLOB
3731 ** <li> NULL
3732 ** </ul>)^
3734 ** These constants are codes for each of those types.
3736 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3737 ** for a completely different meaning. Software that links against both
3738 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3739 ** SQLITE_TEXT.
3741 #define SQLITE_INTEGER 1
3742 #define SQLITE_FLOAT 2
3743 #define SQLITE_BLOB 4
3744 #define SQLITE_NULL 5
3745 #ifdef SQLITE_TEXT
3746 # undef SQLITE_TEXT
3747 #else
3748 # define SQLITE_TEXT 3
3749 #endif
3750 #define SQLITE3_TEXT 3
3753 ** CAPI3REF: Result Values From A Query
3754 ** KEYWORDS: {column access functions}
3756 ** These routines form the "result set" interface.
3758 ** ^These routines return information about a single column of the current
3759 ** result row of a query. ^In every case the first argument is a pointer
3760 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3761 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3762 ** and the second argument is the index of the column for which information
3763 ** should be returned. ^The leftmost column of the result set has the index 0.
3764 ** ^The number of columns in the result can be determined using
3765 ** [sqlite3_column_count()].
3767 ** If the SQL statement does not currently point to a valid row, or if the
3768 ** column index is out of range, the result is undefined.
3769 ** These routines may only be called when the most recent call to
3770 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3771 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3772 ** If any of these routines are called after [sqlite3_reset()] or
3773 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3774 ** something other than [SQLITE_ROW], the results are undefined.
3775 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3776 ** are called from a different thread while any of these routines
3777 ** are pending, then the results are undefined.
3779 ** ^The sqlite3_column_type() routine returns the
3780 ** [SQLITE_INTEGER | datatype code] for the initial data type
3781 ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
3782 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
3783 ** returned by sqlite3_column_type() is only meaningful if no type
3784 ** conversions have occurred as described below. After a type conversion,
3785 ** the value returned by sqlite3_column_type() is undefined. Future
3786 ** versions of SQLite may change the behavior of sqlite3_column_type()
3787 ** following a type conversion.
3789 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3790 ** routine returns the number of bytes in that BLOB or string.
3791 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3792 ** the string to UTF-8 and then returns the number of bytes.
3793 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3794 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3795 ** the number of bytes in that string.
3796 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3798 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3799 ** routine returns the number of bytes in that BLOB or string.
3800 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3801 ** the string to UTF-16 and then returns the number of bytes.
3802 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3803 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3804 ** the number of bytes in that string.
3805 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3807 ** ^The values returned by [sqlite3_column_bytes()] and
3808 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3809 ** of the string. ^For clarity: the values returned by
3810 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3811 ** bytes in the string, not the number of characters.
3813 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3814 ** even empty strings, are always zero terminated. ^The return
3815 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3817 ** ^The object returned by [sqlite3_column_value()] is an
3818 ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
3819 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3820 ** If the [unprotected sqlite3_value] object returned by
3821 ** [sqlite3_column_value()] is used in any other way, including calls
3822 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3823 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3825 ** These routines attempt to convert the value where appropriate. ^For
3826 ** example, if the internal representation is FLOAT and a text result
3827 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3828 ** conversion automatically. ^(The following table details the conversions
3829 ** that are applied:
3831 ** <blockquote>
3832 ** <table border="1">
3833 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
3835 ** <tr><td> NULL <td> INTEGER <td> Result is 0
3836 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
3837 ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
3838 ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
3839 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
3840 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
3841 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
3842 ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
3843 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
3844 ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
3845 ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
3846 ** <tr><td> TEXT <td> FLOAT <td> Use atof()
3847 ** <tr><td> TEXT <td> BLOB <td> No change
3848 ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
3849 ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
3850 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
3851 ** </table>
3852 ** </blockquote>)^
3854 ** The table above makes reference to standard C library functions atoi()
3855 ** and atof(). SQLite does not really use these functions. It has its
3856 ** own equivalent internal routines. The atoi() and atof() names are
3857 ** used in the table for brevity and because they are familiar to most
3858 ** C programmers.
3860 ** Note that when type conversions occur, pointers returned by prior
3861 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3862 ** sqlite3_column_text16() may be invalidated.
3863 ** Type conversions and pointer invalidations might occur
3864 ** in the following cases:
3866 ** <ul>
3867 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3868 ** sqlite3_column_text16() is called. A zero-terminator might
3869 ** need to be added to the string.</li>
3870 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3871 ** sqlite3_column_text16() is called. The content must be converted
3872 ** to UTF-16.</li>
3873 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3874 ** sqlite3_column_text() is called. The content must be converted
3875 ** to UTF-8.</li>
3876 ** </ul>
3878 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3879 ** not invalidate a prior pointer, though of course the content of the buffer
3880 ** that the prior pointer references will have been modified. Other kinds
3881 ** of conversion are done in place when it is possible, but sometimes they
3882 ** are not possible and in those cases prior pointers are invalidated.
3884 ** The safest and easiest to remember policy is to invoke these routines
3885 ** in one of the following ways:
3887 ** <ul>
3888 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3889 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3890 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3891 ** </ul>
3893 ** In other words, you should call sqlite3_column_text(),
3894 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3895 ** into the desired format, then invoke sqlite3_column_bytes() or
3896 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
3897 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3898 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3899 ** with calls to sqlite3_column_bytes().
3901 ** ^The pointers returned are valid until a type conversion occurs as
3902 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3903 ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
3904 ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
3905 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3906 ** [sqlite3_free()].
3908 ** ^(If a memory allocation error occurs during the evaluation of any
3909 ** of these routines, a default value is returned. The default value
3910 ** is either the integer 0, the floating point number 0.0, or a NULL
3911 ** pointer. Subsequent calls to [sqlite3_errcode()] will return
3912 ** [SQLITE_NOMEM].)^
3914 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3915 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3916 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3917 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3918 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3919 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3920 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3921 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3922 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3923 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3926 ** CAPI3REF: Destroy A Prepared Statement Object
3928 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3929 ** ^If the most recent evaluation of the statement encountered no errors or
3930 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
3931 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
3932 ** sqlite3_finalize(S) returns the appropriate [error code] or
3933 ** [extended error code].
3935 ** ^The sqlite3_finalize(S) routine can be called at any point during
3936 ** the life cycle of [prepared statement] S:
3937 ** before statement S is ever evaluated, after
3938 ** one or more calls to [sqlite3_reset()], or after any call
3939 ** to [sqlite3_step()] regardless of whether or not the statement has
3940 ** completed execution.
3942 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3944 ** The application must finalize every [prepared statement] in order to avoid
3945 ** resource leaks. It is a grievous error for the application to try to use
3946 ** a prepared statement after it has been finalized. Any use of a prepared
3947 ** statement after it has been finalized can result in undefined and
3948 ** undesirable behavior such as segfaults and heap corruption.
3950 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3953 ** CAPI3REF: Reset A Prepared Statement Object
3955 ** The sqlite3_reset() function is called to reset a [prepared statement]
3956 ** object back to its initial state, ready to be re-executed.
3957 ** ^Any SQL statement variables that had values bound to them using
3958 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3959 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3961 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3962 ** back to the beginning of its program.
3964 ** ^If the most recent call to [sqlite3_step(S)] for the
3965 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3966 ** or if [sqlite3_step(S)] has never before been called on S,
3967 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
3969 ** ^If the most recent call to [sqlite3_step(S)] for the
3970 ** [prepared statement] S indicated an error, then
3971 ** [sqlite3_reset(S)] returns an appropriate [error code].
3973 ** ^The [sqlite3_reset(S)] interface does not change the values
3974 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3976 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3979 ** CAPI3REF: Create Or Redefine SQL Functions
3980 ** KEYWORDS: {function creation routines}
3981 ** KEYWORDS: {application-defined SQL function}
3982 ** KEYWORDS: {application-defined SQL functions}
3984 ** ^These functions (collectively known as "function creation routines")
3985 ** are used to add SQL functions or aggregates or to redefine the behavior
3986 ** of existing SQL functions or aggregates. The only differences between
3987 ** these routines are the text encoding expected for
3988 ** the second parameter (the name of the function being created)
3989 ** and the presence or absence of a destructor callback for
3990 ** the application data pointer.
3992 ** ^The first parameter is the [database connection] to which the SQL
3993 ** function is to be added. ^If an application uses more than one database
3994 ** connection then application-defined SQL functions must be added
3995 ** to each database connection separately.
3997 ** ^The second parameter is the name of the SQL function to be created or
3998 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
3999 ** representation, exclusive of the zero-terminator. ^Note that the name
4000 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4001 ** ^Any attempt to create a function with a longer name
4002 ** will result in [SQLITE_MISUSE] being returned.
4004 ** ^The third parameter (nArg)
4005 ** is the number of arguments that the SQL function or
4006 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4007 ** aggregate may take any number of arguments between 0 and the limit
4008 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
4009 ** parameter is less than -1 or greater than 127 then the behavior is
4010 ** undefined.
4012 ** ^The fourth parameter, eTextRep, specifies what
4013 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4014 ** its parameters. Every SQL function implementation must be able to work
4015 ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
4016 ** more efficient with one encoding than another. ^An application may
4017 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4018 ** times with the same function but with different values of eTextRep.
4019 ** ^When multiple implementations of the same function are available, SQLite
4020 ** will pick the one that involves the least amount of data conversion.
4021 ** If there is only a single implementation which does not care what text
4022 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4024 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
4025 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4027 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4028 ** pointers to C-language functions that implement the SQL function or
4029 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4030 ** callback only; NULL pointers must be passed as the xStep and xFinal
4031 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4032 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4033 ** SQL function or aggregate, pass NULL pointers for all three function
4034 ** callbacks.
4036 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4037 ** then it is destructor for the application data pointer.
4038 ** The destructor is invoked when the function is deleted, either by being
4039 ** overloaded or when the database connection closes.)^
4040 ** ^The destructor is also invoked if the call to
4041 ** sqlite3_create_function_v2() fails.
4042 ** ^When the destructor callback of the tenth parameter is invoked, it
4043 ** is passed a single argument which is a copy of the application data
4044 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4046 ** ^It is permitted to register multiple implementations of the same
4047 ** functions with the same name but with either differing numbers of
4048 ** arguments or differing preferred text encodings. ^SQLite will use
4049 ** the implementation that most closely matches the way in which the
4050 ** SQL function is used. ^A function implementation with a non-negative
4051 ** nArg parameter is a better match than a function implementation with
4052 ** a negative nArg. ^A function where the preferred text encoding
4053 ** matches the database encoding is a better
4054 ** match than a function where the encoding is different.
4055 ** ^A function where the encoding difference is between UTF16le and UTF16be
4056 ** is a closer match than a function where the encoding difference is
4057 ** between UTF8 and UTF16.
4059 ** ^Built-in functions may be overloaded by new application-defined functions.
4061 ** ^An application-defined function is permitted to call other
4062 ** SQLite interfaces. However, such calls must not
4063 ** close the database connection nor finalize or reset the prepared
4064 ** statement in which the function is running.
4066 SQLITE_API int sqlite3_create_function(
4067 sqlite3 *db,
4068 const char *zFunctionName,
4069 int nArg,
4070 int eTextRep,
4071 void *pApp,
4072 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4073 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4074 void (*xFinal)(sqlite3_context*)
4076 SQLITE_API int sqlite3_create_function16(
4077 sqlite3 *db,
4078 const void *zFunctionName,
4079 int nArg,
4080 int eTextRep,
4081 void *pApp,
4082 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4083 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4084 void (*xFinal)(sqlite3_context*)
4086 SQLITE_API int sqlite3_create_function_v2(
4087 sqlite3 *db,
4088 const char *zFunctionName,
4089 int nArg,
4090 int eTextRep,
4091 void *pApp,
4092 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4093 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4094 void (*xFinal)(sqlite3_context*),
4095 void(*xDestroy)(void*)
4099 ** CAPI3REF: Text Encodings
4101 ** These constant define integer codes that represent the various
4102 ** text encodings supported by SQLite.
4104 #define SQLITE_UTF8 1
4105 #define SQLITE_UTF16LE 2
4106 #define SQLITE_UTF16BE 3
4107 #define SQLITE_UTF16 4 /* Use native byte order */
4108 #define SQLITE_ANY 5 /* sqlite3_create_function only */
4109 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
4112 ** CAPI3REF: Deprecated Functions
4113 ** DEPRECATED
4115 ** These functions are [deprecated]. In order to maintain
4116 ** backwards compatibility with older code, these functions continue
4117 ** to be supported. However, new applications should avoid
4118 ** the use of these functions. To help encourage people to avoid
4119 ** using these functions, we are not going to tell you what they do.
4121 #ifndef SQLITE_OMIT_DEPRECATED
4122 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4123 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4124 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4125 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4126 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4127 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4128 #endif
4131 ** CAPI3REF: Obtaining SQL Function Parameter Values
4133 ** The C-language implementation of SQL functions and aggregates uses
4134 ** this set of interface routines to access the parameter values on
4135 ** the function or aggregate.
4137 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4138 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4139 ** define callbacks that implement the SQL functions and aggregates.
4140 ** The 3rd parameter to these callbacks is an array of pointers to
4141 ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
4142 ** each parameter to the SQL function. These routines are used to
4143 ** extract values from the [sqlite3_value] objects.
4145 ** These routines work only with [protected sqlite3_value] objects.
4146 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4147 ** object results in undefined behavior.
4149 ** ^These routines work just like the corresponding [column access functions]
4150 ** except that these routines take a single [protected sqlite3_value] object
4151 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4153 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4154 ** in the native byte-order of the host machine. ^The
4155 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4156 ** extract UTF-16 strings as big-endian and little-endian respectively.
4158 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4159 ** numeric affinity to the value. This means that an attempt is
4160 ** made to convert the value to an integer or floating point. If
4161 ** such a conversion is possible without loss of information (in other
4162 ** words, if the value is a string that looks like a number)
4163 ** then the conversion is performed. Otherwise no conversion occurs.
4164 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4166 ** Please pay particular attention to the fact that the pointer returned
4167 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4168 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4169 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4170 ** or [sqlite3_value_text16()].
4172 ** These routines must be called from the same thread as
4173 ** the SQL function that supplied the [sqlite3_value*] parameters.
4175 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4176 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4177 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4178 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4179 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4180 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4181 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4182 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4183 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4184 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4185 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4186 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4189 ** CAPI3REF: Obtain Aggregate Function Context
4191 ** Implementations of aggregate SQL functions use this
4192 ** routine to allocate memory for storing their state.
4194 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4195 ** for a particular aggregate function, SQLite
4196 ** allocates N of memory, zeroes out that memory, and returns a pointer
4197 ** to the new memory. ^On second and subsequent calls to
4198 ** sqlite3_aggregate_context() for the same aggregate function instance,
4199 ** the same buffer is returned. Sqlite3_aggregate_context() is normally
4200 ** called once for each invocation of the xStep callback and then one
4201 ** last time when the xFinal callback is invoked. ^(When no rows match
4202 ** an aggregate query, the xStep() callback of the aggregate function
4203 ** implementation is never called and xFinal() is called exactly once.
4204 ** In those cases, sqlite3_aggregate_context() might be called for the
4205 ** first time from within xFinal().)^
4207 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4208 ** less than or equal to zero or if a memory allocate error occurs.
4210 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4211 ** determined by the N parameter on first successful call. Changing the
4212 ** value of N in subsequent call to sqlite3_aggregate_context() within
4213 ** the same aggregate function instance will not resize the memory
4214 ** allocation.)^
4216 ** ^SQLite automatically frees the memory allocated by
4217 ** sqlite3_aggregate_context() when the aggregate query concludes.
4219 ** The first parameter must be a copy of the
4220 ** [sqlite3_context | SQL function context] that is the first parameter
4221 ** to the xStep or xFinal callback routine that implements the aggregate
4222 ** function.
4224 ** This routine must be called from the same thread in which
4225 ** the aggregate SQL function is running.
4227 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4230 ** CAPI3REF: User Data For Functions
4232 ** ^The sqlite3_user_data() interface returns a copy of
4233 ** the pointer that was the pUserData parameter (the 5th parameter)
4234 ** of the [sqlite3_create_function()]
4235 ** and [sqlite3_create_function16()] routines that originally
4236 ** registered the application defined function.
4238 ** This routine must be called from the same thread in which
4239 ** the application-defined function is running.
4241 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4244 ** CAPI3REF: Database Connection For Functions
4246 ** ^The sqlite3_context_db_handle() interface returns a copy of
4247 ** the pointer to the [database connection] (the 1st parameter)
4248 ** of the [sqlite3_create_function()]
4249 ** and [sqlite3_create_function16()] routines that originally
4250 ** registered the application defined function.
4252 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4255 ** CAPI3REF: Function Auxiliary Data
4257 ** The following two functions may be used by scalar SQL functions to
4258 ** associate metadata with argument values. If the same value is passed to
4259 ** multiple invocations of the same SQL function during query execution, under
4260 ** some circumstances the associated metadata may be preserved. This may
4261 ** be used, for example, to add a regular-expression matching scalar
4262 ** function. The compiled version of the regular expression is stored as
4263 ** metadata associated with the SQL value passed as the regular expression
4264 ** pattern. The compiled regular expression can be reused on multiple
4265 ** invocations of the same function so that the original pattern string
4266 ** does not need to be recompiled on each invocation.
4268 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4269 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4270 ** value to the application-defined function. ^If no metadata has been ever
4271 ** been set for the Nth argument of the function, or if the corresponding
4272 ** function parameter has changed since the meta-data was set,
4273 ** then sqlite3_get_auxdata() returns a NULL pointer.
4275 ** ^The sqlite3_set_auxdata() interface saves the metadata
4276 ** pointed to by its 3rd parameter as the metadata for the N-th
4277 ** argument of the application-defined function. Subsequent
4278 ** calls to sqlite3_get_auxdata() might return this data, if it has
4279 ** not been destroyed.
4280 ** ^If it is not NULL, SQLite will invoke the destructor
4281 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4282 ** the metadata when the corresponding function parameter changes
4283 ** or when the SQL statement completes, whichever comes first.
4285 ** SQLite is free to call the destructor and drop metadata on any
4286 ** parameter of any function at any time. ^The only guarantee is that
4287 ** the destructor will be called before the metadata is dropped.
4289 ** ^(In practice, metadata is preserved between function calls for
4290 ** expressions that are constant at compile time. This includes literal
4291 ** values and [parameters].)^
4293 ** These routines must be called from the same thread in which
4294 ** the SQL function is running.
4296 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4297 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4301 ** CAPI3REF: Constants Defining Special Destructor Behavior
4303 ** These are special values for the destructor that is passed in as the
4304 ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
4305 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4306 ** and will never change. It does not need to be destroyed. ^The
4307 ** SQLITE_TRANSIENT value means that the content will likely change in
4308 ** the near future and that SQLite should make its own private copy of
4309 ** the content before returning.
4311 ** The typedef is necessary to work around problems in certain
4312 ** C++ compilers. See ticket #2191.
4314 typedef void (*sqlite3_destructor_type)(void*);
4315 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
4316 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
4319 ** CAPI3REF: Setting The Result Of An SQL Function
4321 ** These routines are used by the xFunc or xFinal callbacks that
4322 ** implement SQL functions and aggregates. See
4323 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4324 ** for additional information.
4326 ** These functions work very much like the [parameter binding] family of
4327 ** functions used to bind values to host parameters in prepared statements.
4328 ** Refer to the [SQL parameter] documentation for additional information.
4330 ** ^The sqlite3_result_blob() interface sets the result from
4331 ** an application-defined function to be the BLOB whose content is pointed
4332 ** to by the second parameter and which is N bytes long where N is the
4333 ** third parameter.
4335 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4336 ** the application-defined function to be a BLOB containing all zero
4337 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4339 ** ^The sqlite3_result_double() interface sets the result from
4340 ** an application-defined function to be a floating point value specified
4341 ** by its 2nd argument.
4343 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4344 ** cause the implemented SQL function to throw an exception.
4345 ** ^SQLite uses the string pointed to by the
4346 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4347 ** as the text of an error message. ^SQLite interprets the error
4348 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4349 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4350 ** byte order. ^If the third parameter to sqlite3_result_error()
4351 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4352 ** message all text up through the first zero character.
4353 ** ^If the third parameter to sqlite3_result_error() or
4354 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4355 ** bytes (not characters) from the 2nd parameter as the error message.
4356 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4357 ** routines make a private copy of the error message text before
4358 ** they return. Hence, the calling function can deallocate or
4359 ** modify the text after they return without harm.
4360 ** ^The sqlite3_result_error_code() function changes the error code
4361 ** returned by SQLite as a result of an error in a function. ^By default,
4362 ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
4363 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4365 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4366 ** indicating that a string or BLOB is too long to represent.
4368 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4369 ** indicating that a memory allocation failed.
4371 ** ^The sqlite3_result_int() interface sets the return value
4372 ** of the application-defined function to be the 32-bit signed integer
4373 ** value given in the 2nd argument.
4374 ** ^The sqlite3_result_int64() interface sets the return value
4375 ** of the application-defined function to be the 64-bit signed integer
4376 ** value given in the 2nd argument.
4378 ** ^The sqlite3_result_null() interface sets the return value
4379 ** of the application-defined function to be NULL.
4381 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4382 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4383 ** set the return value of the application-defined function to be
4384 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4385 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4386 ** ^SQLite takes the text result from the application from
4387 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4388 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4389 ** is negative, then SQLite takes result text from the 2nd parameter
4390 ** through the first zero character.
4391 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4392 ** is non-negative, then as many bytes (not characters) of the text
4393 ** pointed to by the 2nd parameter are taken as the application-defined
4394 ** function result.
4395 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4396 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4397 ** function as the destructor on the text or BLOB result when it has
4398 ** finished using that result.
4399 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4400 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4401 ** assumes that the text or BLOB result is in constant space and does not
4402 ** copy the content of the parameter nor call a destructor on the content
4403 ** when it has finished using that result.
4404 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4405 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4406 ** then SQLite makes a copy of the result into space obtained from
4407 ** from [sqlite3_malloc()] before it returns.
4409 ** ^The sqlite3_result_value() interface sets the result of
4410 ** the application-defined function to be a copy the
4411 ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
4412 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4413 ** so that the [sqlite3_value] specified in the parameter may change or
4414 ** be deallocated after sqlite3_result_value() returns without harm.
4415 ** ^A [protected sqlite3_value] object may always be used where an
4416 ** [unprotected sqlite3_value] object is required, so either
4417 ** kind of [sqlite3_value] object can be used with this interface.
4419 ** If these routines are called from within the different thread
4420 ** than the one containing the application-defined function that received
4421 ** the [sqlite3_context] pointer, the results are undefined.
4423 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4424 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4425 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4426 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4427 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4428 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4429 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4430 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4431 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4432 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4433 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4434 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4435 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4436 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4437 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4438 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4441 ** CAPI3REF: Define New Collating Sequences
4443 ** ^These functions add, remove, or modify a [collation] associated
4444 ** with the [database connection] specified as the first argument.
4446 ** ^The name of the collation is a UTF-8 string
4447 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4448 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4449 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4450 ** considered to be the same name.
4452 ** ^(The third argument (eTextRep) must be one of the constants:
4453 ** <ul>
4454 ** <li> [SQLITE_UTF8],
4455 ** <li> [SQLITE_UTF16LE],
4456 ** <li> [SQLITE_UTF16BE],
4457 ** <li> [SQLITE_UTF16], or
4458 ** <li> [SQLITE_UTF16_ALIGNED].
4459 ** </ul>)^
4460 ** ^The eTextRep argument determines the encoding of strings passed
4461 ** to the collating function callback, xCallback.
4462 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4463 ** force strings to be UTF16 with native byte order.
4464 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4465 ** on an even byte address.
4467 ** ^The fourth argument, pArg, is an application data pointer that is passed
4468 ** through as the first argument to the collating function callback.
4470 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4471 ** ^Multiple collating functions can be registered using the same name but
4472 ** with different eTextRep parameters and SQLite will use whichever
4473 ** function requires the least amount of data transformation.
4474 ** ^If the xCallback argument is NULL then the collating function is
4475 ** deleted. ^When all collating functions having the same name are deleted,
4476 ** that collation is no longer usable.
4478 ** ^The collating function callback is invoked with a copy of the pArg
4479 ** application data pointer and with two strings in the encoding specified
4480 ** by the eTextRep argument. The collating function must return an
4481 ** integer that is negative, zero, or positive
4482 ** if the first string is less than, equal to, or greater than the second,
4483 ** respectively. A collating function must always return the same answer
4484 ** given the same inputs. If two or more collating functions are registered
4485 ** to the same collation name (using different eTextRep values) then all
4486 ** must give an equivalent answer when invoked with equivalent strings.
4487 ** The collating function must obey the following properties for all
4488 ** strings A, B, and C:
4490 ** <ol>
4491 ** <li> If A==B then B==A.
4492 ** <li> If A==B and B==C then A==C.
4493 ** <li> If A&lt;B THEN B&gt;A.
4494 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4495 ** </ol>
4497 ** If a collating function fails any of the above constraints and that
4498 ** collating function is registered and used, then the behavior of SQLite
4499 ** is undefined.
4501 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4502 ** with the addition that the xDestroy callback is invoked on pArg when
4503 ** the collating function is deleted.
4504 ** ^Collating functions are deleted when they are overridden by later
4505 ** calls to the collation creation functions or when the
4506 ** [database connection] is closed using [sqlite3_close()].
4508 ** ^The xDestroy callback is <u>not</u> called if the
4509 ** sqlite3_create_collation_v2() function fails. Applications that invoke
4510 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4511 ** check the return code and dispose of the application data pointer
4512 ** themselves rather than expecting SQLite to deal with it for them.
4513 ** This is different from every other SQLite interface. The inconsistency
4514 ** is unfortunate but cannot be changed without breaking backwards
4515 ** compatibility.
4517 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4519 SQLITE_API int sqlite3_create_collation(
4520 sqlite3*,
4521 const char *zName,
4522 int eTextRep,
4523 void *pArg,
4524 int(*xCompare)(void*,int,const void*,int,const void*)
4526 SQLITE_API int sqlite3_create_collation_v2(
4527 sqlite3*,
4528 const char *zName,
4529 int eTextRep,
4530 void *pArg,
4531 int(*xCompare)(void*,int,const void*,int,const void*),
4532 void(*xDestroy)(void*)
4534 SQLITE_API int sqlite3_create_collation16(
4535 sqlite3*,
4536 const void *zName,
4537 int eTextRep,
4538 void *pArg,
4539 int(*xCompare)(void*,int,const void*,int,const void*)
4543 ** CAPI3REF: Collation Needed Callbacks
4545 ** ^To avoid having to register all collation sequences before a database
4546 ** can be used, a single callback function may be registered with the
4547 ** [database connection] to be invoked whenever an undefined collation
4548 ** sequence is required.
4550 ** ^If the function is registered using the sqlite3_collation_needed() API,
4551 ** then it is passed the names of undefined collation sequences as strings
4552 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4553 ** the names are passed as UTF-16 in machine native byte order.
4554 ** ^A call to either function replaces the existing collation-needed callback.
4556 ** ^(When the callback is invoked, the first argument passed is a copy
4557 ** of the second argument to sqlite3_collation_needed() or
4558 ** sqlite3_collation_needed16(). The second argument is the database
4559 ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4560 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4561 ** sequence function required. The fourth parameter is the name of the
4562 ** required collation sequence.)^
4564 ** The callback function should register the desired collation using
4565 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4566 ** [sqlite3_create_collation_v2()].
4568 SQLITE_API int sqlite3_collation_needed(
4569 sqlite3*,
4570 void*,
4571 void(*)(void*,sqlite3*,int eTextRep,const char*)
4573 SQLITE_API int sqlite3_collation_needed16(
4574 sqlite3*,
4575 void*,
4576 void(*)(void*,sqlite3*,int eTextRep,const void*)
4579 #ifdef SQLITE_HAS_CODEC
4581 ** Specify the key for an encrypted database. This routine should be
4582 ** called right after sqlite3_open().
4584 ** The code to implement this API is not available in the public release
4585 ** of SQLite.
4587 SQLITE_API int sqlite3_key(
4588 sqlite3 *db, /* Database to be rekeyed */
4589 const void *pKey, int nKey /* The key */
4593 ** Change the key on an open database. If the current database is not
4594 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
4595 ** database is decrypted.
4597 ** The code to implement this API is not available in the public release
4598 ** of SQLite.
4600 SQLITE_API int sqlite3_rekey(
4601 sqlite3 *db, /* Database to be rekeyed */
4602 const void *pKey, int nKey /* The new key */
4606 ** Specify the activation key for a SEE database. Unless
4607 ** activated, none of the SEE routines will work.
4609 SQLITE_API void sqlite3_activate_see(
4610 const char *zPassPhrase /* Activation phrase */
4612 #endif
4614 #ifdef SQLITE_ENABLE_CEROD
4616 ** Specify the activation key for a CEROD database. Unless
4617 ** activated, none of the CEROD routines will work.
4619 SQLITE_API void sqlite3_activate_cerod(
4620 const char *zPassPhrase /* Activation phrase */
4622 #endif
4625 ** CAPI3REF: Suspend Execution For A Short Time
4627 ** The sqlite3_sleep() function causes the current thread to suspend execution
4628 ** for at least a number of milliseconds specified in its parameter.
4630 ** If the operating system does not support sleep requests with
4631 ** millisecond time resolution, then the time will be rounded up to
4632 ** the nearest second. The number of milliseconds of sleep actually
4633 ** requested from the operating system is returned.
4635 ** ^SQLite implements this interface by calling the xSleep()
4636 ** method of the default [sqlite3_vfs] object. If the xSleep() method
4637 ** of the default VFS is not implemented correctly, or not implemented at
4638 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4639 ** in the previous paragraphs.
4641 SQLITE_API int sqlite3_sleep(int);
4644 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4646 ** ^(If this global variable is made to point to a string which is
4647 ** the name of a folder (a.k.a. directory), then all temporary files
4648 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4649 ** will be placed in that directory.)^ ^If this variable
4650 ** is a NULL pointer, then SQLite performs a search for an appropriate
4651 ** temporary file directory.
4653 ** It is not safe to read or modify this variable in more than one
4654 ** thread at a time. It is not safe to read or modify this variable
4655 ** if a [database connection] is being used at the same time in a separate
4656 ** thread.
4657 ** It is intended that this variable be set once
4658 ** as part of process initialization and before any SQLite interface
4659 ** routines have been called and that this variable remain unchanged
4660 ** thereafter.
4662 ** ^The [temp_store_directory pragma] may modify this variable and cause
4663 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
4664 ** the [temp_store_directory pragma] always assumes that any string
4665 ** that this variable points to is held in memory obtained from
4666 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4667 ** using [sqlite3_free].
4668 ** Hence, if this variable is modified directly, either it should be
4669 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4670 ** or else the use of the [temp_store_directory pragma] should be avoided.
4672 SQLITE_API char *sqlite3_temp_directory;
4675 ** CAPI3REF: Test For Auto-Commit Mode
4676 ** KEYWORDS: {autocommit mode}
4678 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4679 ** zero if the given database connection is or is not in autocommit mode,
4680 ** respectively. ^Autocommit mode is on by default.
4681 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4682 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4684 ** If certain kinds of errors occur on a statement within a multi-statement
4685 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4686 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4687 ** transaction might be rolled back automatically. The only way to
4688 ** find out whether SQLite automatically rolled back the transaction after
4689 ** an error is to use this function.
4691 ** If another thread changes the autocommit status of the database
4692 ** connection while this routine is running, then the return value
4693 ** is undefined.
4695 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4698 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4700 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4701 ** to which a [prepared statement] belongs. ^The [database connection]
4702 ** returned by sqlite3_db_handle is the same [database connection]
4703 ** that was the first argument
4704 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4705 ** create the statement in the first place.
4707 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4710 ** CAPI3REF: Find the next prepared statement
4712 ** ^This interface returns a pointer to the next [prepared statement] after
4713 ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
4714 ** then this interface returns a pointer to the first prepared statement
4715 ** associated with the database connection pDb. ^If no prepared statement
4716 ** satisfies the conditions of this routine, it returns NULL.
4718 ** The [database connection] pointer D in a call to
4719 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4720 ** connection and in particular must not be a NULL pointer.
4722 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4725 ** CAPI3REF: Commit And Rollback Notification Callbacks
4727 ** ^The sqlite3_commit_hook() interface registers a callback
4728 ** function to be invoked whenever a transaction is [COMMIT | committed].
4729 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4730 ** for the same database connection is overridden.
4731 ** ^The sqlite3_rollback_hook() interface registers a callback
4732 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4733 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4734 ** for the same database connection is overridden.
4735 ** ^The pArg argument is passed through to the callback.
4736 ** ^If the callback on a commit hook function returns non-zero,
4737 ** then the commit is converted into a rollback.
4739 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4740 ** return the P argument from the previous call of the same function
4741 ** on the same [database connection] D, or NULL for
4742 ** the first call for each function on D.
4744 ** The callback implementation must not do anything that will modify
4745 ** the database connection that invoked the callback. Any actions
4746 ** to modify the database connection must be deferred until after the
4747 ** completion of the [sqlite3_step()] call that triggered the commit
4748 ** or rollback hook in the first place.
4749 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4750 ** database connections for the meaning of "modify" in this paragraph.
4752 ** ^Registering a NULL function disables the callback.
4754 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4755 ** operation is allowed to continue normally. ^If the commit hook
4756 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4757 ** ^The rollback hook is invoked on a rollback that results from a commit
4758 ** hook returning non-zero, just as it would be with any other rollback.
4760 ** ^For the purposes of this API, a transaction is said to have been
4761 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4762 ** an error or constraint causes an implicit rollback to occur.
4763 ** ^The rollback callback is not invoked if a transaction is
4764 ** automatically rolled back because the database connection is closed.
4766 ** See also the [sqlite3_update_hook()] interface.
4768 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4769 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4772 ** CAPI3REF: Data Change Notification Callbacks
4774 ** ^The sqlite3_update_hook() interface registers a callback function
4775 ** with the [database connection] identified by the first argument
4776 ** to be invoked whenever a row is updated, inserted or deleted.
4777 ** ^Any callback set by a previous call to this function
4778 ** for the same database connection is overridden.
4780 ** ^The second argument is a pointer to the function to invoke when a
4781 ** row is updated, inserted or deleted.
4782 ** ^The first argument to the callback is a copy of the third argument
4783 ** to sqlite3_update_hook().
4784 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4785 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4786 ** to be invoked.
4787 ** ^The third and fourth arguments to the callback contain pointers to the
4788 ** database and table name containing the affected row.
4789 ** ^The final callback parameter is the [rowid] of the row.
4790 ** ^In the case of an update, this is the [rowid] after the update takes place.
4792 ** ^(The update hook is not invoked when internal system tables are
4793 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4795 ** ^In the current implementation, the update hook
4796 ** is not invoked when duplication rows are deleted because of an
4797 ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
4798 ** invoked when rows are deleted using the [truncate optimization].
4799 ** The exceptions defined in this paragraph might change in a future
4800 ** release of SQLite.
4802 ** The update hook implementation must not do anything that will modify
4803 ** the database connection that invoked the update hook. Any actions
4804 ** to modify the database connection must be deferred until after the
4805 ** completion of the [sqlite3_step()] call that triggered the update hook.
4806 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4807 ** database connections for the meaning of "modify" in this paragraph.
4809 ** ^The sqlite3_update_hook(D,C,P) function
4810 ** returns the P argument from the previous call
4811 ** on the same [database connection] D, or NULL for
4812 ** the first call on D.
4814 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4815 ** interfaces.
4817 SQLITE_API void *sqlite3_update_hook(
4818 sqlite3*,
4819 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4820 void*
4824 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4825 ** KEYWORDS: {shared cache}
4827 ** ^(This routine enables or disables the sharing of the database cache
4828 ** and schema data structures between [database connection | connections]
4829 ** to the same database. Sharing is enabled if the argument is true
4830 ** and disabled if the argument is false.)^
4832 ** ^Cache sharing is enabled and disabled for an entire process.
4833 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4834 ** sharing was enabled or disabled for each thread separately.
4836 ** ^(The cache sharing mode set by this interface effects all subsequent
4837 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4838 ** Existing database connections continue use the sharing mode
4839 ** that was in effect at the time they were opened.)^
4841 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4842 ** successfully. An [error code] is returned otherwise.)^
4844 ** ^Shared cache is disabled by default. But this might change in
4845 ** future releases of SQLite. Applications that care about shared
4846 ** cache setting should set it explicitly.
4848 ** See Also: [SQLite Shared-Cache Mode]
4850 SQLITE_API int sqlite3_enable_shared_cache(int);
4853 ** CAPI3REF: Attempt To Free Heap Memory
4855 ** ^The sqlite3_release_memory() interface attempts to free N bytes
4856 ** of heap memory by deallocating non-essential memory allocations
4857 ** held by the database library. Memory used to cache database
4858 ** pages to improve performance is an example of non-essential memory.
4859 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4860 ** which might be more or less than the amount requested.
4861 ** ^The sqlite3_release_memory() routine is a no-op returning zero
4862 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4864 SQLITE_API int sqlite3_release_memory(int);
4867 ** CAPI3REF: Impose A Limit On Heap Size
4869 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
4870 ** soft limit on the amount of heap memory that may be allocated by SQLite.
4871 ** ^SQLite strives to keep heap memory utilization below the soft heap
4872 ** limit by reducing the number of pages held in the page cache
4873 ** as heap memory usages approaches the limit.
4874 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
4875 ** below the limit, it will exceed the limit rather than generate
4876 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
4877 ** is advisory only.
4879 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
4880 ** the soft heap limit prior to the call. ^If the argument N is negative
4881 ** then no change is made to the soft heap limit. Hence, the current
4882 ** size of the soft heap limit can be determined by invoking
4883 ** sqlite3_soft_heap_limit64() with a negative argument.
4885 ** ^If the argument N is zero then the soft heap limit is disabled.
4887 ** ^(The soft heap limit is not enforced in the current implementation
4888 ** if one or more of following conditions are true:
4890 ** <ul>
4891 ** <li> The soft heap limit is set to zero.
4892 ** <li> Memory accounting is disabled using a combination of the
4893 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
4894 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
4895 ** <li> An alternative page cache implementation is specified using
4896 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
4897 ** <li> The page cache allocates from its own memory pool supplied
4898 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
4899 ** from the heap.
4900 ** </ul>)^
4902 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
4903 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
4904 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
4905 ** the soft heap limit is enforced on every memory allocation. Without
4906 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
4907 ** when memory is allocated by the page cache. Testing suggests that because
4908 ** the page cache is the predominate memory user in SQLite, most
4909 ** applications will achieve adequate soft heap limit enforcement without
4910 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4912 ** The circumstances under which SQLite will enforce the soft heap limit may
4913 ** changes in future releases of SQLite.
4915 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
4918 ** CAPI3REF: Deprecated Soft Heap Limit Interface
4919 ** DEPRECATED
4921 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
4922 ** interface. This routine is provided for historical compatibility
4923 ** only. All new applications should use the
4924 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
4926 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
4930 ** CAPI3REF: Extract Metadata About A Column Of A Table
4932 ** ^This routine returns metadata about a specific column of a specific
4933 ** database table accessible using the [database connection] handle
4934 ** passed as the first function argument.
4936 ** ^The column is identified by the second, third and fourth parameters to
4937 ** this function. ^The second parameter is either the name of the database
4938 ** (i.e. "main", "temp", or an attached database) containing the specified
4939 ** table or NULL. ^If it is NULL, then all attached databases are searched
4940 ** for the table using the same algorithm used by the database engine to
4941 ** resolve unqualified table references.
4943 ** ^The third and fourth parameters to this function are the table and column
4944 ** name of the desired column, respectively. Neither of these parameters
4945 ** may be NULL.
4947 ** ^Metadata is returned by writing to the memory locations passed as the 5th
4948 ** and subsequent parameters to this function. ^Any of these arguments may be
4949 ** NULL, in which case the corresponding element of metadata is omitted.
4951 ** ^(<blockquote>
4952 ** <table border="1">
4953 ** <tr><th> Parameter <th> Output<br>Type <th> Description
4955 ** <tr><td> 5th <td> const char* <td> Data type
4956 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4957 ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
4958 ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
4959 ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
4960 ** </table>
4961 ** </blockquote>)^
4963 ** ^The memory pointed to by the character pointers returned for the
4964 ** declaration type and collation sequence is valid only until the next
4965 ** call to any SQLite API function.
4967 ** ^If the specified table is actually a view, an [error code] is returned.
4969 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4970 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4971 ** parameters are set for the explicitly declared column. ^(If there is no
4972 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4973 ** parameters are set as follows:
4975 ** <pre>
4976 ** data type: "INTEGER"
4977 ** collation sequence: "BINARY"
4978 ** not null: 0
4979 ** primary key: 1
4980 ** auto increment: 0
4981 ** </pre>)^
4983 ** ^(This function may load one or more schemas from database files. If an
4984 ** error occurs during this process, or if the requested table or column
4985 ** cannot be found, an [error code] is returned and an error message left
4986 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4988 ** ^This API is only available if the library was compiled with the
4989 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4991 SQLITE_API int sqlite3_table_column_metadata(
4992 sqlite3 *db, /* Connection handle */
4993 const char *zDbName, /* Database name or NULL */
4994 const char *zTableName, /* Table name */
4995 const char *zColumnName, /* Column name */
4996 char const **pzDataType, /* OUTPUT: Declared data type */
4997 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
4998 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
4999 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
5000 int *pAutoinc /* OUTPUT: True if column is auto-increment */
5004 ** CAPI3REF: Load An Extension
5006 ** ^This interface loads an SQLite extension library from the named file.
5008 ** ^The sqlite3_load_extension() interface attempts to load an
5009 ** SQLite extension library contained in the file zFile.
5011 ** ^The entry point is zProc.
5012 ** ^zProc may be 0, in which case the name of the entry point
5013 ** defaults to "sqlite3_extension_init".
5014 ** ^The sqlite3_load_extension() interface returns
5015 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5016 ** ^If an error occurs and pzErrMsg is not 0, then the
5017 ** [sqlite3_load_extension()] interface shall attempt to
5018 ** fill *pzErrMsg with error message text stored in memory
5019 ** obtained from [sqlite3_malloc()]. The calling function
5020 ** should free this memory by calling [sqlite3_free()].
5022 ** ^Extension loading must be enabled using
5023 ** [sqlite3_enable_load_extension()] prior to calling this API,
5024 ** otherwise an error will be returned.
5026 ** See also the [load_extension() SQL function].
5028 SQLITE_API int sqlite3_load_extension(
5029 sqlite3 *db, /* Load the extension into this database connection */
5030 const char *zFile, /* Name of the shared library containing extension */
5031 const char *zProc, /* Entry point. Derived from zFile if 0 */
5032 char **pzErrMsg /* Put error message here if not 0 */
5036 ** CAPI3REF: Enable Or Disable Extension Loading
5038 ** ^So as not to open security holes in older applications that are
5039 ** unprepared to deal with extension loading, and as a means of disabling
5040 ** extension loading while evaluating user-entered SQL, the following API
5041 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5043 ** ^Extension loading is off by default. See ticket #1863.
5044 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5045 ** to turn extension loading on and call it with onoff==0 to turn
5046 ** it back off again.
5048 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5051 ** CAPI3REF: Automatically Load Statically Linked Extensions
5053 ** ^This interface causes the xEntryPoint() function to be invoked for
5054 ** each new [database connection] that is created. The idea here is that
5055 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5056 ** that is to be automatically loaded into all new database connections.
5058 ** ^(Even though the function prototype shows that xEntryPoint() takes
5059 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5060 ** arguments and expects and integer result as if the signature of the
5061 ** entry point where as follows:
5063 ** <blockquote><pre>
5064 ** &nbsp; int xEntryPoint(
5065 ** &nbsp; sqlite3 *db,
5066 ** &nbsp; const char **pzErrMsg,
5067 ** &nbsp; const struct sqlite3_api_routines *pThunk
5068 ** &nbsp; );
5069 ** </pre></blockquote>)^
5071 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5072 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5073 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
5074 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
5075 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
5076 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5077 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5079 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5080 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5081 ** will be called more than once for each database connection that is opened.
5083 ** See also: [sqlite3_reset_auto_extension()].
5085 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5088 ** CAPI3REF: Reset Automatic Extension Loading
5090 ** ^This interface disables all automatic extensions previously
5091 ** registered using [sqlite3_auto_extension()].
5093 SQLITE_API void sqlite3_reset_auto_extension(void);
5096 ** The interface to the virtual-table mechanism is currently considered
5097 ** to be experimental. The interface might change in incompatible ways.
5098 ** If this is a problem for you, do not use the interface at this time.
5100 ** When the virtual-table mechanism stabilizes, we will declare the
5101 ** interface fixed, support it indefinitely, and remove this comment.
5105 ** Structures used by the virtual table interface
5107 typedef struct sqlite3_vtab sqlite3_vtab;
5108 typedef struct sqlite3_index_info sqlite3_index_info;
5109 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5110 typedef struct sqlite3_module sqlite3_module;
5113 ** CAPI3REF: Virtual Table Object
5114 ** KEYWORDS: sqlite3_module {virtual table module}
5116 ** This structure, sometimes called a "virtual table module",
5117 ** defines the implementation of a [virtual tables].
5118 ** This structure consists mostly of methods for the module.
5120 ** ^A virtual table module is created by filling in a persistent
5121 ** instance of this structure and passing a pointer to that instance
5122 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5123 ** ^The registration remains valid until it is replaced by a different
5124 ** module or until the [database connection] closes. The content
5125 ** of this structure must not change while it is registered with
5126 ** any database connection.
5128 struct sqlite3_module {
5129 int iVersion;
5130 int (*xCreate)(sqlite3*, void *pAux,
5131 int argc, const char *const*argv,
5132 sqlite3_vtab **ppVTab, char**);
5133 int (*xConnect)(sqlite3*, void *pAux,
5134 int argc, const char *const*argv,
5135 sqlite3_vtab **ppVTab, char**);
5136 int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5137 int (*xDisconnect)(sqlite3_vtab *pVTab);
5138 int (*xDestroy)(sqlite3_vtab *pVTab);
5139 int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5140 int (*xClose)(sqlite3_vtab_cursor*);
5141 int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5142 int argc, sqlite3_value **argv);
5143 int (*xNext)(sqlite3_vtab_cursor*);
5144 int (*xEof)(sqlite3_vtab_cursor*);
5145 int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5146 int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5147 int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5148 int (*xBegin)(sqlite3_vtab *pVTab);
5149 int (*xSync)(sqlite3_vtab *pVTab);
5150 int (*xCommit)(sqlite3_vtab *pVTab);
5151 int (*xRollback)(sqlite3_vtab *pVTab);
5152 int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5153 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5154 void **ppArg);
5155 int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5159 ** CAPI3REF: Virtual Table Indexing Information
5160 ** KEYWORDS: sqlite3_index_info
5162 ** The sqlite3_index_info structure and its substructures is used as part
5163 ** of the [virtual table] interface to
5164 ** pass information into and receive the reply from the [xBestIndex]
5165 ** method of a [virtual table module]. The fields under **Inputs** are the
5166 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
5167 ** results into the **Outputs** fields.
5169 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5171 ** <blockquote>column OP expr</blockquote>
5173 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
5174 ** stored in aConstraint[].op using one of the
5175 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5176 ** ^(The index of the column is stored in
5177 ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
5178 ** expr on the right-hand side can be evaluated (and thus the constraint
5179 ** is usable) and false if it cannot.)^
5181 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5182 ** and makes other simplifications to the WHERE clause in an attempt to
5183 ** get as many WHERE clause terms into the form shown above as possible.
5184 ** ^The aConstraint[] array only reports WHERE clause terms that are
5185 ** relevant to the particular virtual table being queried.
5187 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5188 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5190 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5191 ** about what parameters to pass to xFilter. ^If argvIndex>0 then
5192 ** the right-hand side of the corresponding aConstraint[] is evaluated
5193 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
5194 ** is true, then the constraint is assumed to be fully handled by the
5195 ** virtual table and is not checked again by SQLite.)^
5197 ** ^The idxNum and idxPtr values are recorded and passed into the
5198 ** [xFilter] method.
5199 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5200 ** needToFreeIdxPtr is true.
5202 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5203 ** the correct order to satisfy the ORDER BY clause so that no separate
5204 ** sorting step is required.
5206 ** ^The estimatedCost value is an estimate of the cost of doing the
5207 ** particular lookup. A full scan of a table with N entries should have
5208 ** a cost of N. A binary search of a table of N entries should have a
5209 ** cost of approximately log(N).
5211 struct sqlite3_index_info {
5212 /* Inputs */
5213 int nConstraint; /* Number of entries in aConstraint */
5214 struct sqlite3_index_constraint {
5215 int iColumn; /* Column on left-hand side of constraint */
5216 unsigned char op; /* Constraint operator */
5217 unsigned char usable; /* True if this constraint is usable */
5218 int iTermOffset; /* Used internally - xBestIndex should ignore */
5219 } *aConstraint; /* Table of WHERE clause constraints */
5220 int nOrderBy; /* Number of terms in the ORDER BY clause */
5221 struct sqlite3_index_orderby {
5222 int iColumn; /* Column number */
5223 unsigned char desc; /* True for DESC. False for ASC. */
5224 } *aOrderBy; /* The ORDER BY clause */
5225 /* Outputs */
5226 struct sqlite3_index_constraint_usage {
5227 int argvIndex; /* if >0, constraint is part of argv to xFilter */
5228 unsigned char omit; /* Do not code a test for this constraint */
5229 } *aConstraintUsage;
5230 int idxNum; /* Number used to identify the index */
5231 char *idxStr; /* String, possibly obtained from sqlite3_malloc */
5232 int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
5233 int orderByConsumed; /* True if output is already ordered */
5234 double estimatedCost; /* Estimated cost of using this index */
5237 /* Begin preload-cache.patch for Chromium */
5239 ** Preload the databases into the pager cache, up to the maximum size of the
5240 ** pager cache.
5242 ** For a database to be loaded successfully, the pager must be active. That is,
5243 ** there must be an open statement on that database. See sqlite3pager_loadall
5245 ** There might be many databases attached to the given connection. We iterate
5246 ** them all and try to load them. If none are loadable successfully, we return
5247 ** an error. Otherwise, we return OK.
5249 SQLITE_API int sqlite3_preload(sqlite3 *db);
5250 /* End preload-cache.patch for Chromium */
5253 ** CAPI3REF: Virtual Table Constraint Operator Codes
5255 ** These macros defined the allowed values for the
5256 ** [sqlite3_index_info].aConstraint[].op field. Each value represents
5257 ** an operator that is part of a constraint term in the wHERE clause of
5258 ** a query that uses a [virtual table].
5260 #define SQLITE_INDEX_CONSTRAINT_EQ 2
5261 #define SQLITE_INDEX_CONSTRAINT_GT 4
5262 #define SQLITE_INDEX_CONSTRAINT_LE 8
5263 #define SQLITE_INDEX_CONSTRAINT_LT 16
5264 #define SQLITE_INDEX_CONSTRAINT_GE 32
5265 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5268 ** CAPI3REF: Register A Virtual Table Implementation
5270 ** ^These routines are used to register a new [virtual table module] name.
5271 ** ^Module names must be registered before
5272 ** creating a new [virtual table] using the module and before using a
5273 ** preexisting [virtual table] for the module.
5275 ** ^The module name is registered on the [database connection] specified
5276 ** by the first parameter. ^The name of the module is given by the
5277 ** second parameter. ^The third parameter is a pointer to
5278 ** the implementation of the [virtual table module]. ^The fourth
5279 ** parameter is an arbitrary client data pointer that is passed through
5280 ** into the [xCreate] and [xConnect] methods of the virtual table module
5281 ** when a new virtual table is be being created or reinitialized.
5283 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5284 ** is a pointer to a destructor for the pClientData. ^SQLite will
5285 ** invoke the destructor function (if it is not NULL) when SQLite
5286 ** no longer needs the pClientData pointer. ^The destructor will also
5287 ** be invoked if the call to sqlite3_create_module_v2() fails.
5288 ** ^The sqlite3_create_module()
5289 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5290 ** destructor.
5292 SQLITE_API int sqlite3_create_module(
5293 sqlite3 *db, /* SQLite connection to register module with */
5294 const char *zName, /* Name of the module */
5295 const sqlite3_module *p, /* Methods for the module */
5296 void *pClientData /* Client data for xCreate/xConnect */
5298 SQLITE_API int sqlite3_create_module_v2(
5299 sqlite3 *db, /* SQLite connection to register module with */
5300 const char *zName, /* Name of the module */
5301 const sqlite3_module *p, /* Methods for the module */
5302 void *pClientData, /* Client data for xCreate/xConnect */
5303 void(*xDestroy)(void*) /* Module destructor function */
5307 ** CAPI3REF: Virtual Table Instance Object
5308 ** KEYWORDS: sqlite3_vtab
5310 ** Every [virtual table module] implementation uses a subclass
5311 ** of this object to describe a particular instance
5312 ** of the [virtual table]. Each subclass will
5313 ** be tailored to the specific needs of the module implementation.
5314 ** The purpose of this superclass is to define certain fields that are
5315 ** common to all module implementations.
5317 ** ^Virtual tables methods can set an error message by assigning a
5318 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
5319 ** take care that any prior string is freed by a call to [sqlite3_free()]
5320 ** prior to assigning a new string to zErrMsg. ^After the error message
5321 ** is delivered up to the client application, the string will be automatically
5322 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5324 struct sqlite3_vtab {
5325 const sqlite3_module *pModule; /* The module for this virtual table */
5326 int nRef; /* NO LONGER USED */
5327 char *zErrMsg; /* Error message from sqlite3_mprintf() */
5328 /* Virtual table implementations will typically add additional fields */
5332 ** CAPI3REF: Virtual Table Cursor Object
5333 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5335 ** Every [virtual table module] implementation uses a subclass of the
5336 ** following structure to describe cursors that point into the
5337 ** [virtual table] and are used
5338 ** to loop through the virtual table. Cursors are created using the
5339 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5340 ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
5341 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5342 ** of the module. Each module implementation will define
5343 ** the content of a cursor structure to suit its own needs.
5345 ** This superclass exists in order to define fields of the cursor that
5346 ** are common to all implementations.
5348 struct sqlite3_vtab_cursor {
5349 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
5350 /* Virtual table implementations will typically add additional fields */
5354 ** CAPI3REF: Declare The Schema Of A Virtual Table
5356 ** ^The [xCreate] and [xConnect] methods of a
5357 ** [virtual table module] call this interface
5358 ** to declare the format (the names and datatypes of the columns) of
5359 ** the virtual tables they implement.
5361 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5364 ** CAPI3REF: Overload A Function For A Virtual Table
5366 ** ^(Virtual tables can provide alternative implementations of functions
5367 ** using the [xFindFunction] method of the [virtual table module].
5368 ** But global versions of those functions
5369 ** must exist in order to be overloaded.)^
5371 ** ^(This API makes sure a global version of a function with a particular
5372 ** name and number of parameters exists. If no such function exists
5373 ** before this API is called, a new function is created.)^ ^The implementation
5374 ** of the new function always causes an exception to be thrown. So
5375 ** the new function is not good for anything by itself. Its only
5376 ** purpose is to be a placeholder function that can be overloaded
5377 ** by a [virtual table].
5379 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5382 ** The interface to the virtual-table mechanism defined above (back up
5383 ** to a comment remarkably similar to this one) is currently considered
5384 ** to be experimental. The interface might change in incompatible ways.
5385 ** If this is a problem for you, do not use the interface at this time.
5387 ** When the virtual-table mechanism stabilizes, we will declare the
5388 ** interface fixed, support it indefinitely, and remove this comment.
5392 ** CAPI3REF: A Handle To An Open BLOB
5393 ** KEYWORDS: {BLOB handle} {BLOB handles}
5395 ** An instance of this object represents an open BLOB on which
5396 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5397 ** ^Objects of this type are created by [sqlite3_blob_open()]
5398 ** and destroyed by [sqlite3_blob_close()].
5399 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5400 ** can be used to read or write small subsections of the BLOB.
5401 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5403 typedef struct sqlite3_blob sqlite3_blob;
5406 ** CAPI3REF: Open A BLOB For Incremental I/O
5408 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5409 ** in row iRow, column zColumn, table zTable in database zDb;
5410 ** in other words, the same BLOB that would be selected by:
5412 ** <pre>
5413 ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5414 ** </pre>)^
5416 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5417 ** and write access. ^If it is zero, the BLOB is opened for read access.
5418 ** ^It is not possible to open a column that is part of an index or primary
5419 ** key for writing. ^If [foreign key constraints] are enabled, it is
5420 ** not possible to open a column that is part of a [child key] for writing.
5422 ** ^Note that the database name is not the filename that contains
5423 ** the database but rather the symbolic name of the database that
5424 ** appears after the AS keyword when the database is connected using [ATTACH].
5425 ** ^For the main database file, the database name is "main".
5426 ** ^For TEMP tables, the database name is "temp".
5428 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5429 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5430 ** to be a null pointer.)^
5431 ** ^This function sets the [database connection] error code and message
5432 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5433 ** functions. ^Note that the *ppBlob variable is always initialized in a
5434 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5435 ** regardless of the success or failure of this routine.
5437 ** ^(If the row that a BLOB handle points to is modified by an
5438 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5439 ** then the BLOB handle is marked as "expired".
5440 ** This is true if any column of the row is changed, even a column
5441 ** other than the one the BLOB handle is open on.)^
5442 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5443 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5444 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5445 ** rolled back by the expiration of the BLOB. Such changes will eventually
5446 ** commit if the transaction continues to completion.)^
5448 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5449 ** the opened blob. ^The size of a blob may not be changed by this
5450 ** interface. Use the [UPDATE] SQL command to change the size of a
5451 ** blob.
5453 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5454 ** and the built-in [zeroblob] SQL function can be used, if desired,
5455 ** to create an empty, zero-filled blob in which to read or write using
5456 ** this interface.
5458 ** To avoid a resource leak, every open [BLOB handle] should eventually
5459 ** be released by a call to [sqlite3_blob_close()].
5461 SQLITE_API int sqlite3_blob_open(
5462 sqlite3*,
5463 const char *zDb,
5464 const char *zTable,
5465 const char *zColumn,
5466 sqlite3_int64 iRow,
5467 int flags,
5468 sqlite3_blob **ppBlob
5472 ** CAPI3REF: Move a BLOB Handle to a New Row
5474 ** ^This function is used to move an existing blob handle so that it points
5475 ** to a different row of the same database table. ^The new row is identified
5476 ** by the rowid value passed as the second argument. Only the row can be
5477 ** changed. ^The database, table and column on which the blob handle is open
5478 ** remain the same. Moving an existing blob handle to a new row can be
5479 ** faster than closing the existing handle and opening a new one.
5481 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5482 ** it must exist and there must be either a blob or text value stored in
5483 ** the nominated column.)^ ^If the new row is not present in the table, or if
5484 ** it does not contain a blob or text value, or if another error occurs, an
5485 ** SQLite error code is returned and the blob handle is considered aborted.
5486 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5487 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5488 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5489 ** always returns zero.
5491 ** ^This function sets the database handle error code and message.
5493 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5496 ** CAPI3REF: Close A BLOB Handle
5498 ** ^Closes an open [BLOB handle].
5500 ** ^Closing a BLOB shall cause the current transaction to commit
5501 ** if there are no other BLOBs, no pending prepared statements, and the
5502 ** database connection is in [autocommit mode].
5503 ** ^If any writes were made to the BLOB, they might be held in cache
5504 ** until the close operation if they will fit.
5506 ** ^(Closing the BLOB often forces the changes
5507 ** out to disk and so if any I/O errors occur, they will likely occur
5508 ** at the time when the BLOB is closed. Any errors that occur during
5509 ** closing are reported as a non-zero return value.)^
5511 ** ^(The BLOB is closed unconditionally. Even if this routine returns
5512 ** an error code, the BLOB is still closed.)^
5514 ** ^Calling this routine with a null pointer (such as would be returned
5515 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5517 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5520 ** CAPI3REF: Return The Size Of An Open BLOB
5522 ** ^Returns the size in bytes of the BLOB accessible via the
5523 ** successfully opened [BLOB handle] in its only argument. ^The
5524 ** incremental blob I/O routines can only read or overwriting existing
5525 ** blob content; they cannot change the size of a blob.
5527 ** This routine only works on a [BLOB handle] which has been created
5528 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5529 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5530 ** to this routine results in undefined and probably undesirable behavior.
5532 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5535 ** CAPI3REF: Read Data From A BLOB Incrementally
5537 ** ^(This function is used to read data from an open [BLOB handle] into a
5538 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5539 ** from the open BLOB, starting at offset iOffset.)^
5541 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5542 ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
5543 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5544 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5545 ** can be determined using the [sqlite3_blob_bytes()] interface.
5547 ** ^An attempt to read from an expired [BLOB handle] fails with an
5548 ** error code of [SQLITE_ABORT].
5550 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5551 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5553 ** This routine only works on a [BLOB handle] which has been created
5554 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5555 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5556 ** to this routine results in undefined and probably undesirable behavior.
5558 ** See also: [sqlite3_blob_write()].
5560 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5563 ** CAPI3REF: Write Data Into A BLOB Incrementally
5565 ** ^This function is used to write data into an open [BLOB handle] from a
5566 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5567 ** into the open BLOB, starting at offset iOffset.
5569 ** ^If the [BLOB handle] passed as the first argument was not opened for
5570 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5571 ** this function returns [SQLITE_READONLY].
5573 ** ^This function may only modify the contents of the BLOB; it is
5574 ** not possible to increase the size of a BLOB using this API.
5575 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5576 ** [SQLITE_ERROR] is returned and no data is written. ^If N is
5577 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5578 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5579 ** can be determined using the [sqlite3_blob_bytes()] interface.
5581 ** ^An attempt to write to an expired [BLOB handle] fails with an
5582 ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
5583 ** before the [BLOB handle] expired are not rolled back by the
5584 ** expiration of the handle, though of course those changes might
5585 ** have been overwritten by the statement that expired the BLOB handle
5586 ** or by other independent statements.
5588 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5589 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5591 ** This routine only works on a [BLOB handle] which has been created
5592 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5593 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5594 ** to this routine results in undefined and probably undesirable behavior.
5596 ** See also: [sqlite3_blob_read()].
5598 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5601 ** CAPI3REF: Virtual File System Objects
5603 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5604 ** that SQLite uses to interact
5605 ** with the underlying operating system. Most SQLite builds come with a
5606 ** single default VFS that is appropriate for the host computer.
5607 ** New VFSes can be registered and existing VFSes can be unregistered.
5608 ** The following interfaces are provided.
5610 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5611 ** ^Names are case sensitive.
5612 ** ^Names are zero-terminated UTF-8 strings.
5613 ** ^If there is no match, a NULL pointer is returned.
5614 ** ^If zVfsName is NULL then the default VFS is returned.
5616 ** ^New VFSes are registered with sqlite3_vfs_register().
5617 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5618 ** ^The same VFS can be registered multiple times without injury.
5619 ** ^To make an existing VFS into the default VFS, register it again
5620 ** with the makeDflt flag set. If two different VFSes with the
5621 ** same name are registered, the behavior is undefined. If a
5622 ** VFS is registered with a name that is NULL or an empty string,
5623 ** then the behavior is undefined.
5625 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5626 ** ^(If the default VFS is unregistered, another VFS is chosen as
5627 ** the default. The choice for the new VFS is arbitrary.)^
5629 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5630 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5631 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5634 ** CAPI3REF: Mutexes
5636 ** The SQLite core uses these routines for thread
5637 ** synchronization. Though they are intended for internal
5638 ** use by SQLite, code that links against SQLite is
5639 ** permitted to use any of these routines.
5641 ** The SQLite source code contains multiple implementations
5642 ** of these mutex routines. An appropriate implementation
5643 ** is selected automatically at compile-time. ^(The following
5644 ** implementations are available in the SQLite core:
5646 ** <ul>
5647 ** <li> SQLITE_MUTEX_OS2
5648 ** <li> SQLITE_MUTEX_PTHREAD
5649 ** <li> SQLITE_MUTEX_W32
5650 ** <li> SQLITE_MUTEX_NOOP
5651 ** </ul>)^
5653 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5654 ** that does no real locking and is appropriate for use in
5655 ** a single-threaded application. ^The SQLITE_MUTEX_OS2,
5656 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5657 ** are appropriate for use on OS/2, Unix, and Windows.
5659 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5660 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5661 ** implementation is included with the library. In this case the
5662 ** application must supply a custom mutex implementation using the
5663 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5664 ** before calling sqlite3_initialize() or any other public sqlite3_
5665 ** function that calls sqlite3_initialize().)^
5667 ** ^The sqlite3_mutex_alloc() routine allocates a new
5668 ** mutex and returns a pointer to it. ^If it returns NULL
5669 ** that means that a mutex could not be allocated. ^SQLite
5670 ** will unwind its stack and return an error. ^(The argument
5671 ** to sqlite3_mutex_alloc() is one of these integer constants:
5673 ** <ul>
5674 ** <li> SQLITE_MUTEX_FAST
5675 ** <li> SQLITE_MUTEX_RECURSIVE
5676 ** <li> SQLITE_MUTEX_STATIC_MASTER
5677 ** <li> SQLITE_MUTEX_STATIC_MEM
5678 ** <li> SQLITE_MUTEX_STATIC_MEM2
5679 ** <li> SQLITE_MUTEX_STATIC_PRNG
5680 ** <li> SQLITE_MUTEX_STATIC_LRU
5681 ** <li> SQLITE_MUTEX_STATIC_LRU2
5682 ** </ul>)^
5684 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5685 ** cause sqlite3_mutex_alloc() to create
5686 ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5687 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5688 ** The mutex implementation does not need to make a distinction
5689 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5690 ** not want to. ^SQLite will only request a recursive mutex in
5691 ** cases where it really needs one. ^If a faster non-recursive mutex
5692 ** implementation is available on the host platform, the mutex subsystem
5693 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5695 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5696 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5697 ** a pointer to a static preexisting mutex. ^Six static mutexes are
5698 ** used by the current version of SQLite. Future versions of SQLite
5699 ** may add additional static mutexes. Static mutexes are for internal
5700 ** use by SQLite only. Applications that use SQLite mutexes should
5701 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5702 ** SQLITE_MUTEX_RECURSIVE.
5704 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5705 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5706 ** returns a different mutex on every call. ^But for the static
5707 ** mutex types, the same mutex is returned on every call that has
5708 ** the same type number.
5710 ** ^The sqlite3_mutex_free() routine deallocates a previously
5711 ** allocated dynamic mutex. ^SQLite is careful to deallocate every
5712 ** dynamic mutex that it allocates. The dynamic mutexes must not be in
5713 ** use when they are deallocated. Attempting to deallocate a static
5714 ** mutex results in undefined behavior. ^SQLite never deallocates
5715 ** a static mutex.
5717 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5718 ** to enter a mutex. ^If another thread is already within the mutex,
5719 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5720 ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5721 ** upon successful entry. ^(Mutexes created using
5722 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5723 ** In such cases the,
5724 ** mutex must be exited an equal number of times before another thread
5725 ** can enter.)^ ^(If the same thread tries to enter any other
5726 ** kind of mutex more than once, the behavior is undefined.
5727 ** SQLite will never exhibit
5728 ** such behavior in its own use of mutexes.)^
5730 ** ^(Some systems (for example, Windows 95) do not support the operation
5731 ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
5732 ** will always return SQLITE_BUSY. The SQLite core only ever uses
5733 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5735 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5736 ** previously entered by the same thread. ^(The behavior
5737 ** is undefined if the mutex is not currently entered by the
5738 ** calling thread or is not currently allocated. SQLite will
5739 ** never do either.)^
5741 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5742 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5743 ** behave as no-ops.
5745 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5747 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5748 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5749 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5750 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5751 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5754 ** CAPI3REF: Mutex Methods Object
5756 ** An instance of this structure defines the low-level routines
5757 ** used to allocate and use mutexes.
5759 ** Usually, the default mutex implementations provided by SQLite are
5760 ** sufficient, however the user has the option of substituting a custom
5761 ** implementation for specialized deployments or systems for which SQLite
5762 ** does not provide a suitable implementation. In this case, the user
5763 ** creates and populates an instance of this structure to pass
5764 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5765 ** Additionally, an instance of this structure can be used as an
5766 ** output variable when querying the system for the current mutex
5767 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5769 ** ^The xMutexInit method defined by this structure is invoked as
5770 ** part of system initialization by the sqlite3_initialize() function.
5771 ** ^The xMutexInit routine is called by SQLite exactly once for each
5772 ** effective call to [sqlite3_initialize()].
5774 ** ^The xMutexEnd method defined by this structure is invoked as
5775 ** part of system shutdown by the sqlite3_shutdown() function. The
5776 ** implementation of this method is expected to release all outstanding
5777 ** resources obtained by the mutex methods implementation, especially
5778 ** those obtained by the xMutexInit method. ^The xMutexEnd()
5779 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5781 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5782 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5783 ** xMutexNotheld) implement the following interfaces (respectively):
5785 ** <ul>
5786 ** <li> [sqlite3_mutex_alloc()] </li>
5787 ** <li> [sqlite3_mutex_free()] </li>
5788 ** <li> [sqlite3_mutex_enter()] </li>
5789 ** <li> [sqlite3_mutex_try()] </li>
5790 ** <li> [sqlite3_mutex_leave()] </li>
5791 ** <li> [sqlite3_mutex_held()] </li>
5792 ** <li> [sqlite3_mutex_notheld()] </li>
5793 ** </ul>)^
5795 ** The only difference is that the public sqlite3_XXX functions enumerated
5796 ** above silently ignore any invocations that pass a NULL pointer instead
5797 ** of a valid mutex handle. The implementations of the methods defined
5798 ** by this structure are not required to handle this case, the results
5799 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5800 ** (i.e. it is acceptable to provide an implementation that segfaults if
5801 ** it is passed a NULL pointer).
5803 ** The xMutexInit() method must be threadsafe. ^It must be harmless to
5804 ** invoke xMutexInit() multiple times within the same process and without
5805 ** intervening calls to xMutexEnd(). Second and subsequent calls to
5806 ** xMutexInit() must be no-ops.
5808 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5809 ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
5810 ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
5811 ** memory allocation for a fast or recursive mutex.
5813 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5814 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5815 ** If xMutexInit fails in any way, it is expected to clean up after itself
5816 ** prior to returning.
5818 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5819 struct sqlite3_mutex_methods {
5820 int (*xMutexInit)(void);
5821 int (*xMutexEnd)(void);
5822 sqlite3_mutex *(*xMutexAlloc)(int);
5823 void (*xMutexFree)(sqlite3_mutex *);
5824 void (*xMutexEnter)(sqlite3_mutex *);
5825 int (*xMutexTry)(sqlite3_mutex *);
5826 void (*xMutexLeave)(sqlite3_mutex *);
5827 int (*xMutexHeld)(sqlite3_mutex *);
5828 int (*xMutexNotheld)(sqlite3_mutex *);
5832 ** CAPI3REF: Mutex Verification Routines
5834 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5835 ** are intended for use inside assert() statements. ^The SQLite core
5836 ** never uses these routines except inside an assert() and applications
5837 ** are advised to follow the lead of the core. ^The SQLite core only
5838 ** provides implementations for these routines when it is compiled
5839 ** with the SQLITE_DEBUG flag. ^External mutex implementations
5840 ** are only required to provide these routines if SQLITE_DEBUG is
5841 ** defined and if NDEBUG is not defined.
5843 ** ^These routines should return true if the mutex in their argument
5844 ** is held or not held, respectively, by the calling thread.
5846 ** ^The implementation is not required to provided versions of these
5847 ** routines that actually work. If the implementation does not provide working
5848 ** versions of these routines, it should at least provide stubs that always
5849 ** return true so that one does not get spurious assertion failures.
5851 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5852 ** the routine should return 1. This seems counter-intuitive since
5853 ** clearly the mutex cannot be held if it does not exist. But the
5854 ** the reason the mutex does not exist is because the build is not
5855 ** using mutexes. And we do not want the assert() containing the
5856 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5857 ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
5858 ** interface should also return 1 when given a NULL pointer.
5860 #ifndef NDEBUG
5861 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5862 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5863 #endif
5866 ** CAPI3REF: Mutex Types
5868 ** The [sqlite3_mutex_alloc()] interface takes a single argument
5869 ** which is one of these integer constants.
5871 ** The set of static mutexes may change from one SQLite release to the
5872 ** next. Applications that override the built-in mutex logic must be
5873 ** prepared to accommodate additional static mutexes.
5875 #define SQLITE_MUTEX_FAST 0
5876 #define SQLITE_MUTEX_RECURSIVE 1
5877 #define SQLITE_MUTEX_STATIC_MASTER 2
5878 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
5879 #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
5880 #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
5881 #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
5882 #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
5883 #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
5884 #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
5887 ** CAPI3REF: Retrieve the mutex for a database connection
5889 ** ^This interface returns a pointer the [sqlite3_mutex] object that
5890 ** serializes access to the [database connection] given in the argument
5891 ** when the [threading mode] is Serialized.
5892 ** ^If the [threading mode] is Single-thread or Multi-thread then this
5893 ** routine returns a NULL pointer.
5895 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5898 ** CAPI3REF: Low-Level Control Of Database Files
5900 ** ^The [sqlite3_file_control()] interface makes a direct call to the
5901 ** xFileControl method for the [sqlite3_io_methods] object associated
5902 ** with a particular database identified by the second argument. ^The
5903 ** name of the database is "main" for the main database or "temp" for the
5904 ** TEMP database, or the name that appears after the AS keyword for
5905 ** databases that are added using the [ATTACH] SQL command.
5906 ** ^A NULL pointer can be used in place of "main" to refer to the
5907 ** main database file.
5908 ** ^The third and fourth parameters to this routine
5909 ** are passed directly through to the second and third parameters of
5910 ** the xFileControl method. ^The return value of the xFileControl
5911 ** method becomes the return value of this routine.
5913 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
5914 ** a pointer to the underlying [sqlite3_file] object to be written into
5915 ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
5916 ** case is a short-circuit path which does not actually invoke the
5917 ** underlying sqlite3_io_methods.xFileControl method.
5919 ** ^If the second parameter (zDbName) does not match the name of any
5920 ** open database file, then SQLITE_ERROR is returned. ^This error
5921 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5922 ** or [sqlite3_errmsg()]. The underlying xFileControl method might
5923 ** also return SQLITE_ERROR. There is no way to distinguish between
5924 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5925 ** xFileControl method.
5927 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5929 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5932 ** CAPI3REF: Testing Interface
5934 ** ^The sqlite3_test_control() interface is used to read out internal
5935 ** state of SQLite and to inject faults into SQLite for testing
5936 ** purposes. ^The first parameter is an operation code that determines
5937 ** the number, meaning, and operation of all subsequent parameters.
5939 ** This interface is not for use by applications. It exists solely
5940 ** for verifying the correct operation of the SQLite library. Depending
5941 ** on how the SQLite library is compiled, this interface might not exist.
5943 ** The details of the operation codes, their meanings, the parameters
5944 ** they take, and what they do are all subject to change without notice.
5945 ** Unlike most of the SQLite API, this function is not guaranteed to
5946 ** operate consistently from one release to the next.
5948 SQLITE_API int sqlite3_test_control(int op, ...);
5951 ** CAPI3REF: Testing Interface Operation Codes
5953 ** These constants are the valid operation code parameters used
5954 ** as the first argument to [sqlite3_test_control()].
5956 ** These parameters and their meanings are subject to change
5957 ** without notice. These values are for testing purposes only.
5958 ** Applications should not use any of these parameters or the
5959 ** [sqlite3_test_control()] interface.
5961 #define SQLITE_TESTCTRL_FIRST 5
5962 #define SQLITE_TESTCTRL_PRNG_SAVE 5
5963 #define SQLITE_TESTCTRL_PRNG_RESTORE 6
5964 #define SQLITE_TESTCTRL_PRNG_RESET 7
5965 #define SQLITE_TESTCTRL_BITVEC_TEST 8
5966 #define SQLITE_TESTCTRL_FAULT_INSTALL 9
5967 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
5968 #define SQLITE_TESTCTRL_PENDING_BYTE 11
5969 #define SQLITE_TESTCTRL_ASSERT 12
5970 #define SQLITE_TESTCTRL_ALWAYS 13
5971 #define SQLITE_TESTCTRL_RESERVE 14
5972 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
5973 #define SQLITE_TESTCTRL_ISKEYWORD 16
5974 #define SQLITE_TESTCTRL_PGHDRSZ 17
5975 #define SQLITE_TESTCTRL_SCRATCHMALLOC 18
5976 #define SQLITE_TESTCTRL_LAST 18
5979 ** CAPI3REF: SQLite Runtime Status
5981 ** ^This interface is used to retrieve runtime status information
5982 ** about the performance of SQLite, and optionally to reset various
5983 ** highwater marks. ^The first argument is an integer code for
5984 ** the specific parameter to measure. ^(Recognized integer codes
5985 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5986 ** ^The current value of the parameter is returned into *pCurrent.
5987 ** ^The highest recorded value is returned in *pHighwater. ^If the
5988 ** resetFlag is true, then the highest record value is reset after
5989 ** *pHighwater is written. ^(Some parameters do not record the highest
5990 ** value. For those parameters
5991 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5992 ** ^(Other parameters record only the highwater mark and not the current
5993 ** value. For these latter parameters nothing is written into *pCurrent.)^
5995 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
5996 ** non-zero [error code] on failure.
5998 ** This routine is threadsafe but is not atomic. This routine can be
5999 ** called while other threads are running the same or different SQLite
6000 ** interfaces. However the values returned in *pCurrent and
6001 ** *pHighwater reflect the status of SQLite at different points in time
6002 ** and it is possible that another thread might change the parameter
6003 ** in between the times when *pCurrent and *pHighwater are written.
6005 ** See also: [sqlite3_db_status()]
6007 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6011 ** CAPI3REF: Status Parameters
6013 ** These integer constants designate various run-time status parameters
6014 ** that can be returned by [sqlite3_status()].
6016 ** <dl>
6017 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6018 ** <dd>This parameter is the current amount of memory checked out
6019 ** using [sqlite3_malloc()], either directly or indirectly. The
6020 ** figure includes calls made to [sqlite3_malloc()] by the application
6021 ** and internal memory usage by the SQLite library. Scratch memory
6022 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6023 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6024 ** this parameter. The amount returned is the sum of the allocation
6025 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6027 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6028 ** <dd>This parameter records the largest memory allocation request
6029 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6030 ** internal equivalents). Only the value returned in the
6031 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6032 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6034 ** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6035 ** <dd>This parameter records the number of separate memory allocations
6036 ** currently checked out.</dd>)^
6038 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6039 ** <dd>This parameter returns the number of pages used out of the
6040 ** [pagecache memory allocator] that was configured using
6041 ** [SQLITE_CONFIG_PAGECACHE]. The
6042 ** value returned is in pages, not in bytes.</dd>)^
6044 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6045 ** <dd>This parameter returns the number of bytes of page cache
6046 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6047 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
6048 ** returned value includes allocations that overflowed because they
6049 ** where too large (they were larger than the "sz" parameter to
6050 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6051 ** no space was left in the page cache.</dd>)^
6053 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6054 ** <dd>This parameter records the largest memory allocation request
6055 ** handed to [pagecache memory allocator]. Only the value returned in the
6056 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6057 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6059 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6060 ** <dd>This parameter returns the number of allocations used out of the
6061 ** [scratch memory allocator] configured using
6062 ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
6063 ** in bytes. Since a single thread may only have one scratch allocation
6064 ** outstanding at time, this parameter also reports the number of threads
6065 ** using scratch memory at the same time.</dd>)^
6067 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6068 ** <dd>This parameter returns the number of bytes of scratch memory
6069 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6070 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
6071 ** returned include overflows because the requested allocation was too
6072 ** larger (that is, because the requested allocation was larger than the
6073 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6074 ** slots were available.
6075 ** </dd>)^
6077 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6078 ** <dd>This parameter records the largest memory allocation request
6079 ** handed to [scratch memory allocator]. Only the value returned in the
6080 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6081 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6083 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6084 ** <dd>This parameter records the deepest parser stack. It is only
6085 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6086 ** </dl>
6088 ** New status parameters may be added from time to time.
6090 #define SQLITE_STATUS_MEMORY_USED 0
6091 #define SQLITE_STATUS_PAGECACHE_USED 1
6092 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
6093 #define SQLITE_STATUS_SCRATCH_USED 3
6094 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
6095 #define SQLITE_STATUS_MALLOC_SIZE 5
6096 #define SQLITE_STATUS_PARSER_STACK 6
6097 #define SQLITE_STATUS_PAGECACHE_SIZE 7
6098 #define SQLITE_STATUS_SCRATCH_SIZE 8
6099 #define SQLITE_STATUS_MALLOC_COUNT 9
6102 ** CAPI3REF: Database Connection Status
6104 ** ^This interface is used to retrieve runtime status information
6105 ** about a single [database connection]. ^The first argument is the
6106 ** database connection object to be interrogated. ^The second argument
6107 ** is an integer constant, taken from the set of
6108 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
6109 ** determines the parameter to interrogate. The set of
6110 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
6111 ** to grow in future releases of SQLite.
6113 ** ^The current value of the requested parameter is written into *pCur
6114 ** and the highest instantaneous value is written into *pHiwtr. ^If
6115 ** the resetFlg is true, then the highest instantaneous value is
6116 ** reset back down to the current value.
6118 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6119 ** non-zero [error code] on failure.
6121 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6123 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6126 ** CAPI3REF: Status Parameters for database connections
6128 ** These constants are the available integer "verbs" that can be passed as
6129 ** the second argument to the [sqlite3_db_status()] interface.
6131 ** New verbs may be added in future releases of SQLite. Existing verbs
6132 ** might be discontinued. Applications should check the return code from
6133 ** [sqlite3_db_status()] to make sure that the call worked.
6134 ** The [sqlite3_db_status()] interface will return a non-zero error code
6135 ** if a discontinued or unsupported verb is invoked.
6137 ** <dl>
6138 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6139 ** <dd>This parameter returns the number of lookaside memory slots currently
6140 ** checked out.</dd>)^
6142 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6143 ** <dd>This parameter returns the number malloc attempts that were
6144 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6145 ** the current value is always zero.)^
6147 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6148 ** <dd>This parameter returns the number malloc attempts that might have
6149 ** been satisfied using lookaside memory but failed due to the amount of
6150 ** memory requested being larger than the lookaside slot size.
6151 ** Only the high-water value is meaningful;
6152 ** the current value is always zero.)^
6154 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6155 ** <dd>This parameter returns the number malloc attempts that might have
6156 ** been satisfied using lookaside memory but failed due to all lookaside
6157 ** memory already being in use.
6158 ** Only the high-water value is meaningful;
6159 ** the current value is always zero.)^
6161 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6162 ** <dd>This parameter returns the approximate number of of bytes of heap
6163 ** memory used by all pager caches associated with the database connection.)^
6164 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6166 ** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6167 ** <dd>This parameter returns the approximate number of of bytes of heap
6168 ** memory used to store the schema for all databases associated
6169 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6170 ** ^The full amount of memory used by the schemas is reported, even if the
6171 ** schema memory is shared with other database connections due to
6172 ** [shared cache mode] being enabled.
6173 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6175 ** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6176 ** <dd>This parameter returns the approximate number of of bytes of heap
6177 ** and lookaside memory used by all prepared statements associated with
6178 ** the database connection.)^
6179 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6180 ** </dd>
6181 ** </dl>
6183 #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
6184 #define SQLITE_DBSTATUS_CACHE_USED 1
6185 #define SQLITE_DBSTATUS_SCHEMA_USED 2
6186 #define SQLITE_DBSTATUS_STMT_USED 3
6187 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
6188 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
6189 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
6190 #define SQLITE_DBSTATUS_MAX 6 /* Largest defined DBSTATUS */
6194 ** CAPI3REF: Prepared Statement Status
6196 ** ^(Each prepared statement maintains various
6197 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
6198 ** of times it has performed specific operations.)^ These counters can
6199 ** be used to monitor the performance characteristics of the prepared
6200 ** statements. For example, if the number of table steps greatly exceeds
6201 ** the number of table searches or result rows, that would tend to indicate
6202 ** that the prepared statement is using a full table scan rather than
6203 ** an index.
6205 ** ^(This interface is used to retrieve and reset counter values from
6206 ** a [prepared statement]. The first argument is the prepared statement
6207 ** object to be interrogated. The second argument
6208 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
6209 ** to be interrogated.)^
6210 ** ^The current value of the requested counter is returned.
6211 ** ^If the resetFlg is true, then the counter is reset to zero after this
6212 ** interface call returns.
6214 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6216 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6219 ** CAPI3REF: Status Parameters for prepared statements
6221 ** These preprocessor macros define integer codes that name counter
6222 ** values associated with the [sqlite3_stmt_status()] interface.
6223 ** The meanings of the various counters are as follows:
6225 ** <dl>
6226 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6227 ** <dd>^This is the number of times that SQLite has stepped forward in
6228 ** a table as part of a full table scan. Large numbers for this counter
6229 ** may indicate opportunities for performance improvement through
6230 ** careful use of indices.</dd>
6232 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
6233 ** <dd>^This is the number of sort operations that have occurred.
6234 ** A non-zero value in this counter may indicate an opportunity to
6235 ** improvement performance through careful use of indices.</dd>
6237 ** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6238 ** <dd>^This is the number of rows inserted into transient indices that
6239 ** were created automatically in order to help joins run faster.
6240 ** A non-zero value in this counter may indicate an opportunity to
6241 ** improvement performance by adding permanent indices that do not
6242 ** need to be reinitialized each time the statement is run.</dd>
6244 ** </dl>
6246 #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
6247 #define SQLITE_STMTSTATUS_SORT 2
6248 #define SQLITE_STMTSTATUS_AUTOINDEX 3
6251 ** CAPI3REF: Custom Page Cache Object
6253 ** The sqlite3_pcache type is opaque. It is implemented by
6254 ** the pluggable module. The SQLite core has no knowledge of
6255 ** its size or internal structure and never deals with the
6256 ** sqlite3_pcache object except by holding and passing pointers
6257 ** to the object.
6259 ** See [sqlite3_pcache_methods] for additional information.
6261 typedef struct sqlite3_pcache sqlite3_pcache;
6264 ** CAPI3REF: Application Defined Page Cache.
6265 ** KEYWORDS: {page cache}
6267 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
6268 ** register an alternative page cache implementation by passing in an
6269 ** instance of the sqlite3_pcache_methods structure.)^
6270 ** In many applications, most of the heap memory allocated by
6271 ** SQLite is used for the page cache.
6272 ** By implementing a
6273 ** custom page cache using this API, an application can better control
6274 ** the amount of memory consumed by SQLite, the way in which
6275 ** that memory is allocated and released, and the policies used to
6276 ** determine exactly which parts of a database file are cached and for
6277 ** how long.
6279 ** The alternative page cache mechanism is an
6280 ** extreme measure that is only needed by the most demanding applications.
6281 ** The built-in page cache is recommended for most uses.
6283 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
6284 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
6285 ** the application may discard the parameter after the call to
6286 ** [sqlite3_config()] returns.)^
6288 ** ^(The xInit() method is called once for each effective
6289 ** call to [sqlite3_initialize()])^
6290 ** (usually only once during the lifetime of the process). ^(The xInit()
6291 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
6292 ** The intent of the xInit() method is to set up global data structures
6293 ** required by the custom page cache implementation.
6294 ** ^(If the xInit() method is NULL, then the
6295 ** built-in default page cache is used instead of the application defined
6296 ** page cache.)^
6298 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6299 ** It can be used to clean up
6300 ** any outstanding resources before process shutdown, if required.
6301 ** ^The xShutdown() method may be NULL.
6303 ** ^SQLite automatically serializes calls to the xInit method,
6304 ** so the xInit method need not be threadsafe. ^The
6305 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6306 ** not need to be threadsafe either. All other methods must be threadsafe
6307 ** in multithreaded applications.
6309 ** ^SQLite will never invoke xInit() more than once without an intervening
6310 ** call to xShutdown().
6312 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6313 ** SQLite will typically create one cache instance for each open database file,
6314 ** though this is not guaranteed. ^The
6315 ** first parameter, szPage, is the size in bytes of the pages that must
6316 ** be allocated by the cache. ^szPage will not be a power of two. ^szPage
6317 ** will the page size of the database file that is to be cached plus an
6318 ** increment (here called "R") of less than 250. SQLite will use the
6319 ** extra R bytes on each page to store metadata about the underlying
6320 ** database page on disk. The value of R depends
6321 ** on the SQLite version, the target platform, and how SQLite was compiled.
6322 ** ^(R is constant for a particular build of SQLite. Except, there are two
6323 ** distinct values of R when SQLite is compiled with the proprietary
6324 ** ZIPVFS extension.)^ ^The second argument to
6325 ** xCreate(), bPurgeable, is true if the cache being created will
6326 ** be used to cache database pages of a file stored on disk, or
6327 ** false if it is used for an in-memory database. The cache implementation
6328 ** does not have to do anything special based with the value of bPurgeable;
6329 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
6330 ** never invoke xUnpin() except to deliberately delete a page.
6331 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6332 ** false will always have the "discard" flag set to true.
6333 ** ^Hence, a cache created with bPurgeable false will
6334 ** never contain any unpinned pages.
6336 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6337 ** suggested maximum cache-size (number of pages stored by) the cache
6338 ** instance passed as the first argument. This is the value configured using
6339 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
6340 ** parameter, the implementation is not required to do anything with this
6341 ** value; it is advisory only.
6343 ** The xPagecount() method must return the number of pages currently
6344 ** stored in the cache, both pinned and unpinned.
6346 ** The xFetch() method locates a page in the cache and returns a pointer to
6347 ** the page, or a NULL pointer.
6348 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6349 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6350 ** mimimum key value is 1. After it has been retrieved using xFetch, the page
6351 ** is considered to be "pinned".
6353 ** If the requested page is already in the page cache, then the page cache
6354 ** implementation must return a pointer to the page buffer with its content
6355 ** intact. If the requested page is not already in the cache, then the
6356 ** cache implementation should use the value of the createFlag
6357 ** parameter to help it determined what action to take:
6359 ** <table border=1 width=85% align=center>
6360 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6361 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
6362 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6363 ** Otherwise return NULL.
6364 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
6365 ** NULL if allocating a new page is effectively impossible.
6366 ** </table>
6368 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
6369 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6370 ** failed.)^ In between the to xFetch() calls, SQLite may
6371 ** attempt to unpin one or more cache pages by spilling the content of
6372 ** pinned pages to disk and synching the operating system disk cache.
6374 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6375 ** as its second argument. If the third parameter, discard, is non-zero,
6376 ** then the page must be evicted from the cache.
6377 ** ^If the discard parameter is
6378 ** zero, then the page may be discarded or retained at the discretion of
6379 ** page cache implementation. ^The page cache implementation
6380 ** may choose to evict unpinned pages at any time.
6382 ** The cache must not perform any reference counting. A single
6383 ** call to xUnpin() unpins the page regardless of the number of prior calls
6384 ** to xFetch().
6386 ** The xRekey() method is used to change the key value associated with the
6387 ** page passed as the second argument. If the cache
6388 ** previously contains an entry associated with newKey, it must be
6389 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6390 ** to be pinned.
6392 ** When SQLite calls the xTruncate() method, the cache must discard all
6393 ** existing cache entries with page numbers (keys) greater than or equal
6394 ** to the value of the iLimit parameter passed to xTruncate(). If any
6395 ** of these pages are pinned, they are implicitly unpinned, meaning that
6396 ** they can be safely discarded.
6398 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6399 ** All resources associated with the specified cache should be freed. ^After
6400 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6401 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
6402 ** functions.
6404 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6405 struct sqlite3_pcache_methods {
6406 void *pArg;
6407 int (*xInit)(void*);
6408 void (*xShutdown)(void*);
6409 sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6410 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6411 int (*xPagecount)(sqlite3_pcache*);
6412 void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6413 void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6414 void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6415 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6416 void (*xDestroy)(sqlite3_pcache*);
6420 ** CAPI3REF: Online Backup Object
6422 ** The sqlite3_backup object records state information about an ongoing
6423 ** online backup operation. ^The sqlite3_backup object is created by
6424 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6425 ** [sqlite3_backup_finish()].
6427 ** See Also: [Using the SQLite Online Backup API]
6429 typedef struct sqlite3_backup sqlite3_backup;
6432 ** CAPI3REF: Online Backup API.
6434 ** The backup API copies the content of one database into another.
6435 ** It is useful either for creating backups of databases or
6436 ** for copying in-memory databases to or from persistent files.
6438 ** See Also: [Using the SQLite Online Backup API]
6440 ** ^SQLite holds a write transaction open on the destination database file
6441 ** for the duration of the backup operation.
6442 ** ^The source database is read-locked only while it is being read;
6443 ** it is not locked continuously for the entire backup operation.
6444 ** ^Thus, the backup may be performed on a live source database without
6445 ** preventing other database connections from
6446 ** reading or writing to the source database while the backup is underway.
6448 ** ^(To perform a backup operation:
6449 ** <ol>
6450 ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
6451 ** backup,
6452 ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6453 ** the data between the two databases, and finally
6454 ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
6455 ** associated with the backup operation.
6456 ** </ol>)^
6457 ** There should be exactly one call to sqlite3_backup_finish() for each
6458 ** successful call to sqlite3_backup_init().
6460 ** <b>sqlite3_backup_init()</b>
6462 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6463 ** [database connection] associated with the destination database
6464 ** and the database name, respectively.
6465 ** ^The database name is "main" for the main database, "temp" for the
6466 ** temporary database, or the name specified after the AS keyword in
6467 ** an [ATTACH] statement for an attached database.
6468 ** ^The S and M arguments passed to
6469 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6470 ** and database name of the source database, respectively.
6471 ** ^The source and destination [database connections] (parameters S and D)
6472 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6473 ** an error.
6475 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6476 ** returned and an error code and error message are stored in the
6477 ** destination [database connection] D.
6478 ** ^The error code and message for the failed call to sqlite3_backup_init()
6479 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6480 ** [sqlite3_errmsg16()] functions.
6481 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6482 ** [sqlite3_backup] object.
6483 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6484 ** sqlite3_backup_finish() functions to perform the specified backup
6485 ** operation.
6487 ** <b>sqlite3_backup_step()</b>
6489 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6490 ** the source and destination databases specified by [sqlite3_backup] object B.
6491 ** ^If N is negative, all remaining source pages are copied.
6492 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6493 ** are still more pages to be copied, then the function returns [SQLITE_OK].
6494 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6495 ** from source to destination, then it returns [SQLITE_DONE].
6496 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6497 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6498 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6499 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6500 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6502 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6503 ** <ol>
6504 ** <li> the destination database was opened read-only, or
6505 ** <li> the destination database is using write-ahead-log journaling
6506 ** and the destination and source page sizes differ, or
6507 ** <li> the destination database is an in-memory database and the
6508 ** destination and source page sizes differ.
6509 ** </ol>)^
6511 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6512 ** the [sqlite3_busy_handler | busy-handler function]
6513 ** is invoked (if one is specified). ^If the
6514 ** busy-handler returns non-zero before the lock is available, then
6515 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6516 ** sqlite3_backup_step() can be retried later. ^If the source
6517 ** [database connection]
6518 ** is being used to write to the source database when sqlite3_backup_step()
6519 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6520 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6521 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6522 ** [SQLITE_READONLY] is returned, then
6523 ** there is no point in retrying the call to sqlite3_backup_step(). These
6524 ** errors are considered fatal.)^ The application must accept
6525 ** that the backup operation has failed and pass the backup operation handle
6526 ** to the sqlite3_backup_finish() to release associated resources.
6528 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6529 ** on the destination file. ^The exclusive lock is not released until either
6530 ** sqlite3_backup_finish() is called or the backup operation is complete
6531 ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
6532 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6533 ** lasts for the duration of the sqlite3_backup_step() call.
6534 ** ^Because the source database is not locked between calls to
6535 ** sqlite3_backup_step(), the source database may be modified mid-way
6536 ** through the backup process. ^If the source database is modified by an
6537 ** external process or via a database connection other than the one being
6538 ** used by the backup operation, then the backup will be automatically
6539 ** restarted by the next call to sqlite3_backup_step(). ^If the source
6540 ** database is modified by the using the same database connection as is used
6541 ** by the backup operation, then the backup database is automatically
6542 ** updated at the same time.
6544 ** <b>sqlite3_backup_finish()</b>
6546 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
6547 ** application wishes to abandon the backup operation, the application
6548 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6549 ** ^The sqlite3_backup_finish() interfaces releases all
6550 ** resources associated with the [sqlite3_backup] object.
6551 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6552 ** active write-transaction on the destination database is rolled back.
6553 ** The [sqlite3_backup] object is invalid
6554 ** and may not be used following a call to sqlite3_backup_finish().
6556 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6557 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6558 ** sqlite3_backup_step() completed.
6559 ** ^If an out-of-memory condition or IO error occurred during any prior
6560 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6561 ** sqlite3_backup_finish() returns the corresponding [error code].
6563 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6564 ** is not a permanent error and does not affect the return value of
6565 ** sqlite3_backup_finish().
6567 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6569 ** ^Each call to sqlite3_backup_step() sets two values inside
6570 ** the [sqlite3_backup] object: the number of pages still to be backed
6571 ** up and the total number of pages in the source database file.
6572 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6573 ** retrieve these two values, respectively.
6575 ** ^The values returned by these functions are only updated by
6576 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6577 ** operation, then the values are not updated to account for any extra
6578 ** pages that need to be updated or the size of the source database file
6579 ** changing.
6581 ** <b>Concurrent Usage of Database Handles</b>
6583 ** ^The source [database connection] may be used by the application for other
6584 ** purposes while a backup operation is underway or being initialized.
6585 ** ^If SQLite is compiled and configured to support threadsafe database
6586 ** connections, then the source database connection may be used concurrently
6587 ** from within other threads.
6589 ** However, the application must guarantee that the destination
6590 ** [database connection] is not passed to any other API (by any thread) after
6591 ** sqlite3_backup_init() is called and before the corresponding call to
6592 ** sqlite3_backup_finish(). SQLite does not currently check to see
6593 ** if the application incorrectly accesses the destination [database connection]
6594 ** and so no error code is reported, but the operations may malfunction
6595 ** nevertheless. Use of the destination database connection while a
6596 ** backup is in progress might also also cause a mutex deadlock.
6598 ** If running in [shared cache mode], the application must
6599 ** guarantee that the shared cache used by the destination database
6600 ** is not accessed while the backup is running. In practice this means
6601 ** that the application must guarantee that the disk file being
6602 ** backed up to is not accessed by any connection within the process,
6603 ** not just the specific connection that was passed to sqlite3_backup_init().
6605 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
6606 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6607 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6608 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6609 ** same time as another thread is invoking sqlite3_backup_step() it is
6610 ** possible that they return invalid values.
6612 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6613 sqlite3 *pDest, /* Destination database handle */
6614 const char *zDestName, /* Destination database name */
6615 sqlite3 *pSource, /* Source database handle */
6616 const char *zSourceName /* Source database name */
6618 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6619 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6620 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6621 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6624 ** CAPI3REF: Unlock Notification
6626 ** ^When running in shared-cache mode, a database operation may fail with
6627 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6628 ** individual tables within the shared-cache cannot be obtained. See
6629 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
6630 ** ^This API may be used to register a callback that SQLite will invoke
6631 ** when the connection currently holding the required lock relinquishes it.
6632 ** ^This API is only available if the library was compiled with the
6633 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6635 ** See Also: [Using the SQLite Unlock Notification Feature].
6637 ** ^Shared-cache locks are released when a database connection concludes
6638 ** its current transaction, either by committing it or rolling it back.
6640 ** ^When a connection (known as the blocked connection) fails to obtain a
6641 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6642 ** identity of the database connection (the blocking connection) that
6643 ** has locked the required resource is stored internally. ^After an
6644 ** application receives an SQLITE_LOCKED error, it may call the
6645 ** sqlite3_unlock_notify() method with the blocked connection handle as
6646 ** the first argument to register for a callback that will be invoked
6647 ** when the blocking connections current transaction is concluded. ^The
6648 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6649 ** call that concludes the blocking connections transaction.
6651 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6652 ** there is a chance that the blocking connection will have already
6653 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6654 ** If this happens, then the specified callback is invoked immediately,
6655 ** from within the call to sqlite3_unlock_notify().)^
6657 ** ^If the blocked connection is attempting to obtain a write-lock on a
6658 ** shared-cache table, and more than one other connection currently holds
6659 ** a read-lock on the same table, then SQLite arbitrarily selects one of
6660 ** the other connections to use as the blocking connection.
6662 ** ^(There may be at most one unlock-notify callback registered by a
6663 ** blocked connection. If sqlite3_unlock_notify() is called when the
6664 ** blocked connection already has a registered unlock-notify callback,
6665 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6666 ** called with a NULL pointer as its second argument, then any existing
6667 ** unlock-notify callback is canceled. ^The blocked connections
6668 ** unlock-notify callback may also be canceled by closing the blocked
6669 ** connection using [sqlite3_close()].
6671 ** The unlock-notify callback is not reentrant. If an application invokes
6672 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6673 ** crash or deadlock may be the result.
6675 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6676 ** returns SQLITE_OK.
6678 ** <b>Callback Invocation Details</b>
6680 ** When an unlock-notify callback is registered, the application provides a
6681 ** single void* pointer that is passed to the callback when it is invoked.
6682 ** However, the signature of the callback function allows SQLite to pass
6683 ** it an array of void* context pointers. The first argument passed to
6684 ** an unlock-notify callback is a pointer to an array of void* pointers,
6685 ** and the second is the number of entries in the array.
6687 ** When a blocking connections transaction is concluded, there may be
6688 ** more than one blocked connection that has registered for an unlock-notify
6689 ** callback. ^If two or more such blocked connections have specified the
6690 ** same callback function, then instead of invoking the callback function
6691 ** multiple times, it is invoked once with the set of void* context pointers
6692 ** specified by the blocked connections bundled together into an array.
6693 ** This gives the application an opportunity to prioritize any actions
6694 ** related to the set of unblocked database connections.
6696 ** <b>Deadlock Detection</b>
6698 ** Assuming that after registering for an unlock-notify callback a
6699 ** database waits for the callback to be issued before taking any further
6700 ** action (a reasonable assumption), then using this API may cause the
6701 ** application to deadlock. For example, if connection X is waiting for
6702 ** connection Y's transaction to be concluded, and similarly connection
6703 ** Y is waiting on connection X's transaction, then neither connection
6704 ** will proceed and the system may remain deadlocked indefinitely.
6706 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6707 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6708 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6709 ** unlock-notify callback is registered. The system is said to be in
6710 ** a deadlocked state if connection A has registered for an unlock-notify
6711 ** callback on the conclusion of connection B's transaction, and connection
6712 ** B has itself registered for an unlock-notify callback when connection
6713 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6714 ** the system is also considered to be deadlocked if connection B has
6715 ** registered for an unlock-notify callback on the conclusion of connection
6716 ** C's transaction, where connection C is waiting on connection A. ^Any
6717 ** number of levels of indirection are allowed.
6719 ** <b>The "DROP TABLE" Exception</b>
6721 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
6722 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6723 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6724 ** SQLite checks if there are any currently executing SELECT statements
6725 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6726 ** returned. In this case there is no "blocking connection", so invoking
6727 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6728 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6729 ** or "DROP INDEX" query, an infinite loop might be the result.
6731 ** One way around this problem is to check the extended error code returned
6732 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6733 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6734 ** the special "DROP TABLE/INDEX" case, the extended error code is just
6735 ** SQLITE_LOCKED.)^
6737 SQLITE_API int sqlite3_unlock_notify(
6738 sqlite3 *pBlocked, /* Waiting connection */
6739 void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
6740 void *pNotifyArg /* Argument to pass to xNotify */
6745 ** CAPI3REF: String Comparison
6747 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6748 ** compare the contents of two buffers containing UTF-8 strings in a
6749 ** case-independent fashion, using the same definition of case independence
6750 ** that SQLite uses internally when comparing identifiers.
6752 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6755 ** CAPI3REF: Error Logging Interface
6757 ** ^The [sqlite3_log()] interface writes a message into the error log
6758 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6759 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6760 ** used with [sqlite3_snprintf()] to generate the final output string.
6762 ** The sqlite3_log() interface is intended for use by extensions such as
6763 ** virtual tables, collating functions, and SQL functions. While there is
6764 ** nothing to prevent an application from calling sqlite3_log(), doing so
6765 ** is considered bad form.
6767 ** The zFormat string must not be NULL.
6769 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6770 ** will not use dynamically allocated memory. The log message is stored in
6771 ** a fixed-length buffer on the stack. If the log message is longer than
6772 ** a few hundred characters, it will be truncated to the length of the
6773 ** buffer.
6775 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6778 ** CAPI3REF: Write-Ahead Log Commit Hook
6780 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
6781 ** will be invoked each time a database connection commits data to a
6782 ** [write-ahead log] (i.e. whenever a transaction is committed in
6783 ** [journal_mode | journal_mode=WAL mode]).
6785 ** ^The callback is invoked by SQLite after the commit has taken place and
6786 ** the associated write-lock on the database released, so the implementation
6787 ** may read, write or [checkpoint] the database as required.
6789 ** ^The first parameter passed to the callback function when it is invoked
6790 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
6791 ** registering the callback. ^The second is a copy of the database handle.
6792 ** ^The third parameter is the name of the database that was written to -
6793 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6794 ** is the number of pages currently in the write-ahead log file,
6795 ** including those that were just committed.
6797 ** The callback function should normally return [SQLITE_OK]. ^If an error
6798 ** code is returned, that error will propagate back up through the
6799 ** SQLite code base to cause the statement that provoked the callback
6800 ** to report an error, though the commit will have still occurred. If the
6801 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6802 ** that does not correspond to any valid SQLite error code, the results
6803 ** are undefined.
6805 ** A single database handle may have at most a single write-ahead log callback
6806 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6807 ** previously registered write-ahead log callback. ^Note that the
6808 ** [sqlite3_wal_autocheckpoint()] interface and the
6809 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6810 ** those overwrite any prior [sqlite3_wal_hook()] settings.
6812 SQLITE_API void *sqlite3_wal_hook(
6813 sqlite3*,
6814 int(*)(void *,sqlite3*,const char*,int),
6815 void*
6819 ** CAPI3REF: Configure an auto-checkpoint
6821 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6822 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
6823 ** to automatically [checkpoint]
6824 ** after committing a transaction if there are N or
6825 ** more frames in the [write-ahead log] file. ^Passing zero or
6826 ** a negative value as the nFrame parameter disables automatic
6827 ** checkpoints entirely.
6829 ** ^The callback registered by this function replaces any existing callback
6830 ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
6831 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6832 ** configured by this function.
6834 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6835 ** from SQL.
6837 ** ^Every new [database connection] defaults to having the auto-checkpoint
6838 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
6839 ** pages. The use of this interface
6840 ** is only necessary if the default setting is found to be suboptimal
6841 ** for a particular application.
6843 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6846 ** CAPI3REF: Checkpoint a database
6848 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6849 ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
6850 ** empty string, then a checkpoint is run on all databases of
6851 ** connection D. ^If the database connection D is not in
6852 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6854 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
6855 ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
6856 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
6857 ** run whenever the WAL reaches a certain size threshold.
6859 ** See also: [sqlite3_wal_checkpoint_v2()]
6861 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6864 ** CAPI3REF: Checkpoint a database
6866 ** Run a checkpoint operation on WAL database zDb attached to database
6867 ** handle db. The specific operation is determined by the value of the
6868 ** eMode parameter:
6870 ** <dl>
6871 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
6872 ** Checkpoint as many frames as possible without waiting for any database
6873 ** readers or writers to finish. Sync the db file if all frames in the log
6874 ** are checkpointed. This mode is the same as calling
6875 ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
6877 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
6878 ** This mode blocks (calls the busy-handler callback) until there is no
6879 ** database writer and all readers are reading from the most recent database
6880 ** snapshot. It then checkpoints all frames in the log file and syncs the
6881 ** database file. This call blocks database writers while it is running,
6882 ** but not database readers.
6884 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
6885 ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
6886 ** checkpointing the log file it blocks (calls the busy-handler callback)
6887 ** until all readers are reading from the database file only. This ensures
6888 ** that the next client to write to the database file restarts the log file
6889 ** from the beginning. This call blocks database writers while it is running,
6890 ** but not database readers.
6891 ** </dl>
6893 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
6894 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
6895 ** the total number of checkpointed frames (including any that were already
6896 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
6897 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
6898 ** If no values are available because of an error, they are both set to -1
6899 ** before returning to communicate this to the caller.
6901 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
6902 ** any other process is running a checkpoint operation at the same time, the
6903 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
6904 ** busy-handler configured, it will not be invoked in this case.
6906 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
6907 ** "writer" lock on the database file. If the writer lock cannot be obtained
6908 ** immediately, and a busy-handler is configured, it is invoked and the writer
6909 ** lock retried until either the busy-handler returns 0 or the lock is
6910 ** successfully obtained. The busy-handler is also invoked while waiting for
6911 ** database readers as described above. If the busy-handler returns 0 before
6912 ** the writer lock is obtained or while waiting for database readers, the
6913 ** checkpoint operation proceeds from that point in the same way as
6914 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
6915 ** without blocking any further. SQLITE_BUSY is returned in this case.
6917 ** If parameter zDb is NULL or points to a zero length string, then the
6918 ** specified operation is attempted on all WAL databases. In this case the
6919 ** values written to output parameters *pnLog and *pnCkpt are undefined. If
6920 ** an SQLITE_BUSY error is encountered when processing one or more of the
6921 ** attached WAL databases, the operation is still attempted on any remaining
6922 ** attached databases and SQLITE_BUSY is returned to the caller. If any other
6923 ** error occurs while processing an attached database, processing is abandoned
6924 ** and the error code returned to the caller immediately. If no error
6925 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
6926 ** databases, SQLITE_OK is returned.
6928 ** If database zDb is the name of an attached database that is not in WAL
6929 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
6930 ** zDb is not NULL (or a zero length string) and is not the name of any
6931 ** attached database, SQLITE_ERROR is returned to the caller.
6933 SQLITE_API int sqlite3_wal_checkpoint_v2(
6934 sqlite3 *db, /* Database handle */
6935 const char *zDb, /* Name of attached database (or NULL) */
6936 int eMode, /* SQLITE_CHECKPOINT_* value */
6937 int *pnLog, /* OUT: Size of WAL log in frames */
6938 int *pnCkpt /* OUT: Total number of frames checkpointed */
6942 ** CAPI3REF: Checkpoint operation parameters
6944 ** These constants can be used as the 3rd parameter to
6945 ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
6946 ** documentation for additional information about the meaning and use of
6947 ** each of these values.
6949 #define SQLITE_CHECKPOINT_PASSIVE 0
6950 #define SQLITE_CHECKPOINT_FULL 1
6951 #define SQLITE_CHECKPOINT_RESTART 2
6955 ** Undo the hack that converts floating point types to integer for
6956 ** builds on processors without floating point support.
6958 #ifdef SQLITE_OMIT_FLOATING_POINT
6959 # undef double
6960 #endif
6962 #if 0
6963 } /* End of the 'extern "C"' block */
6964 #endif
6965 #endif
6968 ** 2010 August 30
6970 ** The author disclaims copyright to this source code. In place of
6971 ** a legal notice, here is a blessing:
6973 ** May you do good and not evil.
6974 ** May you find forgiveness for yourself and forgive others.
6975 ** May you share freely, never taking more than you give.
6977 *************************************************************************
6980 #ifndef _SQLITE3RTREE_H_
6981 #define _SQLITE3RTREE_H_
6984 #if 0
6985 extern "C" {
6986 #endif
6988 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
6991 ** Register a geometry callback named zGeom that can be used as part of an
6992 ** R-Tree geometry query as follows:
6994 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
6996 SQLITE_API int sqlite3_rtree_geometry_callback(
6997 sqlite3 *db,
6998 const char *zGeom,
6999 int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
7000 void *pContext
7005 ** A pointer to a structure of the following type is passed as the first
7006 ** argument to callbacks registered using rtree_geometry_callback().
7008 struct sqlite3_rtree_geometry {
7009 void *pContext; /* Copy of pContext passed to s_r_g_c() */
7010 int nParam; /* Size of array aParam[] */
7011 double *aParam; /* Parameters passed to SQL geom function */
7012 void *pUser; /* Callback implementation user data */
7013 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
7017 #if 0
7018 } /* end of the 'extern "C"' block */
7019 #endif
7021 #endif /* ifndef _SQLITE3RTREE_H_ */
7024 /************** End of sqlite3.h *********************************************/
7025 /************** Continuing where we left off in sqliteInt.h ******************/
7026 /************** Include hash.h in the middle of sqliteInt.h ******************/
7027 /************** Begin file hash.h ********************************************/
7029 ** 2001 September 22
7031 ** The author disclaims copyright to this source code. In place of
7032 ** a legal notice, here is a blessing:
7034 ** May you do good and not evil.
7035 ** May you find forgiveness for yourself and forgive others.
7036 ** May you share freely, never taking more than you give.
7038 *************************************************************************
7039 ** This is the header file for the generic hash-table implemenation
7040 ** used in SQLite.
7042 #ifndef _SQLITE_HASH_H_
7043 #define _SQLITE_HASH_H_
7045 /* Forward declarations of structures. */
7046 typedef struct Hash Hash;
7047 typedef struct HashElem HashElem;
7049 /* A complete hash table is an instance of the following structure.
7050 ** The internals of this structure are intended to be opaque -- client
7051 ** code should not attempt to access or modify the fields of this structure
7052 ** directly. Change this structure only by using the routines below.
7053 ** However, some of the "procedures" and "functions" for modifying and
7054 ** accessing this structure are really macros, so we can't really make
7055 ** this structure opaque.
7057 ** All elements of the hash table are on a single doubly-linked list.
7058 ** Hash.first points to the head of this list.
7060 ** There are Hash.htsize buckets. Each bucket points to a spot in
7061 ** the global doubly-linked list. The contents of the bucket are the
7062 ** element pointed to plus the next _ht.count-1 elements in the list.
7064 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
7065 ** by a linear search of the global list. For small tables, the
7066 ** Hash.ht table is never allocated because if there are few elements
7067 ** in the table, it is faster to do a linear search than to manage
7068 ** the hash table.
7070 struct Hash {
7071 unsigned int htsize; /* Number of buckets in the hash table */
7072 unsigned int count; /* Number of entries in this table */
7073 HashElem *first; /* The first element of the array */
7074 struct _ht { /* the hash table */
7075 int count; /* Number of entries with this hash */
7076 HashElem *chain; /* Pointer to first entry with this hash */
7077 } *ht;
7080 /* Each element in the hash table is an instance of the following
7081 ** structure. All elements are stored on a single doubly-linked list.
7083 ** Again, this structure is intended to be opaque, but it can't really
7084 ** be opaque because it is used by macros.
7086 struct HashElem {
7087 HashElem *next, *prev; /* Next and previous elements in the table */
7088 void *data; /* Data associated with this element */
7089 const char *pKey; int nKey; /* Key associated with this element */
7093 ** Access routines. To delete, insert a NULL pointer.
7095 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7096 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7097 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7098 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7101 ** Macros for looping over all elements of a hash table. The idiom is
7102 ** like this:
7104 ** Hash h;
7105 ** HashElem *p;
7106 ** ...
7107 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7108 ** SomeStructure *pData = sqliteHashData(p);
7109 ** // do something with pData
7110 ** }
7112 #define sqliteHashFirst(H) ((H)->first)
7113 #define sqliteHashNext(E) ((E)->next)
7114 #define sqliteHashData(E) ((E)->data)
7115 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
7116 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
7119 ** Number of entries in a hash table
7121 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
7123 #endif /* _SQLITE_HASH_H_ */
7125 /************** End of hash.h ************************************************/
7126 /************** Continuing where we left off in sqliteInt.h ******************/
7127 /************** Include parse.h in the middle of sqliteInt.h *****************/
7128 /************** Begin file parse.h *******************************************/
7129 #define TK_SEMI 1
7130 #define TK_EXPLAIN 2
7131 #define TK_QUERY 3
7132 #define TK_PLAN 4
7133 #define TK_BEGIN 5
7134 #define TK_TRANSACTION 6
7135 #define TK_DEFERRED 7
7136 #define TK_IMMEDIATE 8
7137 #define TK_EXCLUSIVE 9
7138 #define TK_COMMIT 10
7139 #define TK_END 11
7140 #define TK_ROLLBACK 12
7141 #define TK_SAVEPOINT 13
7142 #define TK_RELEASE 14
7143 #define TK_TO 15
7144 #define TK_TABLE 16
7145 #define TK_CREATE 17
7146 #define TK_IF 18
7147 #define TK_NOT 19
7148 #define TK_EXISTS 20
7149 #define TK_TEMP 21
7150 #define TK_LP 22
7151 #define TK_RP 23
7152 #define TK_AS 24
7153 #define TK_COMMA 25
7154 #define TK_ID 26
7155 #define TK_INDEXED 27
7156 #define TK_ABORT 28
7157 #define TK_ACTION 29
7158 #define TK_AFTER 30
7159 #define TK_ANALYZE 31
7160 #define TK_ASC 32
7161 #define TK_ATTACH 33
7162 #define TK_BEFORE 34
7163 #define TK_BY 35
7164 #define TK_CASCADE 36
7165 #define TK_CAST 37
7166 #define TK_COLUMNKW 38
7167 #define TK_CONFLICT 39
7168 #define TK_DATABASE 40
7169 #define TK_DESC 41
7170 #define TK_DETACH 42
7171 #define TK_EACH 43
7172 #define TK_FAIL 44
7173 #define TK_FOR 45
7174 #define TK_IGNORE 46
7175 #define TK_INITIALLY 47
7176 #define TK_INSTEAD 48
7177 #define TK_LIKE_KW 49
7178 #define TK_MATCH 50
7179 #define TK_NO 51
7180 #define TK_KEY 52
7181 #define TK_OF 53
7182 #define TK_OFFSET 54
7183 #define TK_PRAGMA 55
7184 #define TK_RAISE 56
7185 #define TK_REPLACE 57
7186 #define TK_RESTRICT 58
7187 #define TK_ROW 59
7188 #define TK_TRIGGER 60
7189 #define TK_VACUUM 61
7190 #define TK_VIEW 62
7191 #define TK_VIRTUAL 63
7192 #define TK_REINDEX 64
7193 #define TK_RENAME 65
7194 #define TK_CTIME_KW 66
7195 #define TK_ANY 67
7196 #define TK_OR 68
7197 #define TK_AND 69
7198 #define TK_IS 70
7199 #define TK_BETWEEN 71
7200 #define TK_IN 72
7201 #define TK_ISNULL 73
7202 #define TK_NOTNULL 74
7203 #define TK_NE 75
7204 #define TK_EQ 76
7205 #define TK_GT 77
7206 #define TK_LE 78
7207 #define TK_LT 79
7208 #define TK_GE 80
7209 #define TK_ESCAPE 81
7210 #define TK_BITAND 82
7211 #define TK_BITOR 83
7212 #define TK_LSHIFT 84
7213 #define TK_RSHIFT 85
7214 #define TK_PLUS 86
7215 #define TK_MINUS 87
7216 #define TK_STAR 88
7217 #define TK_SLASH 89
7218 #define TK_REM 90
7219 #define TK_CONCAT 91
7220 #define TK_COLLATE 92
7221 #define TK_BITNOT 93
7222 #define TK_STRING 94
7223 #define TK_JOIN_KW 95
7224 #define TK_CONSTRAINT 96
7225 #define TK_DEFAULT 97
7226 #define TK_NULL 98
7227 #define TK_PRIMARY 99
7228 #define TK_UNIQUE 100
7229 #define TK_CHECK 101
7230 #define TK_REFERENCES 102
7231 #define TK_AUTOINCR 103
7232 #define TK_ON 104
7233 #define TK_INSERT 105
7234 #define TK_DELETE 106
7235 #define TK_UPDATE 107
7236 #define TK_SET 108
7237 #define TK_DEFERRABLE 109
7238 #define TK_FOREIGN 110
7239 #define TK_DROP 111
7240 #define TK_UNION 112
7241 #define TK_ALL 113
7242 #define TK_EXCEPT 114
7243 #define TK_INTERSECT 115
7244 #define TK_SELECT 116
7245 #define TK_DISTINCT 117
7246 #define TK_DOT 118
7247 #define TK_FROM 119
7248 #define TK_JOIN 120
7249 #define TK_USING 121
7250 #define TK_ORDER 122
7251 #define TK_GROUP 123
7252 #define TK_HAVING 124
7253 #define TK_LIMIT 125
7254 #define TK_WHERE 126
7255 #define TK_INTO 127
7256 #define TK_VALUES 128
7257 #define TK_INTEGER 129
7258 #define TK_FLOAT 130
7259 #define TK_BLOB 131
7260 #define TK_REGISTER 132
7261 #define TK_VARIABLE 133
7262 #define TK_CASE 134
7263 #define TK_WHEN 135
7264 #define TK_THEN 136
7265 #define TK_ELSE 137
7266 #define TK_INDEX 138
7267 #define TK_ALTER 139
7268 #define TK_ADD 140
7269 #define TK_TO_TEXT 141
7270 #define TK_TO_BLOB 142
7271 #define TK_TO_NUMERIC 143
7272 #define TK_TO_INT 144
7273 #define TK_TO_REAL 145
7274 #define TK_ISNOT 146
7275 #define TK_END_OF_FILE 147
7276 #define TK_ILLEGAL 148
7277 #define TK_SPACE 149
7278 #define TK_UNCLOSED_STRING 150
7279 #define TK_FUNCTION 151
7280 #define TK_COLUMN 152
7281 #define TK_AGG_FUNCTION 153
7282 #define TK_AGG_COLUMN 154
7283 #define TK_CONST_FUNC 155
7284 #define TK_UMINUS 156
7285 #define TK_UPLUS 157
7287 /************** End of parse.h ***********************************************/
7288 /************** Continuing where we left off in sqliteInt.h ******************/
7289 #include <stdio.h>
7290 #include <stdlib.h>
7291 #include <string.h>
7292 #include <assert.h>
7293 #include <stddef.h>
7296 ** If compiling for a processor that lacks floating point support,
7297 ** substitute integer for floating-point
7299 #ifdef SQLITE_OMIT_FLOATING_POINT
7300 # define double sqlite_int64
7301 # define float sqlite_int64
7302 # define LONGDOUBLE_TYPE sqlite_int64
7303 # ifndef SQLITE_BIG_DBL
7304 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7305 # endif
7306 # define SQLITE_OMIT_DATETIME_FUNCS 1
7307 # define SQLITE_OMIT_TRACE 1
7308 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7309 # undef SQLITE_HAVE_ISNAN
7310 #endif
7311 #ifndef SQLITE_BIG_DBL
7312 # define SQLITE_BIG_DBL (1e99)
7313 #endif
7316 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7317 ** afterward. Having this macro allows us to cause the C compiler
7318 ** to omit code used by TEMP tables without messy #ifndef statements.
7320 #ifdef SQLITE_OMIT_TEMPDB
7321 #define OMIT_TEMPDB 1
7322 #else
7323 #define OMIT_TEMPDB 0
7324 #endif
7327 ** The "file format" number is an integer that is incremented whenever
7328 ** the VDBE-level file format changes. The following macros define the
7329 ** the default file format for new databases and the maximum file format
7330 ** that the library can read.
7332 #define SQLITE_MAX_FILE_FORMAT 4
7333 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7334 # define SQLITE_DEFAULT_FILE_FORMAT 1
7335 #endif
7338 ** Determine whether triggers are recursive by default. This can be
7339 ** changed at run-time using a pragma.
7341 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7342 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7343 #endif
7346 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7347 ** on the command-line
7349 #ifndef SQLITE_TEMP_STORE
7350 # define SQLITE_TEMP_STORE 1
7351 #endif
7354 ** GCC does not define the offsetof() macro so we'll have to do it
7355 ** ourselves.
7357 #ifndef offsetof
7358 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7359 #endif
7362 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
7363 ** not, there are still machines out there that use EBCDIC.)
7365 #if 'A' == '\301'
7366 # define SQLITE_EBCDIC 1
7367 #else
7368 # define SQLITE_ASCII 1
7369 #endif
7372 ** Integers of known sizes. These typedefs might change for architectures
7373 ** where the sizes very. Preprocessor macros are available so that the
7374 ** types can be conveniently redefined at compile-type. Like this:
7376 ** cc '-DUINTPTR_TYPE=long long int' ...
7378 #ifndef UINT32_TYPE
7379 # ifdef HAVE_UINT32_T
7380 # define UINT32_TYPE uint32_t
7381 # else
7382 # define UINT32_TYPE unsigned int
7383 # endif
7384 #endif
7385 #ifndef UINT16_TYPE
7386 # ifdef HAVE_UINT16_T
7387 # define UINT16_TYPE uint16_t
7388 # else
7389 # define UINT16_TYPE unsigned short int
7390 # endif
7391 #endif
7392 #ifndef INT16_TYPE
7393 # ifdef HAVE_INT16_T
7394 # define INT16_TYPE int16_t
7395 # else
7396 # define INT16_TYPE short int
7397 # endif
7398 #endif
7399 #ifndef UINT8_TYPE
7400 # ifdef HAVE_UINT8_T
7401 # define UINT8_TYPE uint8_t
7402 # else
7403 # define UINT8_TYPE unsigned char
7404 # endif
7405 #endif
7406 #ifndef INT8_TYPE
7407 # ifdef HAVE_INT8_T
7408 # define INT8_TYPE int8_t
7409 # else
7410 # define INT8_TYPE signed char
7411 # endif
7412 #endif
7413 #ifndef LONGDOUBLE_TYPE
7414 # define LONGDOUBLE_TYPE long double
7415 #endif
7416 typedef sqlite_int64 i64; /* 8-byte signed integer */
7417 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
7418 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
7419 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
7420 typedef INT16_TYPE i16; /* 2-byte signed integer */
7421 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
7422 typedef INT8_TYPE i8; /* 1-byte signed integer */
7425 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7426 ** that can be stored in a u32 without loss of data. The value
7427 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
7428 ** have to specify the value in the less intuitive manner shown:
7430 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
7433 ** Macros to determine whether the machine is big or little endian,
7434 ** evaluated at runtime.
7436 #ifdef SQLITE_AMALGAMATION
7437 SQLITE_PRIVATE const int sqlite3one = 1;
7438 #else
7439 SQLITE_PRIVATE const int sqlite3one;
7440 #endif
7441 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7442 || defined(__x86_64) || defined(__x86_64__)
7443 # define SQLITE_BIGENDIAN 0
7444 # define SQLITE_LITTLEENDIAN 1
7445 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
7446 #else
7447 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
7448 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7449 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7450 #endif
7453 ** Constants for the largest and smallest possible 64-bit signed integers.
7454 ** These macros are designed to work correctly on both 32-bit and 64-bit
7455 ** compilers.
7457 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
7458 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7461 ** Round up a number to the next larger multiple of 8. This is used
7462 ** to force 8-byte alignment on 64-bit architectures.
7464 #define ROUND8(x) (((x)+7)&~7)
7467 ** Round down to the nearest multiple of 8
7469 #define ROUNDDOWN8(x) ((x)&~7)
7472 ** Assert that the pointer X is aligned to an 8-byte boundary. This
7473 ** macro is used only within assert() to verify that the code gets
7474 ** all alignment restrictions correct.
7476 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
7477 ** underlying malloc() implemention might return us 4-byte aligned
7478 ** pointers. In that case, only verify 4-byte alignment.
7480 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
7481 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
7482 #else
7483 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
7484 #endif
7488 ** An instance of the following structure is used to store the busy-handler
7489 ** callback for a given sqlite handle.
7491 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7492 ** callback for the database handle. Each pager opened via the sqlite
7493 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7494 ** callback is currently invoked only from within pager.c.
7496 typedef struct BusyHandler BusyHandler;
7497 struct BusyHandler {
7498 int (*xFunc)(void *,int); /* The busy callback */
7499 void *pArg; /* First arg to busy callback */
7500 int nBusy; /* Incremented with each busy call */
7504 ** Name of the master database table. The master database table
7505 ** is a special table that holds the names and attributes of all
7506 ** user tables and indices.
7508 #define MASTER_NAME "sqlite_master"
7509 #define TEMP_MASTER_NAME "sqlite_temp_master"
7512 ** The root-page of the master database table.
7514 #define MASTER_ROOT 1
7517 ** The name of the schema table.
7519 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7522 ** A convenience macro that returns the number of elements in
7523 ** an array.
7525 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
7528 ** The following value as a destructor means to use sqlite3DbFree().
7529 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7531 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree)
7534 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7535 ** not support Writable Static Data (WSD) such as global and static variables.
7536 ** All variables must either be on the stack or dynamically allocated from
7537 ** the heap. When WSD is unsupported, the variable declarations scattered
7538 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
7539 ** macro is used for this purpose. And instead of referencing the variable
7540 ** directly, we use its constant as a key to lookup the run-time allocated
7541 ** buffer that holds real variable. The constant is also the initializer
7542 ** for the run-time allocated buffer.
7544 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7545 ** macros become no-ops and have zero performance impact.
7547 #ifdef SQLITE_OMIT_WSD
7548 #define SQLITE_WSD const
7549 #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7550 #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7551 SQLITE_API int sqlite3_wsd_init(int N, int J);
7552 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
7553 #else
7554 #define SQLITE_WSD
7555 #define GLOBAL(t,v) v
7556 #define sqlite3GlobalConfig sqlite3Config
7557 #endif
7560 ** The following macros are used to suppress compiler warnings and to
7561 ** make it clear to human readers when a function parameter is deliberately
7562 ** left unused within the body of a function. This usually happens when
7563 ** a function is called via a function pointer. For example the
7564 ** implementation of an SQL aggregate step callback may not use the
7565 ** parameter indicating the number of arguments passed to the aggregate,
7566 ** if it knows that this is enforced elsewhere.
7568 ** When a function parameter is not used at all within the body of a function,
7569 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7570 ** However, these macros may also be used to suppress warnings related to
7571 ** parameters that may or may not be used depending on compilation options.
7572 ** For example those parameters only used in assert() statements. In these
7573 ** cases the parameters are named as per the usual conventions.
7575 #define UNUSED_PARAMETER(x) (void)(x)
7576 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7579 ** Forward references to structures
7581 typedef struct AggInfo AggInfo;
7582 typedef struct AuthContext AuthContext;
7583 typedef struct AutoincInfo AutoincInfo;
7584 typedef struct Bitvec Bitvec;
7585 typedef struct CollSeq CollSeq;
7586 typedef struct Column Column;
7587 typedef struct Db Db;
7588 typedef struct Schema Schema;
7589 typedef struct Expr Expr;
7590 typedef struct ExprList ExprList;
7591 typedef struct ExprSpan ExprSpan;
7592 typedef struct FKey FKey;
7593 typedef struct FuncDestructor FuncDestructor;
7594 typedef struct FuncDef FuncDef;
7595 typedef struct FuncDefHash FuncDefHash;
7596 typedef struct IdList IdList;
7597 typedef struct Index Index;
7598 typedef struct IndexSample IndexSample;
7599 typedef struct KeyClass KeyClass;
7600 typedef struct KeyInfo KeyInfo;
7601 typedef struct Lookaside Lookaside;
7602 typedef struct LookasideSlot LookasideSlot;
7603 typedef struct Module Module;
7604 typedef struct NameContext NameContext;
7605 typedef struct Parse Parse;
7606 typedef struct RowSet RowSet;
7607 typedef struct Savepoint Savepoint;
7608 typedef struct Select Select;
7609 typedef struct SrcList SrcList;
7610 typedef struct StrAccum StrAccum;
7611 typedef struct Table Table;
7612 typedef struct TableLock TableLock;
7613 typedef struct Token Token;
7614 typedef struct Trigger Trigger;
7615 typedef struct TriggerPrg TriggerPrg;
7616 typedef struct TriggerStep TriggerStep;
7617 typedef struct UnpackedRecord UnpackedRecord;
7618 typedef struct VTable VTable;
7619 typedef struct Walker Walker;
7620 typedef struct WherePlan WherePlan;
7621 typedef struct WhereInfo WhereInfo;
7622 typedef struct WhereLevel WhereLevel;
7625 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
7626 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7627 ** pointer types (i.e. FuncDef) defined above.
7629 /************** Include btree.h in the middle of sqliteInt.h *****************/
7630 /************** Begin file btree.h *******************************************/
7632 ** 2001 September 15
7634 ** The author disclaims copyright to this source code. In place of
7635 ** a legal notice, here is a blessing:
7637 ** May you do good and not evil.
7638 ** May you find forgiveness for yourself and forgive others.
7639 ** May you share freely, never taking more than you give.
7641 *************************************************************************
7642 ** This header file defines the interface that the sqlite B-Tree file
7643 ** subsystem. See comments in the source code for a detailed description
7644 ** of what each interface routine does.
7646 #ifndef _BTREE_H_
7647 #define _BTREE_H_
7649 /* TODO: This definition is just included so other modules compile. It
7650 ** needs to be revisited.
7652 #define SQLITE_N_BTREE_META 10
7655 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7656 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7658 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7659 #define SQLITE_DEFAULT_AUTOVACUUM 0
7660 #endif
7662 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
7663 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
7664 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
7667 ** Forward declarations of structure
7669 typedef struct Btree Btree;
7670 typedef struct BtCursor BtCursor;
7671 typedef struct BtShared BtShared;
7674 SQLITE_PRIVATE int sqlite3BtreeOpen(
7675 const char *zFilename, /* Name of database file to open */
7676 sqlite3 *db, /* Associated database connection */
7677 Btree **ppBtree, /* Return open Btree* here */
7678 int flags, /* Flags */
7679 int vfsFlags /* Flags passed through to VFS open */
7682 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7683 ** following values.
7685 ** NOTE: These values must match the corresponding PAGER_ values in
7686 ** pager.h.
7688 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
7689 #define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
7690 #define BTREE_MEMORY 4 /* This is an in-memory DB */
7691 #define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */
7692 #define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */
7694 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7695 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7696 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
7697 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7698 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7699 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7700 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7701 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7702 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7703 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7704 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7705 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7706 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7707 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7708 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
7709 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7710 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7711 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7712 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7713 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7714 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7715 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7716 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7717 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7718 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7719 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7721 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7722 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7723 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7725 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7727 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7728 ** of the flags shown below.
7730 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
7731 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
7732 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
7733 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
7734 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
7735 ** indices.)
7737 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
7738 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
7740 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7741 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7742 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7744 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7745 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7748 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7749 ** should be one of the following values. The integer values are assigned
7750 ** to constants so that the offset of the corresponding field in an
7751 ** SQLite database header may be found using the following formula:
7753 ** offset = 36 + (idx * 4)
7755 ** For example, the free-page-count field is located at byte offset 36 of
7756 ** the database file header. The incr-vacuum-flag field is located at
7757 ** byte offset 64 (== 36+4*7).
7759 #define BTREE_FREE_PAGE_COUNT 0
7760 #define BTREE_SCHEMA_VERSION 1
7761 #define BTREE_FILE_FORMAT 2
7762 #define BTREE_DEFAULT_CACHE_SIZE 3
7763 #define BTREE_LARGEST_ROOT_PAGE 4
7764 #define BTREE_TEXT_ENCODING 5
7765 #define BTREE_USER_VERSION 6
7766 #define BTREE_INCR_VACUUM 7
7768 SQLITE_PRIVATE int sqlite3BtreeCursor(
7769 Btree*, /* BTree containing table to open */
7770 int iTable, /* Index of root page */
7771 int wrFlag, /* 1 for writing. 0 for read-only */
7772 struct KeyInfo*, /* First argument to compare function */
7773 BtCursor *pCursor /* Space to write cursor structure */
7775 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7776 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7778 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7779 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7780 BtCursor*,
7781 UnpackedRecord *pUnKey,
7782 i64 intKey,
7783 int bias,
7784 int *pRes
7786 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7787 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7788 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7789 const void *pData, int nData,
7790 int nZero, int bias, int seekResult);
7791 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7792 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7793 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7794 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7795 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7796 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7797 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7798 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7799 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7800 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7801 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7802 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7803 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7805 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7806 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7808 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7809 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7810 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7812 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7814 #ifndef NDEBUG
7815 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7816 #endif
7818 #ifndef SQLITE_OMIT_BTREECOUNT
7819 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7820 #endif
7822 #ifdef SQLITE_TEST
7823 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7824 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7825 #endif
7827 #ifndef SQLITE_OMIT_WAL
7828 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
7829 #endif
7832 ** If we are not using shared cache, then there is no need to
7833 ** use mutexes to access the BtShared structures. So make the
7834 ** Enter and Leave procedures no-ops.
7836 #ifndef SQLITE_OMIT_SHARED_CACHE
7837 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
7838 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
7839 #else
7840 # define sqlite3BtreeEnter(X)
7841 # define sqlite3BtreeEnterAll(X)
7842 #endif
7844 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7845 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
7846 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
7847 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
7848 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
7849 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
7850 #ifndef NDEBUG
7851 /* These routines are used inside assert() statements only. */
7852 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
7853 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7854 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
7855 #endif
7856 #else
7858 # define sqlite3BtreeSharable(X) 0
7859 # define sqlite3BtreeLeave(X)
7860 # define sqlite3BtreeEnterCursor(X)
7861 # define sqlite3BtreeLeaveCursor(X)
7862 # define sqlite3BtreeLeaveAll(X)
7864 # define sqlite3BtreeHoldsMutex(X) 1
7865 # define sqlite3BtreeHoldsAllMutexes(X) 1
7866 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
7867 #endif
7870 #endif /* _BTREE_H_ */
7872 /************** End of btree.h ***********************************************/
7873 /************** Continuing where we left off in sqliteInt.h ******************/
7874 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7875 /************** Begin file vdbe.h ********************************************/
7877 ** 2001 September 15
7879 ** The author disclaims copyright to this source code. In place of
7880 ** a legal notice, here is a blessing:
7882 ** May you do good and not evil.
7883 ** May you find forgiveness for yourself and forgive others.
7884 ** May you share freely, never taking more than you give.
7886 *************************************************************************
7887 ** Header file for the Virtual DataBase Engine (VDBE)
7889 ** This header defines the interface to the virtual database engine
7890 ** or VDBE. The VDBE implements an abstract machine that runs a
7891 ** simple program to access and modify the underlying database.
7893 #ifndef _SQLITE_VDBE_H_
7894 #define _SQLITE_VDBE_H_
7897 ** A single VDBE is an opaque structure named "Vdbe". Only routines
7898 ** in the source file sqliteVdbe.c are allowed to see the insides
7899 ** of this structure.
7901 typedef struct Vdbe Vdbe;
7904 ** The names of the following types declared in vdbeInt.h are required
7905 ** for the VdbeOp definition.
7907 typedef struct VdbeFunc VdbeFunc;
7908 typedef struct Mem Mem;
7909 typedef struct SubProgram SubProgram;
7912 ** A single instruction of the virtual machine has an opcode
7913 ** and as many as three operands. The instruction is recorded
7914 ** as an instance of the following structure:
7916 struct VdbeOp {
7917 u8 opcode; /* What operation to perform */
7918 signed char p4type; /* One of the P4_xxx constants for p4 */
7919 u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
7920 u8 p5; /* Fifth parameter is an unsigned character */
7921 int p1; /* First operand */
7922 int p2; /* Second parameter (often the jump destination) */
7923 int p3; /* The third parameter */
7924 union { /* fourth parameter */
7925 int i; /* Integer value if p4type==P4_INT32 */
7926 void *p; /* Generic pointer */
7927 char *z; /* Pointer to data for string (char array) types */
7928 i64 *pI64; /* Used when p4type is P4_INT64 */
7929 double *pReal; /* Used when p4type is P4_REAL */
7930 FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
7931 VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
7932 CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
7933 Mem *pMem; /* Used when p4type is P4_MEM */
7934 VTable *pVtab; /* Used when p4type is P4_VTAB */
7935 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
7936 int *ai; /* Used when p4type is P4_INTARRAY */
7937 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
7938 } p4;
7939 #ifdef SQLITE_DEBUG
7940 char *zComment; /* Comment to improve readability */
7941 #endif
7942 #ifdef VDBE_PROFILE
7943 int cnt; /* Number of times this instruction was executed */
7944 u64 cycles; /* Total time spent executing this instruction */
7945 #endif
7947 typedef struct VdbeOp VdbeOp;
7951 ** A sub-routine used to implement a trigger program.
7953 struct SubProgram {
7954 VdbeOp *aOp; /* Array of opcodes for sub-program */
7955 int nOp; /* Elements in aOp[] */
7956 int nMem; /* Number of memory cells required */
7957 int nCsr; /* Number of cursors required */
7958 void *token; /* id that may be used to recursive triggers */
7959 SubProgram *pNext; /* Next sub-program already visited */
7963 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7964 ** it takes up less space.
7966 struct VdbeOpList {
7967 u8 opcode; /* What operation to perform */
7968 signed char p1; /* First operand */
7969 signed char p2; /* Second parameter (often the jump destination) */
7970 signed char p3; /* Third parameter */
7972 typedef struct VdbeOpList VdbeOpList;
7975 ** Allowed values of VdbeOp.p4type
7977 #define P4_NOTUSED 0 /* The P4 parameter is not used */
7978 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
7979 #define P4_STATIC (-2) /* Pointer to a static string */
7980 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
7981 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
7982 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
7983 #define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */
7984 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
7985 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
7986 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7987 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7988 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
7989 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
7990 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
7991 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7992 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
7994 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7995 ** is made. That copy is freed when the Vdbe is finalized. But if the
7996 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
7997 ** gets freed when the Vdbe is finalized so it still should be obtained
7998 ** from a single sqliteMalloc(). But no copy is made and the calling
7999 ** function should *not* try to free the KeyInfo.
8001 #define P4_KEYINFO_HANDOFF (-16)
8002 #define P4_KEYINFO_STATIC (-17)
8005 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
8006 ** number of columns of data returned by the statement.
8008 #define COLNAME_NAME 0
8009 #define COLNAME_DECLTYPE 1
8010 #define COLNAME_DATABASE 2
8011 #define COLNAME_TABLE 3
8012 #define COLNAME_COLUMN 4
8013 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8014 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
8015 #else
8016 # ifdef SQLITE_OMIT_DECLTYPE
8017 # define COLNAME_N 1 /* Store only the name */
8018 # else
8019 # define COLNAME_N 2 /* Store the name and decltype */
8020 # endif
8021 #endif
8024 ** The following macro converts a relative address in the p2 field
8025 ** of a VdbeOp structure into a negative number so that
8026 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
8027 ** the macro again restores the address.
8029 #define ADDR(X) (-1-(X))
8032 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8033 ** header file that defines a number for each opcode used by the VDBE.
8035 /************** Include opcodes.h in the middle of vdbe.h ********************/
8036 /************** Begin file opcodes.h *****************************************/
8037 /* Automatically generated. Do not edit */
8038 /* See the mkopcodeh.awk script for details */
8039 #define OP_Goto 1
8040 #define OP_Gosub 2
8041 #define OP_Return 3
8042 #define OP_Yield 4
8043 #define OP_HaltIfNull 5
8044 #define OP_Halt 6
8045 #define OP_Integer 7
8046 #define OP_Int64 8
8047 #define OP_Real 130 /* same as TK_FLOAT */
8048 #define OP_String8 94 /* same as TK_STRING */
8049 #define OP_String 9
8050 #define OP_Null 10
8051 #define OP_Blob 11
8052 #define OP_Variable 12
8053 #define OP_Move 13
8054 #define OP_Copy 14
8055 #define OP_SCopy 15
8056 #define OP_ResultRow 16
8057 #define OP_Concat 91 /* same as TK_CONCAT */
8058 #define OP_Add 86 /* same as TK_PLUS */
8059 #define OP_Subtract 87 /* same as TK_MINUS */
8060 #define OP_Multiply 88 /* same as TK_STAR */
8061 #define OP_Divide 89 /* same as TK_SLASH */
8062 #define OP_Remainder 90 /* same as TK_REM */
8063 #define OP_CollSeq 17
8064 #define OP_Function 18
8065 #define OP_BitAnd 82 /* same as TK_BITAND */
8066 #define OP_BitOr 83 /* same as TK_BITOR */
8067 #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
8068 #define OP_ShiftRight 85 /* same as TK_RSHIFT */
8069 #define OP_AddImm 20
8070 #define OP_MustBeInt 21
8071 #define OP_RealAffinity 22
8072 #define OP_ToText 141 /* same as TK_TO_TEXT */
8073 #define OP_ToBlob 142 /* same as TK_TO_BLOB */
8074 #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
8075 #define OP_ToInt 144 /* same as TK_TO_INT */
8076 #define OP_ToReal 145 /* same as TK_TO_REAL */
8077 #define OP_Eq 76 /* same as TK_EQ */
8078 #define OP_Ne 75 /* same as TK_NE */
8079 #define OP_Lt 79 /* same as TK_LT */
8080 #define OP_Le 78 /* same as TK_LE */
8081 #define OP_Gt 77 /* same as TK_GT */
8082 #define OP_Ge 80 /* same as TK_GE */
8083 #define OP_Permutation 23
8084 #define OP_Compare 24
8085 #define OP_Jump 25
8086 #define OP_And 69 /* same as TK_AND */
8087 #define OP_Or 68 /* same as TK_OR */
8088 #define OP_Not 19 /* same as TK_NOT */
8089 #define OP_BitNot 93 /* same as TK_BITNOT */
8090 #define OP_If 26
8091 #define OP_IfNot 27
8092 #define OP_IsNull 73 /* same as TK_ISNULL */
8093 #define OP_NotNull 74 /* same as TK_NOTNULL */
8094 #define OP_Column 28
8095 #define OP_Affinity 29
8096 #define OP_MakeRecord 30
8097 #define OP_Count 31
8098 #define OP_Savepoint 32
8099 #define OP_AutoCommit 33
8100 #define OP_Transaction 34
8101 #define OP_ReadCookie 35
8102 #define OP_SetCookie 36
8103 #define OP_VerifyCookie 37
8104 #define OP_OpenRead 38
8105 #define OP_OpenWrite 39
8106 #define OP_OpenAutoindex 40
8107 #define OP_OpenEphemeral 41
8108 #define OP_OpenPseudo 42
8109 #define OP_Close 43
8110 #define OP_SeekLt 44
8111 #define OP_SeekLe 45
8112 #define OP_SeekGe 46
8113 #define OP_SeekGt 47
8114 #define OP_Seek 48
8115 #define OP_NotFound 49
8116 #define OP_Found 50
8117 #define OP_IsUnique 51
8118 #define OP_NotExists 52
8119 #define OP_Sequence 53
8120 #define OP_NewRowid 54
8121 #define OP_Insert 55
8122 #define OP_InsertInt 56
8123 #define OP_Delete 57
8124 #define OP_ResetCount 58
8125 #define OP_RowKey 59
8126 #define OP_RowData 60
8127 #define OP_Rowid 61
8128 #define OP_NullRow 62
8129 #define OP_Last 63
8130 #define OP_Sort 64
8131 #define OP_Rewind 65
8132 #define OP_Prev 66
8133 #define OP_Next 67
8134 #define OP_IdxInsert 70
8135 #define OP_IdxDelete 71
8136 #define OP_IdxRowid 72
8137 #define OP_IdxLT 81
8138 #define OP_IdxGE 92
8139 #define OP_Destroy 95
8140 #define OP_Clear 96
8141 #define OP_CreateIndex 97
8142 #define OP_CreateTable 98
8143 #define OP_ParseSchema 99
8144 #define OP_LoadAnalysis 100
8145 #define OP_DropTable 101
8146 #define OP_DropIndex 102
8147 #define OP_DropTrigger 103
8148 #define OP_IntegrityCk 104
8149 #define OP_RowSetAdd 105
8150 #define OP_RowSetRead 106
8151 #define OP_RowSetTest 107
8152 #define OP_Program 108
8153 #define OP_Param 109
8154 #define OP_FkCounter 110
8155 #define OP_FkIfZero 111
8156 #define OP_MemMax 112
8157 #define OP_IfPos 113
8158 #define OP_IfNeg 114
8159 #define OP_IfZero 115
8160 #define OP_AggStep 116
8161 #define OP_AggFinal 117
8162 #define OP_Checkpoint 118
8163 #define OP_JournalMode 119
8164 #define OP_Vacuum 120
8165 #define OP_IncrVacuum 121
8166 #define OP_Expire 122
8167 #define OP_TableLock 123
8168 #define OP_VBegin 124
8169 #define OP_VCreate 125
8170 #define OP_VDestroy 126
8171 #define OP_VOpen 127
8172 #define OP_VFilter 128
8173 #define OP_VColumn 129
8174 #define OP_VNext 131
8175 #define OP_VRename 132
8176 #define OP_VUpdate 133
8177 #define OP_Pagecount 134
8178 #define OP_MaxPgcnt 135
8179 #define OP_Trace 136
8180 #define OP_Noop 137
8181 #define OP_Explain 138
8183 /* The following opcode values are never used */
8184 #define OP_NotUsed_139 139
8185 #define OP_NotUsed_140 140
8188 /* Properties such as "out2" or "jump" that are specified in
8189 ** comments following the "case" for each opcode in the vdbe.c
8190 ** are encoded into bitvectors as follows:
8192 #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
8193 #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
8194 #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
8195 #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
8196 #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
8197 #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
8198 #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
8199 #define OPFLG_INITIALIZER {\
8200 /* 0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
8201 /* 8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8202 /* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8203 /* 24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8204 /* 32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
8205 /* 40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
8206 /* 48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
8207 /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
8208 /* 64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
8209 /* 72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8210 /* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8211 /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
8212 /* 96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8213 /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
8214 /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8215 /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8216 /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\
8217 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
8218 /* 144 */ 0x04, 0x04,}
8220 /************** End of opcodes.h *********************************************/
8221 /************** Continuing where we left off in vdbe.h ***********************/
8224 ** Prototypes for the VDBE interface. See comments on the implementation
8225 ** for a description of what each of these routines does.
8227 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8228 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8229 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8230 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8231 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8232 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8233 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8234 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8235 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
8236 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
8237 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
8238 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8239 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8240 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
8241 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8242 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8243 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8244 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8245 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8246 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8247 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8248 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
8249 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8250 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8251 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8252 #ifdef SQLITE_DEBUG
8253 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8254 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
8255 #endif
8256 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8257 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8258 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8259 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8260 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8261 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8262 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8263 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8264 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8265 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8266 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8267 #ifndef SQLITE_OMIT_TRACE
8268 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8269 #endif
8271 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
8272 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
8273 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8275 #ifndef SQLITE_OMIT_TRIGGER
8276 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8277 #endif
8280 #ifndef NDEBUG
8281 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
8282 # define VdbeComment(X) sqlite3VdbeComment X
8283 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8284 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
8285 #else
8286 # define VdbeComment(X)
8287 # define VdbeNoopComment(X)
8288 #endif
8290 #endif
8292 /************** End of vdbe.h ************************************************/
8293 /************** Continuing where we left off in sqliteInt.h ******************/
8294 /************** Include pager.h in the middle of sqliteInt.h *****************/
8295 /************** Begin file pager.h *******************************************/
8297 ** 2001 September 15
8299 ** The author disclaims copyright to this source code. In place of
8300 ** a legal notice, here is a blessing:
8302 ** May you do good and not evil.
8303 ** May you find forgiveness for yourself and forgive others.
8304 ** May you share freely, never taking more than you give.
8306 *************************************************************************
8307 ** This header file defines the interface that the sqlite page cache
8308 ** subsystem. The page cache subsystem reads and writes a file a page
8309 ** at a time and provides a journal for rollback.
8312 #ifndef _PAGER_H_
8313 #define _PAGER_H_
8316 ** Default maximum size for persistent journal files. A negative
8317 ** value means no limit. This value may be overridden using the
8318 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8320 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8321 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8322 #endif
8325 ** The type used to represent a page number. The first page in a file
8326 ** is called page 1. 0 is used to represent "not a page".
8328 typedef u32 Pgno;
8331 ** Each open file is managed by a separate instance of the "Pager" structure.
8333 typedef struct Pager Pager;
8336 ** Handle type for pages.
8338 typedef struct PgHdr DbPage;
8341 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8342 ** reserved for working around a windows/posix incompatibility). It is
8343 ** used in the journal to signify that the remainder of the journal file
8344 ** is devoted to storing a master journal name - there are no more pages to
8345 ** roll back. See comments for function writeMasterJournal() in pager.c
8346 ** for details.
8348 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8351 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8353 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8355 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
8356 #define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
8357 #define PAGER_MEMORY 0x0004 /* In-memory database */
8360 ** Valid values for the second argument to sqlite3PagerLockingMode().
8362 #define PAGER_LOCKINGMODE_QUERY -1
8363 #define PAGER_LOCKINGMODE_NORMAL 0
8364 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
8367 ** Numeric constants that encode the journalmode.
8369 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
8370 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
8371 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
8372 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
8373 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
8374 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
8375 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
8378 ** The remainder of this file contains the declarations of the functions
8379 ** that make up the Pager sub-system API. See source code comments for
8380 ** a detailed description of each routine.
8383 /* Open and close a Pager connection. */
8384 SQLITE_PRIVATE int sqlite3PagerOpen(
8385 sqlite3_vfs*,
8386 Pager **ppPager,
8387 const char*,
8388 int,
8389 int,
8390 int,
8391 void(*)(DbPage*)
8393 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8394 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8396 /* Functions used to configure a Pager object. */
8397 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8398 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8399 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8400 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8401 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8402 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8403 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8404 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8405 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8406 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8407 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8409 /* Functions used to obtain and release page references. */
8410 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8411 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8412 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8413 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8414 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8416 /* Operations on page references. */
8417 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8418 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8419 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8420 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8421 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
8422 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
8424 /* Functions used to manage pager transactions and savepoints. */
8425 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8426 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8427 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8428 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8429 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8430 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8431 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8432 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8433 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8434 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8436 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
8437 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8438 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8439 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8440 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8442 /* Functions used to query pager state and configuration. */
8443 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8444 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8445 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
8446 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8447 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8448 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8449 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8450 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8451 /* This function is for preload-cache.patch for Chromium: */
8452 SQLITE_PRIVATE int sqlite3PagerLoadall(Pager*);
8453 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8454 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8456 /* Functions used to truncate the database file. */
8457 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8459 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
8460 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
8461 #endif
8463 /* Functions to support testing and debugging. */
8464 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8465 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
8466 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
8467 #endif
8468 #ifdef SQLITE_TEST
8469 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
8470 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
8471 void disable_simulated_io_errors(void);
8472 void enable_simulated_io_errors(void);
8473 #else
8474 # define disable_simulated_io_errors()
8475 # define enable_simulated_io_errors()
8476 #endif
8478 #endif /* _PAGER_H_ */
8480 /************** End of pager.h ***********************************************/
8481 /************** Continuing where we left off in sqliteInt.h ******************/
8482 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8483 /************** Begin file pcache.h ******************************************/
8485 ** 2008 August 05
8487 ** The author disclaims copyright to this source code. In place of
8488 ** a legal notice, here is a blessing:
8490 ** May you do good and not evil.
8491 ** May you find forgiveness for yourself and forgive others.
8492 ** May you share freely, never taking more than you give.
8494 *************************************************************************
8495 ** This header file defines the interface that the sqlite page cache
8496 ** subsystem.
8499 #ifndef _PCACHE_H_
8501 typedef struct PgHdr PgHdr;
8502 typedef struct PCache PCache;
8505 ** Every page in the cache is controlled by an instance of the following
8506 ** structure.
8508 struct PgHdr {
8509 void *pData; /* Content of this page */
8510 void *pExtra; /* Extra content */
8511 PgHdr *pDirty; /* Transient list of dirty pages */
8512 Pgno pgno; /* Page number for this page */
8513 Pager *pPager; /* The pager this page is part of */
8514 #ifdef SQLITE_CHECK_PAGES
8515 u32 pageHash; /* Hash of page content */
8516 #endif
8517 u16 flags; /* PGHDR flags defined below */
8519 /**********************************************************************
8520 ** Elements above are public. All that follows is private to pcache.c
8521 ** and should not be accessed by other modules.
8523 i16 nRef; /* Number of users of this page */
8524 PCache *pCache; /* Cache that owns this page */
8526 PgHdr *pDirtyNext; /* Next element in list of dirty pages */
8527 PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
8530 /* Bit values for PgHdr.flags */
8531 #define PGHDR_DIRTY 0x002 /* Page has changed */
8532 #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
8533 ** writing this page to the database */
8534 #define PGHDR_NEED_READ 0x008 /* Content is unread */
8535 #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
8536 #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
8538 /* Initialize and shutdown the page cache subsystem */
8539 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8540 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8542 /* Page cache buffer management:
8543 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8545 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8547 /* Create a new pager cache.
8548 ** Under memory stress, invoke xStress to try to make pages clean.
8549 ** Only clean and unpinned pages can be reclaimed.
8551 SQLITE_PRIVATE void sqlite3PcacheOpen(
8552 int szPage, /* Size of every page */
8553 int szExtra, /* Extra space associated with each page */
8554 int bPurgeable, /* True if pages are on backing store */
8555 int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8556 void *pStress, /* Argument to xStress */
8557 PCache *pToInit /* Preallocated space for the PCache */
8560 /* Modify the page-size after the cache has been created. */
8561 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8563 /* Return the size in bytes of a PCache object. Used to preallocate
8564 ** storage space.
8566 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8568 /* One release per successful fetch. Page is pinned until released.
8569 ** Reference counted.
8571 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8572 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8574 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
8575 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
8576 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
8577 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
8579 /* Change a page number. Used by incr-vacuum. */
8580 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8582 /* Remove all pages with pgno>x. Reset the cache if x==0 */
8583 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8585 /* Get a list of all dirty pages in the cache, sorted by page number */
8586 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8588 /* Reset and close the cache object */
8589 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8591 /* Clear flags from pages of the page cache */
8592 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8594 /* Discard the contents of the cache */
8595 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8597 /* Return the total number of outstanding page references */
8598 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8600 /* Increment the reference count of an existing page */
8601 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8603 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8605 /* Return the total number of pages stored in the cache */
8606 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8608 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8609 /* Iterate through all dirty pages currently stored in the cache. This
8610 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
8611 ** library is built.
8613 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8614 #endif
8616 /* Set and get the suggested cache-size for the specified pager-cache.
8618 ** If no global maximum is configured, then the system attempts to limit
8619 ** the total number of pages cached by purgeable pager-caches to the sum
8620 ** of the suggested cache-sizes.
8622 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8623 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8625 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8626 /* Try to return memory used by the pcache module to the main memory heap */
8627 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8628 #endif
8630 #ifdef SQLITE_TEST
8631 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8632 #endif
8634 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8636 #endif /* _PCACHE_H_ */
8638 /************** End of pcache.h **********************************************/
8639 /************** Continuing where we left off in sqliteInt.h ******************/
8641 /************** Include os.h in the middle of sqliteInt.h ********************/
8642 /************** Begin file os.h **********************************************/
8644 ** 2001 September 16
8646 ** The author disclaims copyright to this source code. In place of
8647 ** a legal notice, here is a blessing:
8649 ** May you do good and not evil.
8650 ** May you find forgiveness for yourself and forgive others.
8651 ** May you share freely, never taking more than you give.
8653 ******************************************************************************
8655 ** This header file (together with is companion C source-code file
8656 ** "os.c") attempt to abstract the underlying operating system so that
8657 ** the SQLite library will work on both POSIX and windows systems.
8659 ** This header file is #include-ed by sqliteInt.h and thus ends up
8660 ** being included by every source file.
8662 #ifndef _SQLITE_OS_H_
8663 #define _SQLITE_OS_H_
8666 ** Figure out if we are dealing with Unix, Windows, or some other
8667 ** operating system. After the following block of preprocess macros,
8668 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
8669 ** will defined to either 1 or 0. One of the four will be 1. The other
8670 ** three will be 0.
8672 #if defined(SQLITE_OS_OTHER)
8673 # if SQLITE_OS_OTHER==1
8674 # undef SQLITE_OS_UNIX
8675 # define SQLITE_OS_UNIX 0
8676 # undef SQLITE_OS_WIN
8677 # define SQLITE_OS_WIN 0
8678 # undef SQLITE_OS_OS2
8679 # define SQLITE_OS_OS2 0
8680 # else
8681 # undef SQLITE_OS_OTHER
8682 # endif
8683 #endif
8684 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8685 # define SQLITE_OS_OTHER 0
8686 # ifndef SQLITE_OS_WIN
8687 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8688 # define SQLITE_OS_WIN 1
8689 # define SQLITE_OS_UNIX 0
8690 # define SQLITE_OS_OS2 0
8691 # elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8692 # define SQLITE_OS_WIN 0
8693 # define SQLITE_OS_UNIX 0
8694 # define SQLITE_OS_OS2 1
8695 # else
8696 # define SQLITE_OS_WIN 0
8697 # define SQLITE_OS_UNIX 1
8698 # define SQLITE_OS_OS2 0
8699 # endif
8700 # else
8701 # define SQLITE_OS_UNIX 0
8702 # define SQLITE_OS_OS2 0
8703 # endif
8704 #else
8705 # ifndef SQLITE_OS_WIN
8706 # define SQLITE_OS_WIN 0
8707 # endif
8708 #endif
8711 ** Determine if we are dealing with WindowsCE - which has a much
8712 ** reduced API.
8714 #if defined(_WIN32_WCE)
8715 # define SQLITE_OS_WINCE 1
8716 #else
8717 # define SQLITE_OS_WINCE 0
8718 #endif
8722 ** Define the maximum size of a temporary filename
8724 #if SQLITE_OS_WIN
8725 # include <windows.h>
8726 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8727 #elif SQLITE_OS_OS2
8728 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8729 # include <os2safe.h> /* has to be included before os2.h for linking to work */
8730 # endif
8731 # define INCL_DOSDATETIME
8732 # define INCL_DOSFILEMGR
8733 # define INCL_DOSERRORS
8734 # define INCL_DOSMISC
8735 # define INCL_DOSPROCESS
8736 # define INCL_DOSMODULEMGR
8737 # define INCL_DOSSEMAPHORES
8738 # include <os2.h>
8739 # include <uconv.h>
8740 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8741 #else
8742 # define SQLITE_TEMPNAME_SIZE 200
8743 #endif
8745 /* If the SET_FULLSYNC macro is not defined above, then make it
8746 ** a no-op
8748 #ifndef SET_FULLSYNC
8749 # define SET_FULLSYNC(x,y)
8750 #endif
8753 ** The default size of a disk sector
8755 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8756 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8757 #endif
8760 ** Temporary files are named starting with this prefix followed by 16 random
8761 ** alphanumeric characters, and no file extension. They are stored in the
8762 ** OS's standard temporary file directory, and are deleted prior to exit.
8763 ** If sqlite is being embedded in another program, you may wish to change the
8764 ** prefix to reflect your program's name, so that if your program exits
8765 ** prematurely, old temporary files can be easily identified. This can be done
8766 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8768 ** 2006-10-31: The default prefix used to be "sqlite_". But then
8769 ** Mcafee started using SQLite in their anti-virus product and it
8770 ** started putting files with the "sqlite" name in the c:/temp folder.
8771 ** This annoyed many windows users. Those users would then do a
8772 ** Google search for "sqlite", find the telephone numbers of the
8773 ** developers and call to wake them up at night and complain.
8774 ** For this reason, the default name prefix is changed to be "sqlite"
8775 ** spelled backwards. So the temp files are still identified, but
8776 ** anybody smart enough to figure out the code is also likely smart
8777 ** enough to know that calling the developer will not help get rid
8778 ** of the file.
8780 #ifndef SQLITE_TEMP_FILE_PREFIX
8781 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8782 #endif
8785 ** The following values may be passed as the second argument to
8786 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8788 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
8789 ** RESERVED: A single process may hold a RESERVED lock on a file at
8790 ** any time. Other processes may hold and obtain new SHARED locks.
8791 ** PENDING: A single process may hold a PENDING lock on a file at
8792 ** any one time. Existing SHARED locks may persist, but no new
8793 ** SHARED locks may be obtained by other processes.
8794 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8796 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8797 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8798 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8799 ** sqlite3OsLock().
8801 #define NO_LOCK 0
8802 #define SHARED_LOCK 1
8803 #define RESERVED_LOCK 2
8804 #define PENDING_LOCK 3
8805 #define EXCLUSIVE_LOCK 4
8808 ** File Locking Notes: (Mostly about windows but also some info for Unix)
8810 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8811 ** those functions are not available. So we use only LockFile() and
8812 ** UnlockFile().
8814 ** LockFile() prevents not just writing but also reading by other processes.
8815 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
8816 ** byte out of a specific range of bytes. The lock byte is obtained at
8817 ** random so two separate readers can probably access the file at the
8818 ** same time, unless they are unlucky and choose the same lock byte.
8819 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8820 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
8821 ** a single byte of the file that is designated as the reserved lock byte.
8822 ** A PENDING_LOCK is obtained by locking a designated byte different from
8823 ** the RESERVED_LOCK byte.
8825 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8826 ** which means we can use reader/writer locks. When reader/writer locks
8827 ** are used, the lock is placed on the same range of bytes that is used
8828 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
8829 ** will support two or more Win95 readers or two or more WinNT readers.
8830 ** But a single Win95 reader will lock out all WinNT readers and a single
8831 ** WinNT reader will lock out all other Win95 readers.
8833 ** The following #defines specify the range of bytes used for locking.
8834 ** SHARED_SIZE is the number of bytes available in the pool from which
8835 ** a random byte is selected for a shared lock. The pool of bytes for
8836 ** shared locks begins at SHARED_FIRST.
8838 ** The same locking strategy and
8839 ** byte ranges are used for Unix. This leaves open the possiblity of having
8840 ** clients on win95, winNT, and unix all talking to the same shared file
8841 ** and all locking correctly. To do so would require that samba (or whatever
8842 ** tool is being used for file sharing) implements locks correctly between
8843 ** windows and unix. I'm guessing that isn't likely to happen, but by
8844 ** using the same locking range we are at least open to the possibility.
8846 ** Locking in windows is manditory. For this reason, we cannot store
8847 ** actual data in the bytes used for locking. The pager never allocates
8848 ** the pages involved in locking therefore. SHARED_SIZE is selected so
8849 ** that all locks will fit on a single page even at the minimum page size.
8850 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
8851 ** is set high so that we don't have to allocate an unused page except
8852 ** for very large databases. But one should test the page skipping logic
8853 ** by setting PENDING_BYTE low and running the entire regression suite.
8855 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8856 ** file format. Depending on how it is changed, you might not notice
8857 ** the incompatibility right away, even running a full regression test.
8858 ** The default location of PENDING_BYTE is the first byte past the
8859 ** 1GB boundary.
8862 #ifdef SQLITE_OMIT_WSD
8863 # define PENDING_BYTE (0x40000000)
8864 #else
8865 # define PENDING_BYTE sqlite3PendingByte
8866 #endif
8867 #define RESERVED_BYTE (PENDING_BYTE+1)
8868 #define SHARED_FIRST (PENDING_BYTE+2)
8869 #define SHARED_SIZE 510
8872 ** Wrapper around OS specific sqlite3_os_init() function.
8874 SQLITE_PRIVATE int sqlite3OsInit(void);
8877 ** Functions for accessing sqlite3_file methods
8879 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8880 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8881 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8882 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8883 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8884 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8885 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8886 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8887 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8888 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8889 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8890 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8891 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8892 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8893 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8894 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8895 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8898 ** Functions for accessing sqlite3_vfs methods
8900 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8901 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8902 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8903 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8904 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8905 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8906 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8907 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8908 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8909 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8910 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8911 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8912 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8915 ** Convenience functions for opening and closing files using
8916 ** sqlite3_malloc() to obtain space for the file-handle structure.
8918 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8919 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8921 #endif /* _SQLITE_OS_H_ */
8923 /************** End of os.h **************************************************/
8924 /************** Continuing where we left off in sqliteInt.h ******************/
8925 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8926 /************** Begin file mutex.h *******************************************/
8928 ** 2007 August 28
8930 ** The author disclaims copyright to this source code. In place of
8931 ** a legal notice, here is a blessing:
8933 ** May you do good and not evil.
8934 ** May you find forgiveness for yourself and forgive others.
8935 ** May you share freely, never taking more than you give.
8937 *************************************************************************
8939 ** This file contains the common header for all mutex implementations.
8940 ** The sqliteInt.h header #includes this file so that it is available
8941 ** to all source files. We break it out in an effort to keep the code
8942 ** better organized.
8944 ** NOTE: source files should *not* #include this header file directly.
8945 ** Source files should #include the sqliteInt.h file and let that file
8946 ** include this one indirectly.
8951 ** Figure out what version of the code to use. The choices are
8953 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
8954 ** mutexes implemention cannot be overridden
8955 ** at start-time.
8957 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
8958 ** mutual exclusion is provided. But this
8959 ** implementation can be overridden at
8960 ** start-time.
8962 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
8964 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
8966 ** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2.
8968 #if !SQLITE_THREADSAFE
8969 # define SQLITE_MUTEX_OMIT
8970 #endif
8971 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8972 # if SQLITE_OS_UNIX
8973 # define SQLITE_MUTEX_PTHREADS
8974 # elif SQLITE_OS_WIN
8975 # define SQLITE_MUTEX_W32
8976 # elif SQLITE_OS_OS2
8977 # define SQLITE_MUTEX_OS2
8978 # else
8979 # define SQLITE_MUTEX_NOOP
8980 # endif
8981 #endif
8983 #ifdef SQLITE_MUTEX_OMIT
8985 ** If this is a no-op implementation, implement everything as macros.
8987 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
8988 #define sqlite3_mutex_free(X)
8989 #define sqlite3_mutex_enter(X)
8990 #define sqlite3_mutex_try(X) SQLITE_OK
8991 #define sqlite3_mutex_leave(X)
8992 #define sqlite3_mutex_held(X) ((void)(X),1)
8993 #define sqlite3_mutex_notheld(X) ((void)(X),1)
8994 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
8995 #define sqlite3MutexInit() SQLITE_OK
8996 #define sqlite3MutexEnd()
8997 #endif /* defined(SQLITE_MUTEX_OMIT) */
8999 /************** End of mutex.h ***********************************************/
9000 /************** Continuing where we left off in sqliteInt.h ******************/
9004 ** Each database file to be accessed by the system is an instance
9005 ** of the following structure. There are normally two of these structures
9006 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
9007 ** aDb[1] is the database file used to hold temporary tables. Additional
9008 ** databases may be attached.
9010 struct Db {
9011 char *zName; /* Name of this database */
9012 Btree *pBt; /* The B*Tree structure for this database file */
9013 u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
9014 u8 safety_level; /* How aggressive at syncing data to disk */
9015 Schema *pSchema; /* Pointer to database schema (possibly shared) */
9019 ** An instance of the following structure stores a database schema.
9021 ** Most Schema objects are associated with a Btree. The exception is
9022 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9023 ** In shared cache mode, a single Schema object can be shared by multiple
9024 ** Btrees that refer to the same underlying BtShared object.
9026 ** Schema objects are automatically deallocated when the last Btree that
9027 ** references them is destroyed. The TEMP Schema is manually freed by
9028 ** sqlite3_close().
9030 ** A thread must be holding a mutex on the corresponding Btree in order
9031 ** to access Schema content. This implies that the thread must also be
9032 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9033 ** For a TEMP Schema, on the connection mutex is required.
9035 struct Schema {
9036 int schema_cookie; /* Database schema version number for this file */
9037 int iGeneration; /* Generation counter. Incremented with each change */
9038 Hash tblHash; /* All tables indexed by name */
9039 Hash idxHash; /* All (named) indices indexed by name */
9040 Hash trigHash; /* All triggers indexed by name */
9041 Hash fkeyHash; /* All foreign keys by referenced table name */
9042 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
9043 u8 file_format; /* Schema format version for this file */
9044 u8 enc; /* Text encoding used by this database */
9045 u16 flags; /* Flags associated with this schema */
9046 int cache_size; /* Number of pages to use in the cache */
9050 ** These macros can be used to test, set, or clear bits in the
9051 ** Db.pSchema->flags field.
9053 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
9054 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
9055 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
9056 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
9059 ** Allowed values for the DB.pSchema->flags field.
9061 ** The DB_SchemaLoaded flag is set after the database schema has been
9062 ** read into internal hash tables.
9064 ** DB_UnresetViews means that one or more views have column names that
9065 ** have been filled out. If the schema changes, these column names might
9066 ** changes and so the view will need to be reset.
9068 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
9069 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
9070 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
9073 ** The number of different kinds of things that can be limited
9074 ** using the sqlite3_limit() interface.
9076 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9079 ** Lookaside malloc is a set of fixed-size buffers that can be used
9080 ** to satisfy small transient memory allocation requests for objects
9081 ** associated with a particular database connection. The use of
9082 ** lookaside malloc provides a significant performance enhancement
9083 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9084 ** SQL statements.
9086 ** The Lookaside structure holds configuration information about the
9087 ** lookaside malloc subsystem. Each available memory allocation in
9088 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9089 ** objects.
9091 ** Lookaside allocations are only allowed for objects that are associated
9092 ** with a particular database connection. Hence, schema information cannot
9093 ** be stored in lookaside because in shared cache mode the schema information
9094 ** is shared by multiple database connections. Therefore, while parsing
9095 ** schema information, the Lookaside.bEnabled flag is cleared so that
9096 ** lookaside allocations are not used to construct the schema objects.
9098 struct Lookaside {
9099 u16 sz; /* Size of each buffer in bytes */
9100 u8 bEnabled; /* False to disable new lookaside allocations */
9101 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
9102 int nOut; /* Number of buffers currently checked out */
9103 int mxOut; /* Highwater mark for nOut */
9104 int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
9105 LookasideSlot *pFree; /* List of available buffers */
9106 void *pStart; /* First byte of available memory space */
9107 void *pEnd; /* First byte past end of available space */
9109 struct LookasideSlot {
9110 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
9114 ** A hash table for function definitions.
9116 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9117 ** Collisions are on the FuncDef.pHash chain.
9119 struct FuncDefHash {
9120 FuncDef *a[23]; /* Hash table for functions */
9124 ** Each database connection is an instance of the following structure.
9126 ** The sqlite.lastRowid records the last insert rowid generated by an
9127 ** insert statement. Inserts on views do not affect its value. Each
9128 ** trigger has its own context, so that lastRowid can be updated inside
9129 ** triggers as usual. The previous value will be restored once the trigger
9130 ** exits. Upon entering a before or instead of trigger, lastRowid is no
9131 ** longer (since after version 2.8.12) reset to -1.
9133 ** The sqlite.nChange does not count changes within triggers and keeps no
9134 ** context. It is reset at start of sqlite3_exec.
9135 ** The sqlite.lsChange represents the number of changes made by the last
9136 ** insert, update, or delete statement. It remains constant throughout the
9137 ** length of a statement and is then updated by OP_SetCounts. It keeps a
9138 ** context stack just like lastRowid so that the count of changes
9139 ** within a trigger is not seen outside the trigger. Changes to views do not
9140 ** affect the value of lsChange.
9141 ** The sqlite.csChange keeps track of the number of current changes (since
9142 ** the last statement) and is used to update sqlite_lsChange.
9144 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
9145 ** store the most recent error code and, if applicable, string. The
9146 ** internal function sqlite3Error() is used to set these variables
9147 ** consistently.
9149 struct sqlite3 {
9150 sqlite3_vfs *pVfs; /* OS Interface */
9151 int nDb; /* Number of backends currently in use */
9152 Db *aDb; /* All backends */
9153 int flags; /* Miscellaneous flags. See below */
9154 int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
9155 int errCode; /* Most recent error code (SQLITE_*) */
9156 int errMask; /* & result codes with this before returning */
9157 u8 autoCommit; /* The auto-commit flag. */
9158 u8 temp_store; /* 1: file 2: memory 0: default */
9159 u8 mallocFailed; /* True if we have seen a malloc failure */
9160 u8 dfltLockMode; /* Default locking-mode for attached dbs */
9161 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
9162 u8 suppressErr; /* Do not issue error messages if true */
9163 int nextPagesize; /* Pagesize after VACUUM if >0 */
9164 int nTable; /* Number of tables in the database */
9165 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
9166 i64 lastRowid; /* ROWID of most recent insert (see above) */
9167 u32 magic; /* Magic number for detect library misuse */
9168 int nChange; /* Value returned by sqlite3_changes() */
9169 int nTotalChange; /* Value returned by sqlite3_total_changes() */
9170 sqlite3_mutex *mutex; /* Connection mutex */
9171 int aLimit[SQLITE_N_LIMIT]; /* Limits */
9172 struct sqlite3InitInfo { /* Information used during initialization */
9173 int iDb; /* When back is being initialized */
9174 int newTnum; /* Rootpage of table being initialized */
9175 u8 busy; /* TRUE if currently initializing */
9176 u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
9177 } init;
9178 int nExtension; /* Number of loaded extensions */
9179 void **aExtension; /* Array of shared library handles */
9180 struct Vdbe *pVdbe; /* List of active virtual machines */
9181 int activeVdbeCnt; /* Number of VDBEs currently executing */
9182 int writeVdbeCnt; /* Number of active VDBEs that are writing */
9183 int vdbeExecCnt; /* Number of nested calls to VdbeExec() */
9184 void (*xTrace)(void*,const char*); /* Trace function */
9185 void *pTraceArg; /* Argument to the trace function */
9186 void (*xProfile)(void*,const char*,u64); /* Profiling function */
9187 void *pProfileArg; /* Argument to profile function */
9188 void *pCommitArg; /* Argument to xCommitCallback() */
9189 int (*xCommitCallback)(void*); /* Invoked at every commit. */
9190 void *pRollbackArg; /* Argument to xRollbackCallback() */
9191 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9192 void *pUpdateArg;
9193 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9194 #ifndef SQLITE_OMIT_WAL
9195 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9196 void *pWalArg;
9197 #endif
9198 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9199 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9200 void *pCollNeededArg;
9201 sqlite3_value *pErr; /* Most recent error message */
9202 char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
9203 char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
9204 union {
9205 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9206 double notUsed1; /* Spacer */
9207 } u1;
9208 Lookaside lookaside; /* Lookaside malloc configuration */
9209 #ifndef SQLITE_OMIT_AUTHORIZATION
9210 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9211 /* Access authorization function */
9212 void *pAuthArg; /* 1st argument to the access auth function */
9213 #endif
9214 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9215 int (*xProgress)(void *); /* The progress callback */
9216 void *pProgressArg; /* Argument to the progress callback */
9217 int nProgressOps; /* Number of opcodes for progress callback */
9218 #endif
9219 #ifndef SQLITE_OMIT_VIRTUALTABLE
9220 Hash aModule; /* populated by sqlite3_create_module() */
9221 Table *pVTab; /* vtab with active Connect/Create method */
9222 VTable **aVTrans; /* Virtual tables with open transactions */
9223 int nVTrans; /* Allocated size of aVTrans */
9224 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
9225 #endif
9226 FuncDefHash aFunc; /* Hash table of connection functions */
9227 Hash aCollSeq; /* All collating sequences */
9228 BusyHandler busyHandler; /* Busy callback */
9229 int busyTimeout; /* Busy handler timeout, in msec */
9230 Db aDbStatic[2]; /* Static space for the 2 default backends */
9231 Savepoint *pSavepoint; /* List of active savepoints */
9232 int nSavepoint; /* Number of non-transaction savepoints */
9233 int nStatement; /* Number of nested statement-transactions */
9234 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
9235 i64 nDeferredCons; /* Net deferred constraints this transaction. */
9236 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
9238 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9239 /* The following variables are all protected by the STATIC_MASTER
9240 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
9242 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9243 ** unlock so that it can proceed.
9245 ** When X.pBlockingConnection==Y, that means that something that X tried
9246 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9247 ** held by Y.
9249 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9250 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
9251 void *pUnlockArg; /* Argument to xUnlockNotify */
9252 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
9253 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
9254 #endif
9258 ** A macro to discover the encoding of a database.
9260 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9263 ** Possible values for the sqlite3.flags.
9265 #define SQLITE_VdbeTrace 0x00000100 /* True to trace VDBE execution */
9266 #define SQLITE_InternChanges 0x00000200 /* Uncommitted Hash table changes */
9267 #define SQLITE_FullColNames 0x00000400 /* Show full column names on SELECT */
9268 #define SQLITE_ShortColNames 0x00000800 /* Show short columns names */
9269 #define SQLITE_CountRows 0x00001000 /* Count rows changed by INSERT, */
9270 /* DELETE, or UPDATE and return */
9271 /* the count using a callback. */
9272 #define SQLITE_NullCallback 0x00002000 /* Invoke the callback once if the */
9273 /* result set is empty */
9274 #define SQLITE_SqlTrace 0x00004000 /* Debug print SQL as it executes */
9275 #define SQLITE_VdbeListing 0x00008000 /* Debug listings of VDBE programs */
9276 #define SQLITE_WriteSchema 0x00010000 /* OK to update SQLITE_MASTER */
9277 #define SQLITE_NoReadlock 0x00020000 /* Readlocks are omitted when
9278 ** accessing read-only databases */
9279 #define SQLITE_IgnoreChecks 0x00040000 /* Do not enforce check constraints */
9280 #define SQLITE_ReadUncommitted 0x0080000 /* For shared-cache mode */
9281 #define SQLITE_LegacyFileFmt 0x00100000 /* Create new databases in format 1 */
9282 #define SQLITE_FullFSync 0x00200000 /* Use full fsync on the backend */
9283 #define SQLITE_CkptFullFSync 0x00400000 /* Use full fsync for checkpoint */
9284 #define SQLITE_RecoveryMode 0x00800000 /* Ignore schema errors */
9285 #define SQLITE_ReverseOrder 0x01000000 /* Reverse unordered SELECTs */
9286 #define SQLITE_RecTriggers 0x02000000 /* Enable recursive triggers */
9287 #define SQLITE_ForeignKeys 0x04000000 /* Enforce foreign key constraints */
9288 #define SQLITE_AutoIndex 0x08000000 /* Enable automatic indexes */
9289 #define SQLITE_PreferBuiltin 0x10000000 /* Preference to built-in funcs */
9290 #define SQLITE_LoadExtension 0x20000000 /* Enable load_extension */
9291 #define SQLITE_EnableTrigger 0x40000000 /* True to enable triggers */
9294 ** Bits of the sqlite3.flags field that are used by the
9295 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9296 ** These must be the low-order bits of the flags field.
9298 #define SQLITE_QueryFlattener 0x01 /* Disable query flattening */
9299 #define SQLITE_ColumnCache 0x02 /* Disable the column cache */
9300 #define SQLITE_IndexSort 0x04 /* Disable indexes for sorting */
9301 #define SQLITE_IndexSearch 0x08 /* Disable indexes for searching */
9302 #define SQLITE_IndexCover 0x10 /* Disable index covering table */
9303 #define SQLITE_GroupByOrder 0x20 /* Disable GROUPBY cover of ORDERBY */
9304 #define SQLITE_FactorOutConst 0x40 /* Disable factoring out constants */
9305 #define SQLITE_OptMask 0xff /* Mask of all disablable opts */
9308 ** Possible values for the sqlite.magic field.
9309 ** The numbers are obtained at random and have no special meaning, other
9310 ** than being distinct from one another.
9312 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
9313 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
9314 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
9315 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
9316 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
9319 ** Each SQL function is defined by an instance of the following
9320 ** structure. A pointer to this structure is stored in the sqlite.aFunc
9321 ** hash table. When multiple functions have the same name, the hash table
9322 ** points to a linked list of these structures.
9324 struct FuncDef {
9325 i16 nArg; /* Number of arguments. -1 means unlimited */
9326 u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9327 u8 flags; /* Some combination of SQLITE_FUNC_* */
9328 void *pUserData; /* User data parameter */
9329 FuncDef *pNext; /* Next function with same name */
9330 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9331 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9332 void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
9333 char *zName; /* SQL name of the function. */
9334 FuncDef *pHash; /* Next with a different name but the same hash */
9335 FuncDestructor *pDestructor; /* Reference counted destructor function */
9339 ** This structure encapsulates a user-function destructor callback (as
9340 ** configured using create_function_v2()) and a reference counter. When
9341 ** create_function_v2() is called to create a function with a destructor,
9342 ** a single object of this type is allocated. FuncDestructor.nRef is set to
9343 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9344 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9345 ** member of each of the new FuncDef objects is set to point to the allocated
9346 ** FuncDestructor.
9348 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9349 ** count on this object is decremented. When it reaches 0, the destructor
9350 ** is invoked and the FuncDestructor structure freed.
9352 struct FuncDestructor {
9353 int nRef;
9354 void (*xDestroy)(void *);
9355 void *pUserData;
9359 ** Possible values for FuncDef.flags
9361 #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
9362 #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
9363 #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
9364 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9365 #define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */
9366 #define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */
9367 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9370 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9371 ** used to create the initializers for the FuncDef structures.
9373 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
9374 ** Used to create a scalar function definition of a function zName
9375 ** implemented by C function xFunc that accepts nArg arguments. The
9376 ** value passed as iArg is cast to a (void*) and made available
9377 ** as the user-data (sqlite3_user_data()) for the function. If
9378 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9380 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9381 ** Used to create an aggregate function definition implemented by
9382 ** the C functions xStep and xFinal. The first four parameters
9383 ** are interpreted in the same way as the first 4 parameters to
9384 ** FUNCTION().
9386 ** LIKEFUNC(zName, nArg, pArg, flags)
9387 ** Used to create a scalar function definition of a function zName
9388 ** that accepts nArg arguments and is implemented by a call to C
9389 ** function likeFunc. Argument pArg is cast to a (void *) and made
9390 ** available as the function user-data (sqlite3_user_data()). The
9391 ** FuncDef.flags variable is set to the value passed as the flags
9392 ** parameter.
9394 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9395 {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9396 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9397 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9398 {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9399 pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9400 #define LIKEFUNC(zName, nArg, arg, flags) \
9401 {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9402 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9403 {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9404 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9407 ** All current savepoints are stored in a linked list starting at
9408 ** sqlite3.pSavepoint. The first element in the list is the most recently
9409 ** opened savepoint. Savepoints are added to the list by the vdbe
9410 ** OP_Savepoint instruction.
9412 struct Savepoint {
9413 char *zName; /* Savepoint name (nul-terminated) */
9414 i64 nDeferredCons; /* Number of deferred fk violations */
9415 Savepoint *pNext; /* Parent savepoint (if any) */
9419 ** The following are used as the second parameter to sqlite3Savepoint(),
9420 ** and as the P1 argument to the OP_Savepoint instruction.
9422 #define SAVEPOINT_BEGIN 0
9423 #define SAVEPOINT_RELEASE 1
9424 #define SAVEPOINT_ROLLBACK 2
9428 ** Each SQLite module (virtual table definition) is defined by an
9429 ** instance of the following structure, stored in the sqlite3.aModule
9430 ** hash table.
9432 struct Module {
9433 const sqlite3_module *pModule; /* Callback pointers */
9434 const char *zName; /* Name passed to create_module() */
9435 void *pAux; /* pAux passed to create_module() */
9436 void (*xDestroy)(void *); /* Module destructor function */
9440 ** information about each column of an SQL table is held in an instance
9441 ** of this structure.
9443 struct Column {
9444 char *zName; /* Name of this column */
9445 Expr *pDflt; /* Default value of this column */
9446 char *zDflt; /* Original text of the default value */
9447 char *zType; /* Data type for this column */
9448 char *zColl; /* Collating sequence. If NULL, use the default */
9449 u8 notNull; /* True if there is a NOT NULL constraint */
9450 u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
9451 char affinity; /* One of the SQLITE_AFF_... values */
9452 #ifndef SQLITE_OMIT_VIRTUALTABLE
9453 u8 isHidden; /* True if this column is 'hidden' */
9454 #endif
9458 ** A "Collating Sequence" is defined by an instance of the following
9459 ** structure. Conceptually, a collating sequence consists of a name and
9460 ** a comparison routine that defines the order of that sequence.
9462 ** There may two separate implementations of the collation function, one
9463 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9464 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9465 ** native byte order. When a collation sequence is invoked, SQLite selects
9466 ** the version that will require the least expensive encoding
9467 ** translations, if any.
9469 ** The CollSeq.pUser member variable is an extra parameter that passed in
9470 ** as the first argument to the UTF-8 comparison function, xCmp.
9471 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9472 ** xCmp16.
9474 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9475 ** collating sequence is undefined. Indices built on an undefined
9476 ** collating sequence may not be read or written.
9478 struct CollSeq {
9479 char *zName; /* Name of the collating sequence, UTF-8 encoded */
9480 u8 enc; /* Text encoding handled by xCmp() */
9481 u8 type; /* One of the SQLITE_COLL_... values below */
9482 void *pUser; /* First argument to xCmp() */
9483 int (*xCmp)(void*,int, const void*, int, const void*);
9484 void (*xDel)(void*); /* Destructor for pUser */
9488 ** Allowed values of CollSeq.type:
9490 #define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */
9491 #define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */
9492 #define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */
9493 #define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */
9496 ** A sort order can be either ASC or DESC.
9498 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
9499 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
9502 ** Column affinity types.
9504 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9505 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
9506 ** the speed a little by numbering the values consecutively.
9508 ** But rather than start with 0 or 1, we begin with 'a'. That way,
9509 ** when multiple affinity types are concatenated into a string and
9510 ** used as the P4 operand, they will be more readable.
9512 ** Note also that the numeric types are grouped together so that testing
9513 ** for a numeric type is a single comparison.
9515 #define SQLITE_AFF_TEXT 'a'
9516 #define SQLITE_AFF_NONE 'b'
9517 #define SQLITE_AFF_NUMERIC 'c'
9518 #define SQLITE_AFF_INTEGER 'd'
9519 #define SQLITE_AFF_REAL 'e'
9521 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
9524 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9525 ** affinity value.
9527 #define SQLITE_AFF_MASK 0x67
9530 ** Additional bit values that can be ORed with an affinity without
9531 ** changing the affinity.
9533 #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
9534 #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
9535 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
9538 ** An object of this type is created for each virtual table present in
9539 ** the database schema.
9541 ** If the database schema is shared, then there is one instance of this
9542 ** structure for each database connection (sqlite3*) that uses the shared
9543 ** schema. This is because each database connection requires its own unique
9544 ** instance of the sqlite3_vtab* handle used to access the virtual table
9545 ** implementation. sqlite3_vtab* handles can not be shared between
9546 ** database connections, even when the rest of the in-memory database
9547 ** schema is shared, as the implementation often stores the database
9548 ** connection handle passed to it via the xConnect() or xCreate() method
9549 ** during initialization internally. This database connection handle may
9550 ** then be used by the virtual table implementation to access real tables
9551 ** within the database. So that they appear as part of the callers
9552 ** transaction, these accesses need to be made via the same database
9553 ** connection as that used to execute SQL operations on the virtual table.
9555 ** All VTable objects that correspond to a single table in a shared
9556 ** database schema are initially stored in a linked-list pointed to by
9557 ** the Table.pVTable member variable of the corresponding Table object.
9558 ** When an sqlite3_prepare() operation is required to access the virtual
9559 ** table, it searches the list for the VTable that corresponds to the
9560 ** database connection doing the preparing so as to use the correct
9561 ** sqlite3_vtab* handle in the compiled query.
9563 ** When an in-memory Table object is deleted (for example when the
9564 ** schema is being reloaded for some reason), the VTable objects are not
9565 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
9566 ** immediately. Instead, they are moved from the Table.pVTable list to
9567 ** another linked list headed by the sqlite3.pDisconnect member of the
9568 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
9569 ** next time a statement is prepared using said sqlite3*. This is done
9570 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9571 ** Refer to comments above function sqlite3VtabUnlockList() for an
9572 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9573 ** list without holding the corresponding sqlite3.mutex mutex.
9575 ** The memory for objects of this type is always allocated by
9576 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
9577 ** the first argument.
9579 struct VTable {
9580 sqlite3 *db; /* Database connection associated with this table */
9581 Module *pMod; /* Pointer to module implementation */
9582 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
9583 int nRef; /* Number of pointers to this structure */
9584 VTable *pNext; /* Next in linked list (see above) */
9588 ** Each SQL table is represented in memory by an instance of the
9589 ** following structure.
9591 ** Table.zName is the name of the table. The case of the original
9592 ** CREATE TABLE statement is stored, but case is not significant for
9593 ** comparisons.
9595 ** Table.nCol is the number of columns in this table. Table.aCol is a
9596 ** pointer to an array of Column structures, one for each column.
9598 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9599 ** the column that is that key. Otherwise Table.iPKey is negative. Note
9600 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9601 ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
9602 ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
9603 ** is generated for each row of the table. TF_HasPrimaryKey is set if
9604 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9606 ** Table.tnum is the page number for the root BTree page of the table in the
9607 ** database file. If Table.iDb is the index of the database table backend
9608 ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
9609 ** holds temporary tables and indices. If TF_Ephemeral is set
9610 ** then the table is stored in a file that is automatically deleted
9611 ** when the VDBE cursor to the table is closed. In this case Table.tnum
9612 ** refers VDBE cursor number that holds the table open, not to the root
9613 ** page number. Transient tables are used to hold the results of a
9614 ** sub-query that appears instead of a real table name in the FROM clause
9615 ** of a SELECT statement.
9617 struct Table {
9618 char *zName; /* Name of the table or view */
9619 int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
9620 int nCol; /* Number of columns in this table */
9621 Column *aCol; /* Information about each column */
9622 Index *pIndex; /* List of SQL indexes on this table. */
9623 int tnum; /* Root BTree node for this table (see note above) */
9624 unsigned nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
9625 Select *pSelect; /* NULL for tables. Points to definition if a view. */
9626 u16 nRef; /* Number of pointers to this Table */
9627 u8 tabFlags; /* Mask of TF_* values */
9628 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
9629 FKey *pFKey; /* Linked list of all foreign keys in this table */
9630 char *zColAff; /* String defining the affinity of each column */
9631 #ifndef SQLITE_OMIT_CHECK
9632 Expr *pCheck; /* The AND of all CHECK constraints */
9633 #endif
9634 #ifndef SQLITE_OMIT_ALTERTABLE
9635 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
9636 #endif
9637 #ifndef SQLITE_OMIT_VIRTUALTABLE
9638 VTable *pVTable; /* List of VTable objects. */
9639 int nModuleArg; /* Number of arguments to the module */
9640 char **azModuleArg; /* Text of all module args. [0] is module name */
9641 #endif
9642 Trigger *pTrigger; /* List of triggers stored in pSchema */
9643 Schema *pSchema; /* Schema that contains this table */
9644 Table *pNextZombie; /* Next on the Parse.pZombieTab list */
9648 ** Allowed values for Tabe.tabFlags.
9650 #define TF_Readonly 0x01 /* Read-only system table */
9651 #define TF_Ephemeral 0x02 /* An ephemeral table */
9652 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
9653 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
9654 #define TF_Virtual 0x10 /* Is a virtual table */
9655 #define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */
9660 ** Test to see whether or not a table is a virtual table. This is
9661 ** done as a macro so that it will be optimized out when virtual
9662 ** table support is omitted from the build.
9664 #ifndef SQLITE_OMIT_VIRTUALTABLE
9665 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
9666 # define IsHiddenColumn(X) ((X)->isHidden)
9667 #else
9668 # define IsVirtual(X) 0
9669 # define IsHiddenColumn(X) 0
9670 #endif
9673 ** Each foreign key constraint is an instance of the following structure.
9675 ** A foreign key is associated with two tables. The "from" table is
9676 ** the table that contains the REFERENCES clause that creates the foreign
9677 ** key. The "to" table is the table that is named in the REFERENCES clause.
9678 ** Consider this example:
9680 ** CREATE TABLE ex1(
9681 ** a INTEGER PRIMARY KEY,
9682 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9683 ** );
9685 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9687 ** Each REFERENCES clause generates an instance of the following structure
9688 ** which is attached to the from-table. The to-table need not exist when
9689 ** the from-table is created. The existence of the to-table is not checked.
9691 struct FKey {
9692 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
9693 FKey *pNextFrom; /* Next foreign key in pFrom */
9694 char *zTo; /* Name of table that the key points to (aka: Parent) */
9695 FKey *pNextTo; /* Next foreign key on table named zTo */
9696 FKey *pPrevTo; /* Previous foreign key on table named zTo */
9697 int nCol; /* Number of columns in this key */
9698 /* EV: R-30323-21917 */
9699 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
9700 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
9701 Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
9702 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
9703 int iFrom; /* Index of column in pFrom */
9704 char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
9705 } aCol[1]; /* One entry for each of nCol column s */
9709 ** SQLite supports many different ways to resolve a constraint
9710 ** error. ROLLBACK processing means that a constraint violation
9711 ** causes the operation in process to fail and for the current transaction
9712 ** to be rolled back. ABORT processing means the operation in process
9713 ** fails and any prior changes from that one operation are backed out,
9714 ** but the transaction is not rolled back. FAIL processing means that
9715 ** the operation in progress stops and returns an error code. But prior
9716 ** changes due to the same operation are not backed out and no rollback
9717 ** occurs. IGNORE means that the particular row that caused the constraint
9718 ** error is not inserted or updated. Processing continues and no error
9719 ** is returned. REPLACE means that preexisting database rows that caused
9720 ** a UNIQUE constraint violation are removed so that the new insert or
9721 ** update can proceed. Processing continues and no error is reported.
9723 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9724 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9725 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
9726 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
9727 ** referenced table row is propagated into the row that holds the
9728 ** foreign key.
9730 ** The following symbolic values are used to record which type
9731 ** of action to take.
9733 #define OE_None 0 /* There is no constraint to check */
9734 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
9735 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
9736 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
9737 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
9738 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
9740 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9741 #define OE_SetNull 7 /* Set the foreign key value to NULL */
9742 #define OE_SetDflt 8 /* Set the foreign key value to its default */
9743 #define OE_Cascade 9 /* Cascade the changes */
9745 #define OE_Default 99 /* Do whatever the default action is */
9749 ** An instance of the following structure is passed as the first
9750 ** argument to sqlite3VdbeKeyCompare and is used to control the
9751 ** comparison of the two index keys.
9753 struct KeyInfo {
9754 sqlite3 *db; /* The database connection */
9755 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
9756 u16 nField; /* Number of entries in aColl[] */
9757 u8 *aSortOrder; /* Sort order for each column. May be NULL */
9758 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
9762 ** An instance of the following structure holds information about a
9763 ** single index record that has already been parsed out into individual
9764 ** values.
9766 ** A record is an object that contains one or more fields of data.
9767 ** Records are used to store the content of a table row and to store
9768 ** the key of an index. A blob encoding of a record is created by
9769 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9770 ** OP_Column opcode.
9772 ** This structure holds a record that has already been disassembled
9773 ** into its constituent fields.
9775 struct UnpackedRecord {
9776 KeyInfo *pKeyInfo; /* Collation and sort-order information */
9777 u16 nField; /* Number of entries in apMem[] */
9778 u16 flags; /* Boolean settings. UNPACKED_... below */
9779 i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
9780 Mem *aMem; /* Values */
9784 ** Allowed values of UnpackedRecord.flags
9786 #define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */
9787 #define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */
9788 #define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */
9789 #define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */
9790 #define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */
9791 #define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */
9794 ** Each SQL index is represented in memory by an
9795 ** instance of the following structure.
9797 ** The columns of the table that are to be indexed are described
9798 ** by the aiColumn[] field of this structure. For example, suppose
9799 ** we have the following table and index:
9801 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9802 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
9804 ** In the Table structure describing Ex1, nCol==3 because there are
9805 ** three columns in the table. In the Index structure describing
9806 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9807 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
9808 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9809 ** The second column to be indexed (c1) has an index of 0 in
9810 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9812 ** The Index.onError field determines whether or not the indexed columns
9813 ** must be unique and what to do if they are not. When Index.onError=OE_None,
9814 ** it means this is not a unique index. Otherwise it is a unique index
9815 ** and the value of Index.onError indicate the which conflict resolution
9816 ** algorithm to employ whenever an attempt is made to insert a non-unique
9817 ** element.
9819 struct Index {
9820 char *zName; /* Name of this index */
9821 int nColumn; /* Number of columns in the table used by this index */
9822 int *aiColumn; /* Which columns are used by this index. 1st is 0 */
9823 unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9824 Table *pTable; /* The SQL table being indexed */
9825 int tnum; /* Page containing root of this index in database file */
9826 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9827 u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
9828 u8 bUnordered; /* Use this index for == or IN queries only */
9829 char *zColAff; /* String defining the affinity of each column */
9830 Index *pNext; /* The next index associated with the same table */
9831 Schema *pSchema; /* Schema containing this index */
9832 u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
9833 char **azColl; /* Array of collation sequence names for index */
9834 IndexSample *aSample; /* Array of SQLITE_INDEX_SAMPLES samples */
9838 ** Each sample stored in the sqlite_stat2 table is represented in memory
9839 ** using a structure of this type.
9841 struct IndexSample {
9842 union {
9843 char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9844 double r; /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9845 } u;
9846 u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9847 u8 nByte; /* Size in byte of text or blob. */
9851 ** Each token coming out of the lexer is an instance of
9852 ** this structure. Tokens are also used as part of an expression.
9854 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9855 ** may contain random values. Do not make any assumptions about Token.dyn
9856 ** and Token.n when Token.z==0.
9858 struct Token {
9859 const char *z; /* Text of the token. Not NULL-terminated! */
9860 unsigned int n; /* Number of characters in this token */
9864 ** An instance of this structure contains information needed to generate
9865 ** code for a SELECT that contains aggregate functions.
9867 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9868 ** pointer to this structure. The Expr.iColumn field is the index in
9869 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9870 ** code for that node.
9872 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9873 ** original Select structure that describes the SELECT statement. These
9874 ** fields do not need to be freed when deallocating the AggInfo structure.
9876 struct AggInfo {
9877 u8 directMode; /* Direct rendering mode means take data directly
9878 ** from source tables rather than from accumulators */
9879 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
9880 ** than the source table */
9881 int sortingIdx; /* Cursor number of the sorting index */
9882 ExprList *pGroupBy; /* The group by clause */
9883 int nSortingColumn; /* Number of columns in the sorting index */
9884 struct AggInfo_col { /* For each column used in source tables */
9885 Table *pTab; /* Source table */
9886 int iTable; /* Cursor number of the source table */
9887 int iColumn; /* Column number within the source table */
9888 int iSorterColumn; /* Column number in the sorting index */
9889 int iMem; /* Memory location that acts as accumulator */
9890 Expr *pExpr; /* The original expression */
9891 } *aCol;
9892 int nColumn; /* Number of used entries in aCol[] */
9893 int nColumnAlloc; /* Number of slots allocated for aCol[] */
9894 int nAccumulator; /* Number of columns that show through to the output.
9895 ** Additional columns are used only as parameters to
9896 ** aggregate functions */
9897 struct AggInfo_func { /* For each aggregate function */
9898 Expr *pExpr; /* Expression encoding the function */
9899 FuncDef *pFunc; /* The aggregate function implementation */
9900 int iMem; /* Memory location that acts as accumulator */
9901 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
9902 } *aFunc;
9903 int nFunc; /* Number of entries in aFunc[] */
9904 int nFuncAlloc; /* Number of slots allocated for aFunc[] */
9908 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9909 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
9910 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
9911 ** it uses less memory in the Expr object, which is a big memory user
9912 ** in systems with lots of prepared statements. And few applications
9913 ** need more than about 10 or 20 variables. But some extreme users want
9914 ** to have prepared statements with over 32767 variables, and for them
9915 ** the option is available (at compile-time).
9917 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
9918 typedef i16 ynVar;
9919 #else
9920 typedef int ynVar;
9921 #endif
9924 ** Each node of an expression in the parse tree is an instance
9925 ** of this structure.
9927 ** Expr.op is the opcode. The integer parser token codes are reused
9928 ** as opcodes here. For example, the parser defines TK_GE to be an integer
9929 ** code representing the ">=" operator. This same integer code is reused
9930 ** to represent the greater-than-or-equal-to operator in the expression
9931 ** tree.
9933 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
9934 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9935 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
9936 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9937 ** then Expr.token contains the name of the function.
9939 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9940 ** binary operator. Either or both may be NULL.
9942 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
9943 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9944 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9945 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9946 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
9947 ** valid.
9949 ** An expression of the form ID or ID.ID refers to a column in a table.
9950 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9951 ** the integer cursor number of a VDBE cursor pointing to that table and
9952 ** Expr.iColumn is the column number for the specific column. If the
9953 ** expression is used as a result in an aggregate SELECT, then the
9954 ** value is also stored in the Expr.iAgg column in the aggregate so that
9955 ** it can be accessed after all aggregates are computed.
9957 ** If the expression is an unbound variable marker (a question mark
9958 ** character '?' in the original SQL) then the Expr.iTable holds the index
9959 ** number for that variable.
9961 ** If the expression is a subquery then Expr.iColumn holds an integer
9962 ** register number containing the result of the subquery. If the
9963 ** subquery gives a constant result, then iTable is -1. If the subquery
9964 ** gives a different answer at different times during statement processing
9965 ** then iTable is the address of a subroutine that computes the subquery.
9967 ** If the Expr is of type OP_Column, and the table it is selecting from
9968 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9969 ** corresponding table definition.
9971 ** ALLOCATION NOTES:
9973 ** Expr objects can use a lot of memory space in database schema. To
9974 ** help reduce memory requirements, sometimes an Expr object will be
9975 ** truncated. And to reduce the number of memory allocations, sometimes
9976 ** two or more Expr objects will be stored in a single memory allocation,
9977 ** together with Expr.zToken strings.
9979 ** If the EP_Reduced and EP_TokenOnly flags are set when
9980 ** an Expr object is truncated. When EP_Reduced is set, then all
9981 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9982 ** are contained within the same memory allocation. Note, however, that
9983 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9984 ** allocated, regardless of whether or not EP_Reduced is set.
9986 struct Expr {
9987 u8 op; /* Operation performed by this node */
9988 char affinity; /* The affinity of the column or 0 if not a column */
9989 u16 flags; /* Various flags. EP_* See below */
9990 union {
9991 char *zToken; /* Token value. Zero terminated and dequoted */
9992 int iValue; /* Non-negative integer value if EP_IntValue */
9993 } u;
9995 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9996 ** space is allocated for the fields below this point. An attempt to
9997 ** access them will result in a segfault or malfunction.
9998 *********************************************************************/
10000 Expr *pLeft; /* Left subnode */
10001 Expr *pRight; /* Right subnode */
10002 union {
10003 ExprList *pList; /* Function arguments or in "<expr> IN (<expr-list)" */
10004 Select *pSelect; /* Used for sub-selects and "<expr> IN (<select>)" */
10005 } x;
10006 CollSeq *pColl; /* The collation type of the column or 0 */
10008 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10009 ** space is allocated for the fields below this point. An attempt to
10010 ** access them will result in a segfault or malfunction.
10011 *********************************************************************/
10013 int iTable; /* TK_COLUMN: cursor number of table holding column
10014 ** TK_REGISTER: register number
10015 ** TK_TRIGGER: 1 -> new, 0 -> old */
10016 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
10017 ** TK_VARIABLE: variable number (always >= 1). */
10018 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10019 i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
10020 u8 flags2; /* Second set of flags. EP2_... */
10021 u8 op2; /* If a TK_REGISTER, the original value of Expr.op */
10022 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10023 Table *pTab; /* Table for TK_COLUMN expressions. */
10024 #if SQLITE_MAX_EXPR_DEPTH>0
10025 int nHeight; /* Height of the tree headed by this node */
10026 #endif
10030 ** The following are the meanings of bits in the Expr.flags field.
10032 #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
10033 #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
10034 #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
10035 #define EP_Error 0x0008 /* Expression contains one or more errors */
10036 #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
10037 #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
10038 #define EP_DblQuoted 0x0040 /* token.z was originally in "..." */
10039 #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
10040 #define EP_ExpCollate 0x0100 /* Collating sequence specified explicitly */
10041 #define EP_FixedDest 0x0200 /* Result needed in a specific register */
10042 #define EP_IntValue 0x0400 /* Integer value contained in u.iValue */
10043 #define EP_xIsSelect 0x0800 /* x.pSelect is valid (otherwise x.pList is) */
10045 #define EP_Reduced 0x1000 /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10046 #define EP_TokenOnly 0x2000 /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10047 #define EP_Static 0x4000 /* Held in memory not obtained from malloc() */
10050 ** The following are the meanings of bits in the Expr.flags2 field.
10052 #define EP2_MallocedToken 0x0001 /* Need to sqlite3DbFree() Expr.zToken */
10053 #define EP2_Irreducible 0x0002 /* Cannot EXPRDUP_REDUCE this Expr */
10056 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10057 ** flag on an expression structure. This flag is used for VV&A only. The
10058 ** routine is implemented as a macro that only works when in debugging mode,
10059 ** so as not to burden production code.
10061 #ifdef SQLITE_DEBUG
10062 # define ExprSetIrreducible(X) (X)->flags2 |= EP2_Irreducible
10063 #else
10064 # define ExprSetIrreducible(X)
10065 #endif
10068 ** These macros can be used to test, set, or clear bits in the
10069 ** Expr.flags field.
10071 #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
10072 #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
10073 #define ExprSetProperty(E,P) (E)->flags|=(P)
10074 #define ExprClearProperty(E,P) (E)->flags&=~(P)
10077 ** Macros to determine the number of bytes required by a normal Expr
10078 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
10079 ** and an Expr struct with the EP_TokenOnly flag set.
10081 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
10082 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
10083 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
10086 ** Flags passed to the sqlite3ExprDup() function. See the header comment
10087 ** above sqlite3ExprDup() for details.
10089 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
10092 ** A list of expressions. Each expression may optionally have a
10093 ** name. An expr/name combination can be used in several ways, such
10094 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10095 ** list of "ID = expr" items in an UPDATE. A list of expressions can
10096 ** also be used as the argument to a function, in which case the a.zName
10097 ** field is not used.
10099 struct ExprList {
10100 int nExpr; /* Number of expressions on the list */
10101 int nAlloc; /* Number of entries allocated below */
10102 int iECursor; /* VDBE Cursor associated with this ExprList */
10103 struct ExprList_item {
10104 Expr *pExpr; /* The list of expressions */
10105 char *zName; /* Token associated with this expression */
10106 char *zSpan; /* Original text of the expression */
10107 u8 sortOrder; /* 1 for DESC or 0 for ASC */
10108 u8 done; /* A flag to indicate when processing is finished */
10109 u16 iCol; /* For ORDER BY, column number in result set */
10110 u16 iAlias; /* Index into Parse.aAlias[] for zName */
10111 } *a; /* One entry for each expression */
10115 ** An instance of this structure is used by the parser to record both
10116 ** the parse tree for an expression and the span of input text for an
10117 ** expression.
10119 struct ExprSpan {
10120 Expr *pExpr; /* The expression parse tree */
10121 const char *zStart; /* First character of input text */
10122 const char *zEnd; /* One character past the end of input text */
10126 ** An instance of this structure can hold a simple list of identifiers,
10127 ** such as the list "a,b,c" in the following statements:
10129 ** INSERT INTO t(a,b,c) VALUES ...;
10130 ** CREATE INDEX idx ON t(a,b,c);
10131 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10133 ** The IdList.a.idx field is used when the IdList represents the list of
10134 ** column names after a table name in an INSERT statement. In the statement
10136 ** INSERT INTO t(a,b,c) ...
10138 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10140 struct IdList {
10141 struct IdList_item {
10142 char *zName; /* Name of the identifier */
10143 int idx; /* Index in some Table.aCol[] of a column named zName */
10144 } *a;
10145 int nId; /* Number of identifiers on the list */
10146 int nAlloc; /* Number of entries allocated for a[] below */
10150 ** The bitmask datatype defined below is used for various optimizations.
10152 ** Changing this from a 64-bit to a 32-bit type limits the number of
10153 ** tables in a join to 32 instead of 64. But it also reduces the size
10154 ** of the library by 738 bytes on ix86.
10156 typedef u64 Bitmask;
10159 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
10161 #define BMS ((int)(sizeof(Bitmask)*8))
10164 ** The following structure describes the FROM clause of a SELECT statement.
10165 ** Each table or subquery in the FROM clause is a separate element of
10166 ** the SrcList.a[] array.
10168 ** With the addition of multiple database support, the following structure
10169 ** can also be used to describe a particular table such as the table that
10170 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
10171 ** such a table must be a simple name: ID. But in SQLite, the table can
10172 ** now be identified by a database name, a dot, then the table name: ID.ID.
10174 ** The jointype starts out showing the join type between the current table
10175 ** and the next table on the list. The parser builds the list this way.
10176 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10177 ** jointype expresses the join between the table and the previous table.
10179 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10180 ** contains more than 63 columns and the 64-th or later column is used.
10182 struct SrcList {
10183 i16 nSrc; /* Number of tables or subqueries in the FROM clause */
10184 i16 nAlloc; /* Number of entries allocated in a[] below */
10185 struct SrcList_item {
10186 char *zDatabase; /* Name of database holding this table */
10187 char *zName; /* Name of the table */
10188 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
10189 Table *pTab; /* An SQL table corresponding to zName */
10190 Select *pSelect; /* A SELECT statement used in place of a table name */
10191 u8 isPopulated; /* Temporary table associated with SELECT is populated */
10192 u8 jointype; /* Type of join between this able and the previous */
10193 u8 notIndexed; /* True if there is a NOT INDEXED clause */
10194 #ifndef SQLITE_OMIT_EXPLAIN
10195 u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
10196 #endif
10197 int iCursor; /* The VDBE cursor number used to access this table */
10198 Expr *pOn; /* The ON clause of a join */
10199 IdList *pUsing; /* The USING clause of a join */
10200 Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
10201 char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
10202 Index *pIndex; /* Index structure corresponding to zIndex, if any */
10203 } a[1]; /* One entry for each identifier on the list */
10207 ** Permitted values of the SrcList.a.jointype field
10209 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
10210 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
10211 #define JT_NATURAL 0x0004 /* True for a "natural" join */
10212 #define JT_LEFT 0x0008 /* Left outer join */
10213 #define JT_RIGHT 0x0010 /* Right outer join */
10214 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
10215 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
10219 ** A WherePlan object holds information that describes a lookup
10220 ** strategy.
10222 ** This object is intended to be opaque outside of the where.c module.
10223 ** It is included here only so that that compiler will know how big it
10224 ** is. None of the fields in this object should be used outside of
10225 ** the where.c module.
10227 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10228 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
10229 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
10230 ** case that more than one of these conditions is true.
10232 struct WherePlan {
10233 u32 wsFlags; /* WHERE_* flags that describe the strategy */
10234 u32 nEq; /* Number of == constraints */
10235 double nRow; /* Estimated number of rows (for EQP) */
10236 union {
10237 Index *pIdx; /* Index when WHERE_INDEXED is true */
10238 struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
10239 sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
10240 } u;
10244 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10245 ** structure contains a single instance of this structure. This structure
10246 ** is intended to be private the the where.c module and should not be
10247 ** access or modified by other modules.
10249 ** The pIdxInfo field is used to help pick the best index on a
10250 ** virtual table. The pIdxInfo pointer contains indexing
10251 ** information for the i-th table in the FROM clause before reordering.
10252 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10253 ** All other information in the i-th WhereLevel object for the i-th table
10254 ** after FROM clause ordering.
10256 struct WhereLevel {
10257 WherePlan plan; /* query plan for this element of the FROM clause */
10258 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
10259 int iTabCur; /* The VDBE cursor used to access the table */
10260 int iIdxCur; /* The VDBE cursor used to access pIdx */
10261 int addrBrk; /* Jump here to break out of the loop */
10262 int addrNxt; /* Jump here to start the next IN combination */
10263 int addrCont; /* Jump here to continue with the next loop cycle */
10264 int addrFirst; /* First instruction of interior of the loop */
10265 u8 iFrom; /* Which entry in the FROM clause */
10266 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
10267 int p1, p2; /* Operands of the opcode used to ends the loop */
10268 union { /* Information that depends on plan.wsFlags */
10269 struct {
10270 int nIn; /* Number of entries in aInLoop[] */
10271 struct InLoop {
10272 int iCur; /* The VDBE cursor used by this IN operator */
10273 int addrInTop; /* Top of the IN loop */
10274 } *aInLoop; /* Information about each nested IN operator */
10275 } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
10276 } u;
10278 /* The following field is really not part of the current level. But
10279 ** we need a place to cache virtual table index information for each
10280 ** virtual table in the FROM clause and the WhereLevel structure is
10281 ** a convenient place since there is one WhereLevel for each FROM clause
10282 ** element.
10284 sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
10288 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10289 ** and the WhereInfo.wctrlFlags member.
10291 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
10292 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
10293 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
10294 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
10295 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
10296 #define WHERE_OMIT_OPEN 0x0010 /* Table cursors are already open */
10297 #define WHERE_OMIT_CLOSE 0x0020 /* Omit close of table & index cursors */
10298 #define WHERE_FORCE_TABLE 0x0040 /* Do not use an index-only search */
10299 #define WHERE_ONETABLE_ONLY 0x0080 /* Only code the 1st table in pTabList */
10302 ** The WHERE clause processing routine has two halves. The
10303 ** first part does the start of the WHERE loop and the second
10304 ** half does the tail of the WHERE loop. An instance of
10305 ** this structure is returned by the first half and passed
10306 ** into the second half to give some continuity.
10308 struct WhereInfo {
10309 Parse *pParse; /* Parsing and code generating context */
10310 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
10311 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE or DELETE */
10312 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
10313 SrcList *pTabList; /* List of tables in the join */
10314 int iTop; /* The very beginning of the WHERE loop */
10315 int iContinue; /* Jump here to continue with next record */
10316 int iBreak; /* Jump here to break out of the loop */
10317 int nLevel; /* Number of nested loop */
10318 struct WhereClause *pWC; /* Decomposition of the WHERE clause */
10319 double savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
10320 double nRowOut; /* Estimated number of output rows */
10321 WhereLevel a[1]; /* Information about each nest loop in WHERE */
10325 ** A NameContext defines a context in which to resolve table and column
10326 ** names. The context consists of a list of tables (the pSrcList) field and
10327 ** a list of named expression (pEList). The named expression list may
10328 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
10329 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
10330 ** pEList corresponds to the result set of a SELECT and is NULL for
10331 ** other statements.
10333 ** NameContexts can be nested. When resolving names, the inner-most
10334 ** context is searched first. If no match is found, the next outer
10335 ** context is checked. If there is still no match, the next context
10336 ** is checked. This process continues until either a match is found
10337 ** or all contexts are check. When a match is found, the nRef member of
10338 ** the context containing the match is incremented.
10340 ** Each subquery gets a new NameContext. The pNext field points to the
10341 ** NameContext in the parent query. Thus the process of scanning the
10342 ** NameContext list corresponds to searching through successively outer
10343 ** subqueries looking for a match.
10345 struct NameContext {
10346 Parse *pParse; /* The parser */
10347 SrcList *pSrcList; /* One or more tables used to resolve names */
10348 ExprList *pEList; /* Optional list of named expressions */
10349 int nRef; /* Number of names resolved by this context */
10350 int nErr; /* Number of errors encountered while resolving names */
10351 u8 allowAgg; /* Aggregate functions allowed here */
10352 u8 hasAgg; /* True if aggregates are seen */
10353 u8 isCheck; /* True if resolving names in a CHECK constraint */
10354 int nDepth; /* Depth of subquery recursion. 1 for no recursion */
10355 AggInfo *pAggInfo; /* Information about aggregates at this level */
10356 NameContext *pNext; /* Next outer name context. NULL for outermost */
10360 ** An instance of the following structure contains all information
10361 ** needed to generate code for a single SELECT statement.
10363 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
10364 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10365 ** limit and nOffset to the value of the offset (or 0 if there is not
10366 ** offset). But later on, nLimit and nOffset become the memory locations
10367 ** in the VDBE that record the limit and offset counters.
10369 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10370 ** These addresses must be stored so that we can go back and fill in
10371 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
10372 ** the number of columns in P2 can be computed at the same time
10373 ** as the OP_OpenEphm instruction is coded because not
10374 ** enough information about the compound query is known at that point.
10375 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10376 ** for the result set. The KeyInfo for addrOpenTran[2] contains collating
10377 ** sequences for the ORDER BY clause.
10379 struct Select {
10380 ExprList *pEList; /* The fields of the result */
10381 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10382 char affinity; /* MakeRecord with this affinity for SRT_Set */
10383 u16 selFlags; /* Various SF_* values */
10384 SrcList *pSrc; /* The FROM clause */
10385 Expr *pWhere; /* The WHERE clause */
10386 ExprList *pGroupBy; /* The GROUP BY clause */
10387 Expr *pHaving; /* The HAVING clause */
10388 ExprList *pOrderBy; /* The ORDER BY clause */
10389 Select *pPrior; /* Prior select in a compound select statement */
10390 Select *pNext; /* Next select to the left in a compound */
10391 Select *pRightmost; /* Right-most select in a compound select statement */
10392 Expr *pLimit; /* LIMIT expression. NULL means not used. */
10393 Expr *pOffset; /* OFFSET expression. NULL means not used. */
10394 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
10395 int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
10396 double nSelectRow; /* Estimated number of result rows */
10400 ** Allowed values for Select.selFlags. The "SF" prefix stands for
10401 ** "Select Flag".
10403 #define SF_Distinct 0x0001 /* Output should be DISTINCT */
10404 #define SF_Resolved 0x0002 /* Identifiers have been resolved */
10405 #define SF_Aggregate 0x0004 /* Contains aggregate functions */
10406 #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
10407 #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
10408 #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
10412 ** The results of a select can be distributed in several ways. The
10413 ** "SRT" prefix means "SELECT Result Type".
10415 #define SRT_Union 1 /* Store result as keys in an index */
10416 #define SRT_Except 2 /* Remove result from a UNION index */
10417 #define SRT_Exists 3 /* Store 1 if the result is not empty */
10418 #define SRT_Discard 4 /* Do not save the results anywhere */
10420 /* The ORDER BY clause is ignored for all of the above */
10421 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10423 #define SRT_Output 5 /* Output each row of result */
10424 #define SRT_Mem 6 /* Store result in a memory cell */
10425 #define SRT_Set 7 /* Store results as keys in an index */
10426 #define SRT_Table 8 /* Store result as data with an automatic rowid */
10427 #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
10428 #define SRT_Coroutine 10 /* Generate a single row of result */
10431 ** A structure used to customize the behavior of sqlite3Select(). See
10432 ** comments above sqlite3Select() for details.
10434 typedef struct SelectDest SelectDest;
10435 struct SelectDest {
10436 u8 eDest; /* How to dispose of the results */
10437 u8 affinity; /* Affinity used when eDest==SRT_Set */
10438 int iParm; /* A parameter used by the eDest disposal method */
10439 int iMem; /* Base register where results are written */
10440 int nMem; /* Number of registers allocated */
10444 ** During code generation of statements that do inserts into AUTOINCREMENT
10445 ** tables, the following information is attached to the Table.u.autoInc.p
10446 ** pointer of each autoincrement table to record some side information that
10447 ** the code generator needs. We have to keep per-table autoincrement
10448 ** information in case inserts are down within triggers. Triggers do not
10449 ** normally coordinate their activities, but we do need to coordinate the
10450 ** loading and saving of autoincrement information.
10452 struct AutoincInfo {
10453 AutoincInfo *pNext; /* Next info block in a list of them all */
10454 Table *pTab; /* Table this info block refers to */
10455 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
10456 int regCtr; /* Memory register holding the rowid counter */
10460 ** Size of the column cache
10462 #ifndef SQLITE_N_COLCACHE
10463 # define SQLITE_N_COLCACHE 10
10464 #endif
10467 ** At least one instance of the following structure is created for each
10468 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10469 ** statement. All such objects are stored in the linked list headed at
10470 ** Parse.pTriggerPrg and deleted once statement compilation has been
10471 ** completed.
10473 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10474 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10475 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10476 ** The Parse.pTriggerPrg list never contains two entries with the same
10477 ** values for both pTrigger and orconf.
10479 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10480 ** accessed (or set to 0 for triggers fired as a result of INSERT
10481 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10482 ** a mask of new.* columns used by the program.
10484 struct TriggerPrg {
10485 Trigger *pTrigger; /* Trigger this program was coded from */
10486 int orconf; /* Default ON CONFLICT policy */
10487 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
10488 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
10489 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
10493 ** The yDbMask datatype for the bitmask of all attached databases.
10495 #if SQLITE_MAX_ATTACHED>30
10496 typedef sqlite3_uint64 yDbMask;
10497 #else
10498 typedef unsigned int yDbMask;
10499 #endif
10502 ** An SQL parser context. A copy of this structure is passed through
10503 ** the parser and down into all the parser action routine in order to
10504 ** carry around information that is global to the entire parse.
10506 ** The structure is divided into two parts. When the parser and code
10507 ** generate call themselves recursively, the first part of the structure
10508 ** is constant but the second part is reset at the beginning and end of
10509 ** each recursion.
10511 ** The nTableLock and aTableLock variables are only used if the shared-cache
10512 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10513 ** used to store the set of table-locks required by the statement being
10514 ** compiled. Function sqlite3TableLock() is used to add entries to the
10515 ** list.
10517 struct Parse {
10518 sqlite3 *db; /* The main database structure */
10519 int rc; /* Return code from execution */
10520 char *zErrMsg; /* An error message */
10521 Vdbe *pVdbe; /* An engine for executing database bytecode */
10522 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
10523 u8 nameClash; /* A permanent table name clashes with temp table name */
10524 u8 checkSchema; /* Causes schema cookie check after an error */
10525 u8 nested; /* Number of nested calls to the parser/code generator */
10526 u8 parseError; /* True after a parsing error. Ticket #1794 */
10527 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
10528 u8 nTempInUse; /* Number of aTempReg[] currently checked out */
10529 int aTempReg[8]; /* Holding area for temporary registers */
10530 int nRangeReg; /* Size of the temporary register block */
10531 int iRangeReg; /* First register in temporary register block */
10532 int nErr; /* Number of errors seen */
10533 int nTab; /* Number of previously allocated VDBE cursors */
10534 int nMem; /* Number of memory cells used so far */
10535 int nSet; /* Number of sets used so far */
10536 int ckBase; /* Base register of data during check constraints */
10537 int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10538 int iCacheCnt; /* Counter used to generate aColCache[].lru values */
10539 u8 nColCache; /* Number of entries in the column cache */
10540 u8 iColCache; /* Next entry of the cache to replace */
10541 struct yColCache {
10542 int iTable; /* Table cursor number */
10543 int iColumn; /* Table column number */
10544 u8 tempReg; /* iReg is a temp register that needs to be freed */
10545 int iLevel; /* Nesting level */
10546 int iReg; /* Reg with value of this column. 0 means none. */
10547 int lru; /* Least recently used entry has the smallest value */
10548 } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
10549 yDbMask writeMask; /* Start a write transaction on these databases */
10550 yDbMask cookieMask; /* Bitmask of schema verified databases */
10551 u8 isMultiWrite; /* True if statement may affect/insert multiple rows */
10552 u8 mayAbort; /* True if statement may throw an ABORT exception */
10553 int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
10554 int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
10555 #ifndef SQLITE_OMIT_SHARED_CACHE
10556 int nTableLock; /* Number of locks in aTableLock */
10557 TableLock *aTableLock; /* Required table locks for shared-cache mode */
10558 #endif
10559 int regRowid; /* Register holding rowid of CREATE TABLE entry */
10560 int regRoot; /* Register holding root page number for new objects */
10561 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
10562 int nMaxArg; /* Max args passed to user function by sub-program */
10564 /* Information used while coding trigger programs. */
10565 Parse *pToplevel; /* Parse structure for main program (or NULL) */
10566 Table *pTriggerTab; /* Table triggers are being coded for */
10567 u32 oldmask; /* Mask of old.* columns referenced */
10568 u32 newmask; /* Mask of new.* columns referenced */
10569 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
10570 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
10571 u8 disableTriggers; /* True to disable triggers */
10572 double nQueryLoop; /* Estimated number of iterations of a query */
10574 /* Above is constant between recursions. Below is reset before and after
10575 ** each recursion */
10577 int nVar; /* Number of '?' variables seen in the SQL so far */
10578 int nVarExpr; /* Number of used slots in apVarExpr[] */
10579 int nVarExprAlloc; /* Number of allocated slots in apVarExpr[] */
10580 Expr **apVarExpr; /* Pointers to :aaa and $aaaa wildcard expressions */
10581 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
10582 int nAlias; /* Number of aliased result set columns */
10583 int nAliasAlloc; /* Number of allocated slots for aAlias[] */
10584 int *aAlias; /* Register used to hold aliased result */
10585 u8 explain; /* True if the EXPLAIN flag is found on the query */
10586 Token sNameToken; /* Token with unqualified schema object name */
10587 Token sLastToken; /* The last token parsed */
10588 const char *zTail; /* All SQL text past the last semicolon parsed */
10589 Table *pNewTable; /* A table being constructed by CREATE TABLE */
10590 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
10591 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10592 #ifndef SQLITE_OMIT_VIRTUALTABLE
10593 Token sArg; /* Complete text of a module argument */
10594 u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
10595 int nVtabLock; /* Number of virtual tables to lock */
10596 Table **apVtabLock; /* Pointer to virtual tables needing locking */
10597 #endif
10598 int nHeight; /* Expression tree height of current sub-select */
10599 Table *pZombieTab; /* List of Table objects to delete after code gen */
10600 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
10602 #ifndef SQLITE_OMIT_EXPLAIN
10603 int iSelectId;
10604 int iNextSelectId;
10605 #endif
10608 #ifdef SQLITE_OMIT_VIRTUALTABLE
10609 #define IN_DECLARE_VTAB 0
10610 #else
10611 #define IN_DECLARE_VTAB (pParse->declareVtab)
10612 #endif
10615 ** An instance of the following structure can be declared on a stack and used
10616 ** to save the Parse.zAuthContext value so that it can be restored later.
10618 struct AuthContext {
10619 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
10620 Parse *pParse; /* The Parse structure */
10624 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10626 #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
10627 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
10628 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
10629 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
10630 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
10631 #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
10634 * Each trigger present in the database schema is stored as an instance of
10635 * struct Trigger.
10637 * Pointers to instances of struct Trigger are stored in two ways.
10638 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
10639 * database). This allows Trigger structures to be retrieved by name.
10640 * 2. All triggers associated with a single table form a linked list, using the
10641 * pNext member of struct Trigger. A pointer to the first element of the
10642 * linked list is stored as the "pTrigger" member of the associated
10643 * struct Table.
10645 * The "step_list" member points to the first element of a linked list
10646 * containing the SQL statements specified as the trigger program.
10648 struct Trigger {
10649 char *zName; /* The name of the trigger */
10650 char *table; /* The table or view to which the trigger applies */
10651 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
10652 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10653 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
10654 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
10655 the <column-list> is stored here */
10656 Schema *pSchema; /* Schema containing the trigger */
10657 Schema *pTabSchema; /* Schema containing the table */
10658 TriggerStep *step_list; /* Link list of trigger program steps */
10659 Trigger *pNext; /* Next trigger associated with the table */
10663 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
10664 ** determine which.
10666 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10667 ** In that cases, the constants below can be ORed together.
10669 #define TRIGGER_BEFORE 1
10670 #define TRIGGER_AFTER 2
10673 * An instance of struct TriggerStep is used to store a single SQL statement
10674 * that is a part of a trigger-program.
10676 * Instances of struct TriggerStep are stored in a singly linked list (linked
10677 * using the "pNext" member) referenced by the "step_list" member of the
10678 * associated struct Trigger instance. The first element of the linked list is
10679 * the first step of the trigger-program.
10681 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10682 * "SELECT" statement. The meanings of the other members is determined by the
10683 * value of "op" as follows:
10685 * (op == TK_INSERT)
10686 * orconf -> stores the ON CONFLICT algorithm
10687 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
10688 * this stores a pointer to the SELECT statement. Otherwise NULL.
10689 * target -> A token holding the quoted name of the table to insert into.
10690 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10691 * this stores values to be inserted. Otherwise NULL.
10692 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
10693 * statement, then this stores the column-names to be
10694 * inserted into.
10696 * (op == TK_DELETE)
10697 * target -> A token holding the quoted name of the table to delete from.
10698 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
10699 * Otherwise NULL.
10701 * (op == TK_UPDATE)
10702 * target -> A token holding the quoted name of the table to update rows of.
10703 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
10704 * Otherwise NULL.
10705 * pExprList -> A list of the columns to update and the expressions to update
10706 * them to. See sqlite3Update() documentation of "pChanges"
10707 * argument.
10710 struct TriggerStep {
10711 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10712 u8 orconf; /* OE_Rollback etc. */
10713 Trigger *pTrig; /* The trigger that this step is a part of */
10714 Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10715 Token target; /* Target table for DELETE, UPDATE, INSERT */
10716 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
10717 ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
10718 IdList *pIdList; /* Column names for INSERT */
10719 TriggerStep *pNext; /* Next in the link-list */
10720 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
10724 ** The following structure contains information used by the sqliteFix...
10725 ** routines as they walk the parse tree to make database references
10726 ** explicit.
10728 typedef struct DbFixer DbFixer;
10729 struct DbFixer {
10730 Parse *pParse; /* The parsing context. Error messages written here */
10731 const char *zDb; /* Make sure all objects are contained in this database */
10732 const char *zType; /* Type of the container - used for error messages */
10733 const Token *pName; /* Name of the container - used for error messages */
10737 ** An objected used to accumulate the text of a string where we
10738 ** do not necessarily know how big the string will be in the end.
10740 struct StrAccum {
10741 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
10742 char *zBase; /* A base allocation. Not from malloc. */
10743 char *zText; /* The string collected so far */
10744 int nChar; /* Length of the string so far */
10745 int nAlloc; /* Amount of space allocated in zText */
10746 int mxAlloc; /* Maximum allowed string length */
10747 u8 mallocFailed; /* Becomes true if any memory allocation fails */
10748 u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
10749 u8 tooBig; /* Becomes true if string size exceeds limits */
10753 ** A pointer to this structure is used to communicate information
10754 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10756 typedef struct {
10757 sqlite3 *db; /* The database being initialized */
10758 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
10759 char **pzErrMsg; /* Error message stored here */
10760 int rc; /* Result code stored here */
10761 } InitData;
10764 ** Structure containing global configuration data for the SQLite library.
10766 ** This structure also contains some state information.
10768 struct Sqlite3Config {
10769 int bMemstat; /* True to enable memory status */
10770 int bCoreMutex; /* True to enable core mutexing */
10771 int bFullMutex; /* True to enable full mutexing */
10772 int mxStrlen; /* Maximum string length */
10773 int szLookaside; /* Default lookaside buffer size */
10774 int nLookaside; /* Default lookaside buffer count */
10775 sqlite3_mem_methods m; /* Low-level memory allocation interface */
10776 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
10777 sqlite3_pcache_methods pcache; /* Low-level page-cache interface */
10778 void *pHeap; /* Heap storage space */
10779 int nHeap; /* Size of pHeap[] */
10780 int mnReq, mxReq; /* Min and max heap requests sizes */
10781 void *pScratch; /* Scratch memory */
10782 int szScratch; /* Size of each scratch buffer */
10783 int nScratch; /* Number of scratch buffers */
10784 void *pPage; /* Page cache memory */
10785 int szPage; /* Size of each page in pPage[] */
10786 int nPage; /* Number of pages in pPage[] */
10787 int mxParserStack; /* maximum depth of the parser stack */
10788 int sharedCacheEnabled; /* true if shared-cache mode enabled */
10789 /* The above might be initialized to non-zero. The following need to always
10790 ** initially be zero, however. */
10791 int isInit; /* True after initialization has finished */
10792 int inProgress; /* True while initialization in progress */
10793 int isMutexInit; /* True after mutexes are initialized */
10794 int isMallocInit; /* True after malloc is initialized */
10795 int isPCacheInit; /* True after malloc is initialized */
10796 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
10797 int nRefInitMutex; /* Number of users of pInitMutex */
10798 void (*xLog)(void*,int,const char*); /* Function for logging */
10799 void *pLogArg; /* First argument to xLog() */
10803 ** Context pointer passed down through the tree-walk.
10805 struct Walker {
10806 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
10807 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
10808 Parse *pParse; /* Parser context. */
10809 union { /* Extra data for callback */
10810 NameContext *pNC; /* Naming context */
10811 int i; /* Integer value */
10812 } u;
10815 /* Forward declarations */
10816 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10817 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10818 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10819 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10820 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10823 ** Return code from the parse-tree walking primitives and their
10824 ** callbacks.
10826 #define WRC_Continue 0 /* Continue down into children */
10827 #define WRC_Prune 1 /* Omit children but continue walking siblings */
10828 #define WRC_Abort 2 /* Abandon the tree walk */
10831 ** Assuming zIn points to the first byte of a UTF-8 character,
10832 ** advance zIn to point to the first byte of the next UTF-8 character.
10834 #define SQLITE_SKIP_UTF8(zIn) { \
10835 if( (*(zIn++))>=0xc0 ){ \
10836 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
10841 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
10842 ** the same name but without the _BKPT suffix. These macros invoke
10843 ** routines that report the line-number on which the error originated
10844 ** using sqlite3_log(). The routines also provide a convenient place
10845 ** to set a debugger breakpoint.
10847 SQLITE_PRIVATE int sqlite3CorruptError(int);
10848 SQLITE_PRIVATE int sqlite3MisuseError(int);
10849 SQLITE_PRIVATE int sqlite3CantopenError(int);
10850 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10851 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10852 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10856 ** FTS4 is really an extension for FTS3. It is enabled using the
10857 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
10858 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10860 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10861 # define SQLITE_ENABLE_FTS3
10862 #endif
10865 ** The ctype.h header is needed for non-ASCII systems. It is also
10866 ** needed by FTS3 when FTS3 is included in the amalgamation.
10868 #if !defined(SQLITE_ASCII) || \
10869 (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10870 # include <ctype.h>
10871 #endif
10874 ** The CoreServices.h and CoreFoundation.h headers are needed for excluding a
10875 ** -journal file from Time Machine backups when its associated database has
10876 ** previously been excluded by the client code.
10878 #if defined(__APPLE__)
10879 #include <CoreServices/CoreServices.h>
10880 #include <CoreFoundation/CoreFoundation.h>
10881 #endif
10884 ** The following macros mimic the standard library functions toupper(),
10885 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10886 ** sqlite versions only work for ASCII characters, regardless of locale.
10888 #ifdef SQLITE_ASCII
10889 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10890 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10891 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10892 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10893 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10894 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10895 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
10896 #else
10897 # define sqlite3Toupper(x) toupper((unsigned char)(x))
10898 # define sqlite3Isspace(x) isspace((unsigned char)(x))
10899 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
10900 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
10901 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
10902 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
10903 # define sqlite3Tolower(x) tolower((unsigned char)(x))
10904 #endif
10907 ** Internal function prototypes
10909 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10910 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10911 #define sqlite3StrNICmp sqlite3_strnicmp
10913 SQLITE_PRIVATE int sqlite3MallocInit(void);
10914 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10915 SQLITE_PRIVATE void *sqlite3Malloc(int);
10916 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10917 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10918 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10919 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10920 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10921 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10922 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10923 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10924 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10925 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10926 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10927 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10928 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10929 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10930 SQLITE_PRIVATE void sqlite3PageFree(void*);
10931 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10932 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10933 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
10936 ** On systems with ample stack space and that support alloca(), make
10937 ** use of alloca() to obtain space for large automatic objects. By default,
10938 ** obtain space from malloc().
10940 ** The alloca() routine never returns NULL. This will cause code paths
10941 ** that deal with sqlite3StackAlloc() failures to be unreachable.
10943 #ifdef SQLITE_USE_ALLOCA
10944 # define sqlite3StackAllocRaw(D,N) alloca(N)
10945 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
10946 # define sqlite3StackFree(D,P)
10947 #else
10948 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
10949 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
10950 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
10951 #endif
10953 #ifdef SQLITE_ENABLE_MEMSYS3
10954 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10955 #endif
10956 #ifdef SQLITE_ENABLE_MEMSYS5
10957 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10958 #endif
10961 #ifndef SQLITE_MUTEX_OMIT
10962 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10963 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10964 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
10965 SQLITE_PRIVATE int sqlite3MutexInit(void);
10966 SQLITE_PRIVATE int sqlite3MutexEnd(void);
10967 #endif
10969 SQLITE_PRIVATE int sqlite3StatusValue(int);
10970 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10971 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10973 #ifndef SQLITE_OMIT_FLOATING_POINT
10974 SQLITE_PRIVATE int sqlite3IsNaN(double);
10975 #else
10976 # define sqlite3IsNaN(X) 0
10977 #endif
10979 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10980 #ifndef SQLITE_OMIT_TRACE
10981 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10982 #endif
10983 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10984 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10985 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10986 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10987 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
10988 #endif
10989 #if defined(SQLITE_TEST)
10990 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
10991 #endif
10992 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10993 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10994 SQLITE_PRIVATE int sqlite3Dequote(char*);
10995 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10996 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10997 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10998 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10999 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11000 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11001 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11002 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11003 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11004 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11005 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11006 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11007 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11008 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11009 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11010 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11011 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11012 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11013 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11014 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11015 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11016 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11017 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
11018 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11019 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11020 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11021 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11022 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11023 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11024 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11025 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11026 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11027 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11028 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11029 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11030 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11032 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11033 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11034 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11035 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11036 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11037 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11038 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11040 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11041 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11042 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11043 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11044 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11046 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11048 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11049 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
11050 #else
11051 # define sqlite3ViewGetColumnNames(A,B) 0
11052 #endif
11054 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11055 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11056 #ifndef SQLITE_OMIT_AUTOINCREMENT
11057 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
11058 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
11059 #else
11060 # define sqlite3AutoincrementBegin(X)
11061 # define sqlite3AutoincrementEnd(X)
11062 #endif
11063 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11064 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
11065 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11066 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11067 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11068 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11069 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11070 Token*, Select*, Expr*, IdList*);
11071 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11072 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11073 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11074 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11075 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11076 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11077 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11078 Token*, int, int);
11079 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11080 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11081 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11082 Expr*,ExprList*,int,Expr*,Expr*);
11083 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11084 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11085 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11086 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11087 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11088 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11089 #endif
11090 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11091 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11092 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
11093 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11094 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11095 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11096 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11097 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11098 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11099 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11100 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11101 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11102 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11103 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11104 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11105 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11106 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11107 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11108 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11109 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11110 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11111 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11112 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11113 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11114 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11115 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11116 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11117 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11118 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11119 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11120 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11121 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11122 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11123 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11124 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11125 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11126 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11127 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11128 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
11129 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11130 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11131 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11132 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11133 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11134 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11135 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11136 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11137 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11138 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11139 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11140 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11141 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11142 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11143 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11144 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11145 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11146 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11147 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11148 int*,int,int,int,int,int*);
11149 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11150 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11151 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11152 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11153 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11154 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11155 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11156 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11157 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11158 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11159 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11160 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11161 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
11162 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11163 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11164 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11165 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11166 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11167 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11169 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11170 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11171 #endif
11173 #ifndef SQLITE_OMIT_TRIGGER
11174 SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11175 Expr*,int, int);
11176 SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11177 SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
11178 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
11179 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11180 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
11181 SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11182 int, int, int);
11183 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11184 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11185 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11186 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11187 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11188 ExprList*,Select*,u8);
11189 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11190 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11191 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11192 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11193 SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11194 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11195 #else
11196 # define sqlite3TriggersExist(B,C,D,E,F) 0
11197 # define sqlite3DeleteTrigger(A,B)
11198 # define sqlite3DropTriggerPtr(A,B)
11199 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11200 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11201 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11202 # define sqlite3TriggerList(X, Y) 0
11203 # define sqlite3ParseToplevel(p) p
11204 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11205 #endif
11207 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11208 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11209 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11210 #ifndef SQLITE_OMIT_AUTHORIZATION
11211 SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11212 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11213 SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11214 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
11215 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11216 #else
11217 # define sqlite3AuthRead(a,b,c,d)
11218 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
11219 # define sqlite3AuthContextPush(a,b,c)
11220 # define sqlite3AuthContextPop(a) ((void)(a))
11221 #endif
11222 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11223 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11224 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11225 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11226 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11227 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11228 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11229 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11230 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11231 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11232 SQLITE_PRIVATE int sqlite3Atoi(const char*);
11233 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11234 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11235 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
11238 ** Routines to read and write variable-length integers. These used to
11239 ** be defined locally, but now we use the varint routines in the util.c
11240 ** file. Code should use the MACRO forms below, as the Varint32 versions
11241 ** are coded to assume the single byte case is already handled (which
11242 ** the MACRO form does).
11244 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11245 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11246 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11247 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11248 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11251 ** The header of a record consists of a sequence variable-length integers.
11252 ** These integers are almost always small and are encoded as a single byte.
11253 ** The following macros take advantage this fact to provide a fast encode
11254 ** and decode of the integers in a record header. It is faster for the common
11255 ** case where the integer is a single byte. It is a little slower when the
11256 ** integer is two or more bytes. But overall it is faster.
11258 ** The following expressions are equivalent:
11260 ** x = sqlite3GetVarint32( A, &B );
11261 ** x = sqlite3PutVarint32( A, B );
11263 ** x = getVarint32( A, B );
11264 ** x = putVarint32( A, B );
11267 #define getVarint32(A,B) (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11268 #define putVarint32(A,B) (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11269 #define getVarint sqlite3GetVarint
11270 #define putVarint sqlite3PutVarint
11273 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11274 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11275 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11276 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11277 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11278 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11279 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11280 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11281 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11282 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11283 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11284 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11285 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11286 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11287 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11288 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11289 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11290 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11291 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11292 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
11293 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
11294 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
11295 SQLITE_PRIVATE int sqlite3AbsInt32(int);
11297 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11298 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11299 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
11300 void(*)(void*));
11301 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11302 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11303 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11304 #ifdef SQLITE_ENABLE_STAT2
11305 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11306 #endif
11307 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11308 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11309 #ifndef SQLITE_AMALGAMATION
11310 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11311 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11312 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11313 SQLITE_PRIVATE const Token sqlite3IntTokens[];
11314 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11315 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11316 #ifndef SQLITE_OMIT_WSD
11317 SQLITE_PRIVATE int sqlite3PendingByte;
11318 #endif
11319 #endif
11320 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
11321 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11322 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11323 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11324 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11325 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11326 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11327 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11328 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11329 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11330 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11331 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11332 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11333 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11334 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11335 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11336 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11337 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11338 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11339 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11340 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11341 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11342 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11343 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11344 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11345 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11346 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11347 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
11348 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11349 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11350 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11351 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
11352 void (*)(sqlite3_context*,int,sqlite3_value **),
11353 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11354 FuncDestructor *pDestructor
11356 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11357 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11359 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11360 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11361 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11362 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11363 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11364 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11366 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11367 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11370 ** The interface to the LEMON-generated parser
11372 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11373 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11374 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11375 #ifdef YYTRACKMAXSTACKDEPTH
11376 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
11377 #endif
11379 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11380 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11381 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
11382 #else
11383 # define sqlite3CloseExtensions(X)
11384 #endif
11386 #ifndef SQLITE_OMIT_SHARED_CACHE
11387 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
11388 #else
11389 #define sqlite3TableLock(v,w,x,y,z)
11390 #endif
11392 #ifdef SQLITE_TEST
11393 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
11394 #endif
11396 #ifdef SQLITE_OMIT_VIRTUALTABLE
11397 # define sqlite3VtabClear(Y)
11398 # define sqlite3VtabSync(X,Y) SQLITE_OK
11399 # define sqlite3VtabRollback(X)
11400 # define sqlite3VtabCommit(X)
11401 # define sqlite3VtabInSync(db) 0
11402 # define sqlite3VtabLock(X)
11403 # define sqlite3VtabUnlock(X)
11404 # define sqlite3VtabUnlockList(X)
11405 #else
11406 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
11407 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **);
11408 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
11409 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
11410 SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
11411 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
11412 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
11413 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11414 #endif
11415 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11416 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11417 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11418 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11419 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11420 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11421 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11422 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11423 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
11424 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11425 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11426 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
11427 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11428 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11429 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11430 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11431 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
11432 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
11433 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
11434 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
11435 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
11437 /* Declarations for functions in fkey.c. All of these are replaced by
11438 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11439 ** key functionality is available. If OMIT_TRIGGER is defined but
11440 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11441 ** this case foreign keys are parsed, but no other functionality is
11442 ** provided (enforcement of FK constraints requires the triggers sub-system).
11444 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
11445 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int);
11446 SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
11447 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int);
11448 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
11449 SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
11450 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
11451 #else
11452 #define sqlite3FkActions(a,b,c,d)
11453 #define sqlite3FkCheck(a,b,c,d)
11454 #define sqlite3FkDropTable(a,b,c)
11455 #define sqlite3FkOldmask(a,b) 0
11456 #define sqlite3FkRequired(a,b,c,d) 0
11457 #endif
11458 #ifndef SQLITE_OMIT_FOREIGN_KEY
11459 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
11460 #else
11461 #define sqlite3FkDelete(a,b)
11462 #endif
11466 ** Available fault injectors. Should be numbered beginning with 0.
11468 #define SQLITE_FAULTINJECTOR_MALLOC 0
11469 #define SQLITE_FAULTINJECTOR_COUNT 1
11472 ** The interface to the code in fault.c used for identifying "benign"
11473 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11474 ** is not defined.
11476 #ifndef SQLITE_OMIT_BUILTIN_TEST
11477 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
11478 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
11479 #else
11480 #define sqlite3BeginBenignMalloc()
11481 #define sqlite3EndBenignMalloc()
11482 #endif
11484 #define IN_INDEX_ROWID 1
11485 #define IN_INDEX_EPH 2
11486 #define IN_INDEX_INDEX 3
11487 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11489 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11490 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11491 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
11492 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
11493 #else
11494 #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11495 #endif
11497 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11498 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11499 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11501 #if SQLITE_MAX_EXPR_DEPTH>0
11502 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11503 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
11504 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
11505 #else
11506 #define sqlite3ExprSetHeight(x,y)
11507 #define sqlite3SelectExprHeight(x) 0
11508 #define sqlite3ExprCheckHeight(x,y)
11509 #endif
11511 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11512 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11514 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11515 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
11516 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
11517 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
11518 #else
11519 #define sqlite3ConnectionBlocked(x,y)
11520 #define sqlite3ConnectionUnlocked(x)
11521 #define sqlite3ConnectionClosed(x)
11522 #endif
11524 #ifdef SQLITE_DEBUG
11525 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
11526 #endif
11529 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11530 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11531 ** print I/O tracing messages.
11533 #ifdef SQLITE_ENABLE_IOTRACE
11534 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11535 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
11536 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11537 #else
11538 # define IOTRACE(A)
11539 # define sqlite3VdbeIOTraceSql(X)
11540 #endif
11543 ** These routines are available for the mem2.c debugging memory allocator
11544 ** only. They are used to verify that different "types" of memory
11545 ** allocations are properly tracked by the system.
11547 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
11548 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
11549 ** a single bit set.
11551 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
11552 ** argument match the type set by the previous sqlite3MemdebugSetType().
11553 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
11555 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
11556 ** argument match the type set by the previous sqlite3MemdebugSetType().
11558 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11559 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
11560 ** it might have been allocated by lookaside, except the allocation was
11561 ** too large or lookaside was already full. It is important to verify
11562 ** that allocations that might have been satisfied by lookaside are not
11563 ** passed back to non-lookaside free() routines. Asserts such as the
11564 ** example above are placed on the non-lookaside free() routines to verify
11565 ** this constraint.
11567 ** All of this is no-op for a production build. It only comes into
11568 ** play when the SQLITE_MEMDEBUG compile-time option is used.
11570 #ifdef SQLITE_MEMDEBUG
11571 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
11572 SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
11573 SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
11574 #else
11575 # define sqlite3MemdebugSetType(X,Y) /* no-op */
11576 # define sqlite3MemdebugHasType(X,Y) 1
11577 # define sqlite3MemdebugNoType(X,Y) 1
11578 #endif
11579 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
11580 #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
11581 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
11582 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
11583 #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
11585 #endif /* _SQLITEINT_H_ */
11587 /************** End of sqliteInt.h *******************************************/
11588 /************** Begin file global.c ******************************************/
11590 ** 2008 June 13
11592 ** The author disclaims copyright to this source code. In place of
11593 ** a legal notice, here is a blessing:
11595 ** May you do good and not evil.
11596 ** May you find forgiveness for yourself and forgive others.
11597 ** May you share freely, never taking more than you give.
11599 *************************************************************************
11601 ** This file contains definitions of global variables and contants.
11604 /* An array to map all upper-case characters into their corresponding
11605 ** lower-case character.
11607 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
11608 ** handle case conversions for the UTF character set since the tables
11609 ** involved are nearly as big or bigger than SQLite itself.
11611 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11612 #ifdef SQLITE_ASCII
11613 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
11614 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11615 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11616 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11617 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11618 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11619 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11620 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11621 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11622 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11623 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11624 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11625 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11626 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11627 252,253,254,255
11628 #endif
11629 #ifdef SQLITE_EBCDIC
11630 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
11631 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11632 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11633 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11634 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11635 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11636 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11637 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11638 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11639 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11640 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11641 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11642 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11643 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11644 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11645 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11646 #endif
11650 ** The following 256 byte lookup table is used to support SQLites built-in
11651 ** equivalents to the following standard library functions:
11653 ** isspace() 0x01
11654 ** isalpha() 0x02
11655 ** isdigit() 0x04
11656 ** isalnum() 0x06
11657 ** isxdigit() 0x08
11658 ** toupper() 0x20
11659 ** SQLite identifier character 0x40
11661 ** Bit 0x20 is set if the mapped character requires translation to upper
11662 ** case. i.e. if the character is a lower-case ASCII character.
11663 ** If x is a lower-case ASCII character, then its upper-case equivalent
11664 ** is (x - 0x20). Therefore toupper() can be implemented as:
11666 ** (x & ~(map[x]&0x20))
11668 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11669 ** array. tolower() is used more often than toupper() by SQLite.
11671 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
11672 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
11673 ** non-ASCII UTF character. Hence the test for whether or not a character is
11674 ** part of an identifier is 0x46.
11676 ** SQLite's versions are identical to the standard versions assuming a
11677 ** locale of "C". They are implemented as macros in sqliteInt.h.
11679 #ifdef SQLITE_ASCII
11680 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11681 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
11682 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
11683 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
11684 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
11685 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
11686 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
11687 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
11688 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
11690 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
11691 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
11692 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
11693 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
11694 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
11695 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
11696 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
11697 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
11699 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
11700 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
11701 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
11702 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
11703 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
11704 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
11705 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
11706 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
11708 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
11709 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
11710 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
11711 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
11712 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
11713 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
11714 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
11715 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
11717 #endif
11722 ** The following singleton contains the global configuration for
11723 ** the SQLite library.
11725 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11726 SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
11727 1, /* bCoreMutex */
11728 SQLITE_THREADSAFE==1, /* bFullMutex */
11729 0x7ffffffe, /* mxStrlen */
11730 100, /* szLookaside */
11731 500, /* nLookaside */
11732 {0,0,0,0,0,0,0,0}, /* m */
11733 {0,0,0,0,0,0,0,0,0}, /* mutex */
11734 {0,0,0,0,0,0,0,0,0,0,0}, /* pcache */
11735 (void*)0, /* pHeap */
11736 0, /* nHeap */
11737 0, 0, /* mnHeap, mxHeap */
11738 (void*)0, /* pScratch */
11739 0, /* szScratch */
11740 0, /* nScratch */
11741 (void*)0, /* pPage */
11742 0, /* szPage */
11743 0, /* nPage */
11744 0, /* mxParserStack */
11745 0, /* sharedCacheEnabled */
11746 /* All the rest should always be initialized to zero */
11747 0, /* isInit */
11748 0, /* inProgress */
11749 0, /* isMutexInit */
11750 0, /* isMallocInit */
11751 0, /* isPCacheInit */
11752 0, /* pInitMutex */
11753 0, /* nRefInitMutex */
11754 0, /* xLog */
11755 0, /* pLogArg */
11760 ** Hash table for global functions - functions common to all
11761 ** database connections. After initialization, this table is
11762 ** read-only.
11764 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11767 ** Constant tokens for values 0 and 1.
11769 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11770 { "0", 1 },
11771 { "1", 1 }
11776 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
11777 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
11778 ** the database page that contains the pending byte. It never attempts
11779 ** to read or write that page. The pending byte page is set assign
11780 ** for use by the VFS layers as space for managing file locks.
11782 ** During testing, it is often desirable to move the pending byte to
11783 ** a different position in the file. This allows code that has to
11784 ** deal with the pending byte to run on files that are much smaller
11785 ** than 1 GiB. The sqlite3_test_control() interface can be used to
11786 ** move the pending byte.
11788 ** IMPORTANT: Changing the pending byte to any value other than
11789 ** 0x40000000 results in an incompatible database file format!
11790 ** Changing the pending byte during operating results in undefined
11791 ** and dileterious behavior.
11793 #ifndef SQLITE_OMIT_WSD
11794 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11795 #endif
11798 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
11799 ** created by mkopcodeh.awk during compilation. Data is obtained
11800 ** from the comments following the "case OP_xxxx:" statements in
11801 ** the vdbe.c file.
11803 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11805 /************** End of global.c **********************************************/
11806 /************** Begin file ctime.c *******************************************/
11808 ** 2010 February 23
11810 ** The author disclaims copyright to this source code. In place of
11811 ** a legal notice, here is a blessing:
11813 ** May you do good and not evil.
11814 ** May you find forgiveness for yourself and forgive others.
11815 ** May you share freely, never taking more than you give.
11817 *************************************************************************
11819 ** This file implements routines used to report what compile-time options
11820 ** SQLite was built with.
11823 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11827 ** An array of names of all compile-time options. This array should
11828 ** be sorted A-Z.
11830 ** This array looks large, but in a typical installation actually uses
11831 ** only a handful of compile-time options, so most times this array is usually
11832 ** rather short and uses little memory space.
11834 static const char * const azCompileOpt[] = {
11836 /* These macros are provided to "stringify" the value of the define
11837 ** for those options in which the value is meaningful. */
11838 #define CTIMEOPT_VAL_(opt) #opt
11839 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11841 #ifdef SQLITE_32BIT_ROWID
11842 "32BIT_ROWID",
11843 #endif
11844 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11845 "4_BYTE_ALIGNED_MALLOC",
11846 #endif
11847 #ifdef SQLITE_CASE_SENSITIVE_LIKE
11848 "CASE_SENSITIVE_LIKE",
11849 #endif
11850 #ifdef SQLITE_CHECK_PAGES
11851 "CHECK_PAGES",
11852 #endif
11853 #ifdef SQLITE_COVERAGE_TEST
11854 "COVERAGE_TEST",
11855 #endif
11856 #ifdef SQLITE_DEBUG
11857 "DEBUG",
11858 #endif
11859 #ifdef SQLITE_DEFAULT_LOCKING_MODE
11860 "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11861 #endif
11862 #ifdef SQLITE_DISABLE_DIRSYNC
11863 "DISABLE_DIRSYNC",
11864 #endif
11865 #ifdef SQLITE_DISABLE_LFS
11866 "DISABLE_LFS",
11867 #endif
11868 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11869 "ENABLE_ATOMIC_WRITE",
11870 #endif
11871 #ifdef SQLITE_ENABLE_CEROD
11872 "ENABLE_CEROD",
11873 #endif
11874 #ifdef SQLITE_ENABLE_COLUMN_METADATA
11875 "ENABLE_COLUMN_METADATA",
11876 #endif
11877 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11878 "ENABLE_EXPENSIVE_ASSERT",
11879 #endif
11880 #ifdef SQLITE_ENABLE_FTS1
11881 "ENABLE_FTS1",
11882 #endif
11883 #ifdef SQLITE_ENABLE_FTS2
11884 "ENABLE_FTS2",
11885 #endif
11886 #ifdef SQLITE_ENABLE_FTS3
11887 "ENABLE_FTS3",
11888 #endif
11889 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11890 "ENABLE_FTS3_PARENTHESIS",
11891 #endif
11892 #ifdef SQLITE_ENABLE_FTS4
11893 "ENABLE_FTS4",
11894 #endif
11895 #ifdef SQLITE_ENABLE_ICU
11896 "ENABLE_ICU",
11897 #endif
11898 #ifdef SQLITE_ENABLE_IOTRACE
11899 "ENABLE_IOTRACE",
11900 #endif
11901 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
11902 "ENABLE_LOAD_EXTENSION",
11903 #endif
11904 #ifdef SQLITE_ENABLE_LOCKING_STYLE
11905 "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11906 #endif
11907 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11908 "ENABLE_MEMORY_MANAGEMENT",
11909 #endif
11910 #ifdef SQLITE_ENABLE_MEMSYS3
11911 "ENABLE_MEMSYS3",
11912 #endif
11913 #ifdef SQLITE_ENABLE_MEMSYS5
11914 "ENABLE_MEMSYS5",
11915 #endif
11916 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11917 "ENABLE_OVERSIZE_CELL_CHECK",
11918 #endif
11919 #ifdef SQLITE_ENABLE_RTREE
11920 "ENABLE_RTREE",
11921 #endif
11922 #ifdef SQLITE_ENABLE_STAT2
11923 "ENABLE_STAT2",
11924 #endif
11925 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11926 "ENABLE_UNLOCK_NOTIFY",
11927 #endif
11928 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11929 "ENABLE_UPDATE_DELETE_LIMIT",
11930 #endif
11931 #ifdef SQLITE_HAS_CODEC
11932 "HAS_CODEC",
11933 #endif
11934 #ifdef SQLITE_HAVE_ISNAN
11935 "HAVE_ISNAN",
11936 #endif
11937 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11938 "HOMEGROWN_RECURSIVE_MUTEX",
11939 #endif
11940 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11941 "IGNORE_AFP_LOCK_ERRORS",
11942 #endif
11943 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11944 "IGNORE_FLOCK_LOCK_ERRORS",
11945 #endif
11946 #ifdef SQLITE_INT64_TYPE
11947 "INT64_TYPE",
11948 #endif
11949 #ifdef SQLITE_LOCK_TRACE
11950 "LOCK_TRACE",
11951 #endif
11952 #ifdef SQLITE_MEMDEBUG
11953 "MEMDEBUG",
11954 #endif
11955 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11956 "MIXED_ENDIAN_64BIT_FLOAT",
11957 #endif
11958 #ifdef SQLITE_NO_SYNC
11959 "NO_SYNC",
11960 #endif
11961 #ifdef SQLITE_OMIT_ALTERTABLE
11962 "OMIT_ALTERTABLE",
11963 #endif
11964 #ifdef SQLITE_OMIT_ANALYZE
11965 "OMIT_ANALYZE",
11966 #endif
11967 #ifdef SQLITE_OMIT_ATTACH
11968 "OMIT_ATTACH",
11969 #endif
11970 #ifdef SQLITE_OMIT_AUTHORIZATION
11971 "OMIT_AUTHORIZATION",
11972 #endif
11973 #ifdef SQLITE_OMIT_AUTOINCREMENT
11974 "OMIT_AUTOINCREMENT",
11975 #endif
11976 #ifdef SQLITE_OMIT_AUTOINIT
11977 "OMIT_AUTOINIT",
11978 #endif
11979 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11980 "OMIT_AUTOMATIC_INDEX",
11981 #endif
11982 #ifdef SQLITE_OMIT_AUTORESET
11983 "OMIT_AUTORESET",
11984 #endif
11985 #ifdef SQLITE_OMIT_AUTOVACUUM
11986 "OMIT_AUTOVACUUM",
11987 #endif
11988 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11989 "OMIT_BETWEEN_OPTIMIZATION",
11990 #endif
11991 #ifdef SQLITE_OMIT_BLOB_LITERAL
11992 "OMIT_BLOB_LITERAL",
11993 #endif
11994 #ifdef SQLITE_OMIT_BTREECOUNT
11995 "OMIT_BTREECOUNT",
11996 #endif
11997 #ifdef SQLITE_OMIT_BUILTIN_TEST
11998 "OMIT_BUILTIN_TEST",
11999 #endif
12000 #ifdef SQLITE_OMIT_CAST
12001 "OMIT_CAST",
12002 #endif
12003 #ifdef SQLITE_OMIT_CHECK
12004 "OMIT_CHECK",
12005 #endif
12006 /* // redundant
12007 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12008 ** "OMIT_COMPILEOPTION_DIAGS",
12009 ** #endif
12011 #ifdef SQLITE_OMIT_COMPLETE
12012 "OMIT_COMPLETE",
12013 #endif
12014 #ifdef SQLITE_OMIT_COMPOUND_SELECT
12015 "OMIT_COMPOUND_SELECT",
12016 #endif
12017 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12018 "OMIT_DATETIME_FUNCS",
12019 #endif
12020 #ifdef SQLITE_OMIT_DECLTYPE
12021 "OMIT_DECLTYPE",
12022 #endif
12023 #ifdef SQLITE_OMIT_DEPRECATED
12024 "OMIT_DEPRECATED",
12025 #endif
12026 #ifdef SQLITE_OMIT_DISKIO
12027 "OMIT_DISKIO",
12028 #endif
12029 #ifdef SQLITE_OMIT_EXPLAIN
12030 "OMIT_EXPLAIN",
12031 #endif
12032 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12033 "OMIT_FLAG_PRAGMAS",
12034 #endif
12035 #ifdef SQLITE_OMIT_FLOATING_POINT
12036 "OMIT_FLOATING_POINT",
12037 #endif
12038 #ifdef SQLITE_OMIT_FOREIGN_KEY
12039 "OMIT_FOREIGN_KEY",
12040 #endif
12041 #ifdef SQLITE_OMIT_GET_TABLE
12042 "OMIT_GET_TABLE",
12043 #endif
12044 #ifdef SQLITE_OMIT_INCRBLOB
12045 "OMIT_INCRBLOB",
12046 #endif
12047 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12048 "OMIT_INTEGRITY_CHECK",
12049 #endif
12050 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12051 "OMIT_LIKE_OPTIMIZATION",
12052 #endif
12053 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12054 "OMIT_LOAD_EXTENSION",
12055 #endif
12056 #ifdef SQLITE_OMIT_LOCALTIME
12057 "OMIT_LOCALTIME",
12058 #endif
12059 #ifdef SQLITE_OMIT_LOOKASIDE
12060 "OMIT_LOOKASIDE",
12061 #endif
12062 #ifdef SQLITE_OMIT_MEMORYDB
12063 "OMIT_MEMORYDB",
12064 #endif
12065 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12066 "OMIT_OR_OPTIMIZATION",
12067 #endif
12068 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12069 "OMIT_PAGER_PRAGMAS",
12070 #endif
12071 #ifdef SQLITE_OMIT_PRAGMA
12072 "OMIT_PRAGMA",
12073 #endif
12074 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12075 "OMIT_PROGRESS_CALLBACK",
12076 #endif
12077 #ifdef SQLITE_OMIT_QUICKBALANCE
12078 "OMIT_QUICKBALANCE",
12079 #endif
12080 #ifdef SQLITE_OMIT_REINDEX
12081 "OMIT_REINDEX",
12082 #endif
12083 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12084 "OMIT_SCHEMA_PRAGMAS",
12085 #endif
12086 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12087 "OMIT_SCHEMA_VERSION_PRAGMAS",
12088 #endif
12089 #ifdef SQLITE_OMIT_SHARED_CACHE
12090 "OMIT_SHARED_CACHE",
12091 #endif
12092 #ifdef SQLITE_OMIT_SUBQUERY
12093 "OMIT_SUBQUERY",
12094 #endif
12095 #ifdef SQLITE_OMIT_TCL_VARIABLE
12096 "OMIT_TCL_VARIABLE",
12097 #endif
12098 #ifdef SQLITE_OMIT_TEMPDB
12099 "OMIT_TEMPDB",
12100 #endif
12101 #ifdef SQLITE_OMIT_TRACE
12102 "OMIT_TRACE",
12103 #endif
12104 #ifdef SQLITE_OMIT_TRIGGER
12105 "OMIT_TRIGGER",
12106 #endif
12107 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12108 "OMIT_TRUNCATE_OPTIMIZATION",
12109 #endif
12110 #ifdef SQLITE_OMIT_UTF16
12111 "OMIT_UTF16",
12112 #endif
12113 #ifdef SQLITE_OMIT_VACUUM
12114 "OMIT_VACUUM",
12115 #endif
12116 #ifdef SQLITE_OMIT_VIEW
12117 "OMIT_VIEW",
12118 #endif
12119 #ifdef SQLITE_OMIT_VIRTUALTABLE
12120 "OMIT_VIRTUALTABLE",
12121 #endif
12122 #ifdef SQLITE_OMIT_WAL
12123 "OMIT_WAL",
12124 #endif
12125 #ifdef SQLITE_OMIT_WSD
12126 "OMIT_WSD",
12127 #endif
12128 #ifdef SQLITE_OMIT_XFER_OPT
12129 "OMIT_XFER_OPT",
12130 #endif
12131 #ifdef SQLITE_PERFORMANCE_TRACE
12132 "PERFORMANCE_TRACE",
12133 #endif
12134 #ifdef SQLITE_PROXY_DEBUG
12135 "PROXY_DEBUG",
12136 #endif
12137 #ifdef SQLITE_SECURE_DELETE
12138 "SECURE_DELETE",
12139 #endif
12140 #ifdef SQLITE_SMALL_STACK
12141 "SMALL_STACK",
12142 #endif
12143 #ifdef SQLITE_SOUNDEX
12144 "SOUNDEX",
12145 #endif
12146 #ifdef SQLITE_TCL
12147 "TCL",
12148 #endif
12149 #ifdef SQLITE_TEMP_STORE
12150 "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12151 #endif
12152 #ifdef SQLITE_TEST
12153 "TEST",
12154 #endif
12155 #ifdef SQLITE_THREADSAFE
12156 "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12157 #endif
12158 #ifdef SQLITE_USE_ALLOCA
12159 "USE_ALLOCA",
12160 #endif
12161 #ifdef SQLITE_ZERO_MALLOC
12162 "ZERO_MALLOC"
12163 #endif
12167 ** Given the name of a compile-time option, return true if that option
12168 ** was used and false if not.
12170 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12171 ** is not required for a match.
12173 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12174 int i, n;
12175 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12176 n = sqlite3Strlen30(zOptName);
12178 /* Since ArraySize(azCompileOpt) is normally in single digits, a
12179 ** linear search is adequate. No need for a binary search. */
12180 for(i=0; i<ArraySize(azCompileOpt); i++){
12181 if( (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12182 && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12184 return 0;
12188 ** Return the N-th compile-time option string. If N is out of range,
12189 ** return a NULL pointer.
12191 SQLITE_API const char *sqlite3_compileoption_get(int N){
12192 if( N>=0 && N<ArraySize(azCompileOpt) ){
12193 return azCompileOpt[N];
12195 return 0;
12198 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12200 /************** End of ctime.c ***********************************************/
12201 /************** Begin file status.c ******************************************/
12203 ** 2008 June 18
12205 ** The author disclaims copyright to this source code. In place of
12206 ** a legal notice, here is a blessing:
12208 ** May you do good and not evil.
12209 ** May you find forgiveness for yourself and forgive others.
12210 ** May you share freely, never taking more than you give.
12212 *************************************************************************
12214 ** This module implements the sqlite3_status() interface and related
12215 ** functionality.
12217 /************** Include vdbeInt.h in the middle of status.c ******************/
12218 /************** Begin file vdbeInt.h *****************************************/
12220 ** 2003 September 6
12222 ** The author disclaims copyright to this source code. In place of
12223 ** a legal notice, here is a blessing:
12225 ** May you do good and not evil.
12226 ** May you find forgiveness for yourself and forgive others.
12227 ** May you share freely, never taking more than you give.
12229 *************************************************************************
12230 ** This is the header file for information that is private to the
12231 ** VDBE. This information used to all be at the top of the single
12232 ** source code file "vdbe.c". When that file became too big (over
12233 ** 6000 lines long) it was split up into several smaller files and
12234 ** this header information was factored out.
12236 #ifndef _VDBEINT_H_
12237 #define _VDBEINT_H_
12240 ** SQL is translated into a sequence of instructions to be
12241 ** executed by a virtual machine. Each instruction is an instance
12242 ** of the following structure.
12244 typedef struct VdbeOp Op;
12247 ** Boolean values
12249 typedef unsigned char Bool;
12252 ** A cursor is a pointer into a single BTree within a database file.
12253 ** The cursor can seek to a BTree entry with a particular key, or
12254 ** loop over all entries of the Btree. You can also insert new BTree
12255 ** entries or retrieve the key or data from the entry that the cursor
12256 ** is currently pointing to.
12258 ** Every cursor that the virtual machine has open is represented by an
12259 ** instance of the following structure.
12261 struct VdbeCursor {
12262 BtCursor *pCursor; /* The cursor structure of the backend */
12263 Btree *pBt; /* Separate file holding temporary table */
12264 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
12265 int iDb; /* Index of cursor database in db->aDb[] (or -1) */
12266 int pseudoTableReg; /* Register holding pseudotable content. */
12267 int nField; /* Number of fields in the header */
12268 Bool zeroed; /* True if zeroed out and ready for reuse */
12269 Bool rowidIsValid; /* True if lastRowid is valid */
12270 Bool atFirst; /* True if pointing to first entry */
12271 Bool useRandomRowid; /* Generate new record numbers semi-randomly */
12272 Bool nullRow; /* True if pointing to a row with no data */
12273 Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
12274 Bool isTable; /* True if a table requiring integer keys */
12275 Bool isIndex; /* True if an index containing keys only - no data */
12276 Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
12277 sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
12278 const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
12279 i64 seqCount; /* Sequence counter */
12280 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
12281 i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
12283 /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
12284 ** OP_IsUnique opcode on this cursor. */
12285 int seekResult;
12287 /* Cached information about the header for the data record that the
12288 ** cursor is currently pointing to. Only valid if cacheStatus matches
12289 ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
12290 ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12291 ** the cache is out of date.
12293 ** aRow might point to (ephemeral) data for the current row, or it might
12294 ** be NULL.
12296 u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
12297 int payloadSize; /* Total number of bytes in the record */
12298 u32 *aType; /* Type values for all entries in the record */
12299 u32 *aOffset; /* Cached offsets to the start of each columns data */
12300 u8 *aRow; /* Data for the current row, if all on one page */
12302 typedef struct VdbeCursor VdbeCursor;
12305 ** When a sub-program is executed (OP_Program), a structure of this type
12306 ** is allocated to store the current value of the program counter, as
12307 ** well as the current memory cell array and various other frame specific
12308 ** values stored in the Vdbe struct. When the sub-program is finished,
12309 ** these values are copied back to the Vdbe from the VdbeFrame structure,
12310 ** restoring the state of the VM to as it was before the sub-program
12311 ** began executing.
12313 ** The memory for a VdbeFrame object is allocated and managed by a memory
12314 ** cell in the parent (calling) frame. When the memory cell is deleted or
12315 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12316 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12317 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12318 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
12319 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12320 ** child frame are released.
12322 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12323 ** set to NULL if the currently executing frame is the main program.
12325 typedef struct VdbeFrame VdbeFrame;
12326 struct VdbeFrame {
12327 Vdbe *v; /* VM this frame belongs to */
12328 int pc; /* Program Counter in parent (calling) frame */
12329 Op *aOp; /* Program instructions for parent frame */
12330 int nOp; /* Size of aOp array */
12331 Mem *aMem; /* Array of memory cells for parent frame */
12332 int nMem; /* Number of entries in aMem */
12333 VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
12334 u16 nCursor; /* Number of entries in apCsr */
12335 void *token; /* Copy of SubProgram.token */
12336 int nChildMem; /* Number of memory cells for child frame */
12337 int nChildCsr; /* Number of cursors for child frame */
12338 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
12339 int nChange; /* Statement changes (Vdbe.nChanges) */
12340 VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
12343 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12346 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12348 #define CACHE_STALE 0
12351 ** Internally, the vdbe manipulates nearly all SQL values as Mem
12352 ** structures. Each Mem struct may cache multiple representations (string,
12353 ** integer etc.) of the same value.
12355 struct Mem {
12356 sqlite3 *db; /* The associated database connection */
12357 char *z; /* String or BLOB value */
12358 double r; /* Real value */
12359 union {
12360 i64 i; /* Integer value used when MEM_Int is set in flags */
12361 int nZero; /* Used when bit MEM_Zero is set in flags */
12362 FuncDef *pDef; /* Used only when flags==MEM_Agg */
12363 RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
12364 VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
12365 } u;
12366 int n; /* Number of characters in string value, excluding '\0' */
12367 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12368 u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12369 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12370 #ifdef SQLITE_DEBUG
12371 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
12372 void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
12373 #endif
12374 void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
12375 char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
12378 /* One or more of the following flags are set to indicate the validOK
12379 ** representations of the value stored in the Mem struct.
12381 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
12382 ** No other flags may be set in this case.
12384 ** If the MEM_Str flag is set then Mem.z points at a string representation.
12385 ** Usually this is encoded in the same unicode encoding as the main
12386 ** database (see below for exceptions). If the MEM_Term flag is also
12387 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
12388 ** flags may coexist with the MEM_Str flag.
12390 #define MEM_Null 0x0001 /* Value is NULL */
12391 #define MEM_Str 0x0002 /* Value is a string */
12392 #define MEM_Int 0x0004 /* Value is an integer */
12393 #define MEM_Real 0x0008 /* Value is a real number */
12394 #define MEM_Blob 0x0010 /* Value is a BLOB */
12395 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
12396 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
12397 #define MEM_Invalid 0x0080 /* Value is undefined */
12398 #define MEM_TypeMask 0x00ff /* Mask of type bits */
12400 /* Whenever Mem contains a valid string or blob representation, one of
12401 ** the following flags must be set to determine the memory management
12402 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
12403 ** string is \000 or \u0000 terminated
12405 #define MEM_Term 0x0200 /* String rep is nul terminated */
12406 #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
12407 #define MEM_Static 0x0800 /* Mem.z points to a static string */
12408 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
12409 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
12410 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
12411 #ifdef SQLITE_OMIT_INCRBLOB
12412 #undef MEM_Zero
12413 #define MEM_Zero 0x0000
12414 #endif
12417 ** Clear any existing type flags from a Mem and replace them with f
12419 #define MemSetTypeFlag(p, f) \
12420 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12423 ** Return true if a memory cell is not marked as invalid. This macro
12424 ** is for use inside assert() statements only.
12426 #ifdef SQLITE_DEBUG
12427 #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
12428 #endif
12431 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12432 ** additional information about auxiliary information bound to arguments
12433 ** of the function. This is used to implement the sqlite3_get_auxdata()
12434 ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
12435 ** that can be associated with a constant argument to a function. This
12436 ** allows functions such as "regexp" to compile their constant regular
12437 ** expression argument once and reused the compiled code for multiple
12438 ** invocations.
12440 struct VdbeFunc {
12441 FuncDef *pFunc; /* The definition of the function */
12442 int nAux; /* Number of entries allocated for apAux[] */
12443 struct AuxData {
12444 void *pAux; /* Aux data for the i-th argument */
12445 void (*xDelete)(void *); /* Destructor for the aux data */
12446 } apAux[1]; /* One slot for each function argument */
12450 ** The "context" argument for a installable function. A pointer to an
12451 ** instance of this structure is the first argument to the routines used
12452 ** implement the SQL functions.
12454 ** There is a typedef for this structure in sqlite.h. So all routines,
12455 ** even the public interface to SQLite, can use a pointer to this structure.
12456 ** But this file is the only place where the internal details of this
12457 ** structure are known.
12459 ** This structure is defined inside of vdbeInt.h because it uses substructures
12460 ** (Mem) which are only defined there.
12462 struct sqlite3_context {
12463 FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
12464 VdbeFunc *pVdbeFunc; /* Auxilary data, if created. */
12465 Mem s; /* The return value is stored here */
12466 Mem *pMem; /* Memory cell used to store aggregate context */
12467 int isError; /* Error code returned by the function. */
12468 CollSeq *pColl; /* Collating sequence */
12472 ** An instance of the virtual machine. This structure contains the complete
12473 ** state of the virtual machine.
12475 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
12476 ** is really a pointer to an instance of this structure.
12478 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12479 ** any virtual table method invocations made by the vdbe program. It is
12480 ** set to 2 for xDestroy method calls and 1 for all other methods. This
12481 ** variable is used for two purposes: to allow xDestroy methods to execute
12482 ** "DROP TABLE" statements and to prevent some nasty side effects of
12483 ** malloc failure when SQLite is invoked recursively by a virtual table
12484 ** method function.
12486 struct Vdbe {
12487 sqlite3 *db; /* The database connection that owns this statement */
12488 Op *aOp; /* Space to hold the virtual machine's program */
12489 Mem *aMem; /* The memory locations */
12490 Mem **apArg; /* Arguments to currently executing user function */
12491 Mem *aColName; /* Column names to return */
12492 Mem *pResultSet; /* Pointer to an array of results */
12493 int nMem; /* Number of memory locations currently allocated */
12494 int nOp; /* Number of instructions in the program */
12495 int nOpAlloc; /* Number of slots allocated for aOp[] */
12496 int nLabel; /* Number of labels used */
12497 int nLabelAlloc; /* Number of slots allocated in aLabel[] */
12498 int *aLabel; /* Space to hold the labels */
12499 u16 nResColumn; /* Number of columns in one row of the result set */
12500 u16 nCursor; /* Number of slots in apCsr[] */
12501 u32 magic; /* Magic number for sanity checking */
12502 char *zErrMsg; /* Error message written here */
12503 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
12504 VdbeCursor **apCsr; /* One element of this array for each open cursor */
12505 Mem *aVar; /* Values for the OP_Variable opcode. */
12506 char **azVar; /* Name of variables */
12507 ynVar nVar; /* Number of entries in aVar[] */
12508 u32 cacheCtr; /* VdbeCursor row cache generation counter */
12509 int pc; /* The program counter */
12510 int rc; /* Value to return */
12511 u8 errorAction; /* Recovery action to do in case of an error */
12512 u8 okVar; /* True if azVar[] has been initialized */
12513 u8 explain; /* True if EXPLAIN present on SQL command */
12514 u8 changeCntOn; /* True to update the change-counter */
12515 u8 expired; /* True if the VM needs to be recompiled */
12516 u8 runOnlyOnce; /* Automatically expire on reset */
12517 u8 minWriteFileFormat; /* Minimum file format for writable database files */
12518 u8 inVtabMethod; /* See comments above */
12519 u8 usesStmtJournal; /* True if uses a statement journal */
12520 u8 readOnly; /* True for read-only statements */
12521 u8 isPrepareV2; /* True if prepared with prepare_v2() */
12522 int nChange; /* Number of db changes made since last reset */
12523 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
12524 yDbMask lockMask; /* Subset of btreeMask that requires a lock */
12525 int iStatement; /* Statement number (or 0 if has not opened stmt) */
12526 int aCounter[3]; /* Counters used by sqlite3_stmt_status() */
12527 #ifndef SQLITE_OMIT_TRACE
12528 i64 startTime; /* Time when query started - used for profiling */
12529 #endif
12530 i64 nFkConstraint; /* Number of imm. FK constraints this VM */
12531 i64 nStmtDefCons; /* Number of def. constraints when stmt started */
12532 char *zSql; /* Text of the SQL statement that generated this */
12533 void *pFree; /* Free this when deleting the vdbe */
12534 #ifdef SQLITE_DEBUG
12535 FILE *trace; /* Write an execution trace here, if not NULL */
12536 #endif
12537 VdbeFrame *pFrame; /* Parent frame */
12538 VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
12539 int nFrame; /* Number of frames in pFrame list */
12540 u32 expmask; /* Binding to these vars invalidates VM */
12541 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
12545 ** The following are allowed values for Vdbe.magic
12547 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
12548 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
12549 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
12550 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
12553 ** Function prototypes
12555 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
12556 void sqliteVdbePopStack(Vdbe*,int);
12557 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
12558 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12559 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12560 #endif
12561 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
12562 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12563 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12564 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12565 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12567 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12568 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
12569 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
12570 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12571 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12572 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12573 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12574 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12575 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12576 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12577 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12578 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
12579 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12580 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12581 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12582 #ifdef SQLITE_OMIT_FLOATING_POINT
12583 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
12584 #else
12585 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
12586 #endif
12587 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12588 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12589 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
12590 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12591 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12592 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12593 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12594 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12595 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12596 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12597 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12598 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12599 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12600 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12601 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12602 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12603 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12604 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12605 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12606 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12607 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12609 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
12610 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
12611 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
12612 #else
12613 # define sqlite3VdbeEnter(X)
12614 # define sqlite3VdbeLeave(X)
12615 #endif
12617 #ifdef SQLITE_DEBUG
12618 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12619 #endif
12621 #ifndef SQLITE_OMIT_FOREIGN_KEY
12622 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12623 #else
12624 # define sqlite3VdbeCheckFk(p,i) 0
12625 #endif
12627 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12628 #ifdef SQLITE_DEBUG
12629 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
12630 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12631 #endif
12632 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12634 #ifndef SQLITE_OMIT_INCRBLOB
12635 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
12636 #else
12637 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12638 #endif
12640 #endif /* !defined(_VDBEINT_H_) */
12642 /************** End of vdbeInt.h *********************************************/
12643 /************** Continuing where we left off in status.c *********************/
12646 ** Variables in which to record status information.
12648 typedef struct sqlite3StatType sqlite3StatType;
12649 static SQLITE_WSD struct sqlite3StatType {
12650 int nowValue[10]; /* Current value */
12651 int mxValue[10]; /* Maximum value */
12652 } sqlite3Stat = { {0,}, {0,} };
12655 /* The "wsdStat" macro will resolve to the status information
12656 ** state vector. If writable static data is unsupported on the target,
12657 ** we have to locate the state vector at run-time. In the more common
12658 ** case where writable static data is supported, wsdStat can refer directly
12659 ** to the "sqlite3Stat" state vector declared above.
12661 #ifdef SQLITE_OMIT_WSD
12662 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
12663 # define wsdStat x[0]
12664 #else
12665 # define wsdStatInit
12666 # define wsdStat sqlite3Stat
12667 #endif
12670 ** Return the current value of a status parameter.
12672 SQLITE_PRIVATE int sqlite3StatusValue(int op){
12673 wsdStatInit;
12674 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12675 return wsdStat.nowValue[op];
12679 ** Add N to the value of a status record. It is assumed that the
12680 ** caller holds appropriate locks.
12682 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
12683 wsdStatInit;
12684 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12685 wsdStat.nowValue[op] += N;
12686 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12687 wsdStat.mxValue[op] = wsdStat.nowValue[op];
12692 ** Set the value of a status to X.
12694 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
12695 wsdStatInit;
12696 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12697 wsdStat.nowValue[op] = X;
12698 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12699 wsdStat.mxValue[op] = wsdStat.nowValue[op];
12704 ** Query status information.
12706 ** This implementation assumes that reading or writing an aligned
12707 ** 32-bit integer is an atomic operation. If that assumption is not true,
12708 ** then this routine is not threadsafe.
12710 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
12711 wsdStatInit;
12712 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
12713 return SQLITE_MISUSE_BKPT;
12715 *pCurrent = wsdStat.nowValue[op];
12716 *pHighwater = wsdStat.mxValue[op];
12717 if( resetFlag ){
12718 wsdStat.mxValue[op] = wsdStat.nowValue[op];
12720 return SQLITE_OK;
12724 ** Query status information for a single database connection
12726 SQLITE_API int sqlite3_db_status(
12727 sqlite3 *db, /* The database connection whose status is desired */
12728 int op, /* Status verb */
12729 int *pCurrent, /* Write current value here */
12730 int *pHighwater, /* Write high-water mark here */
12731 int resetFlag /* Reset high-water mark if true */
12733 int rc = SQLITE_OK; /* Return code */
12734 sqlite3_mutex_enter(db->mutex);
12735 switch( op ){
12736 case SQLITE_DBSTATUS_LOOKASIDE_USED: {
12737 *pCurrent = db->lookaside.nOut;
12738 *pHighwater = db->lookaside.mxOut;
12739 if( resetFlag ){
12740 db->lookaside.mxOut = db->lookaside.nOut;
12742 break;
12745 case SQLITE_DBSTATUS_LOOKASIDE_HIT:
12746 case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
12747 case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
12748 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
12749 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
12750 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
12751 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
12752 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
12753 *pCurrent = 0;
12754 *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
12755 if( resetFlag ){
12756 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
12758 break;
12762 ** Return an approximation for the amount of memory currently used
12763 ** by all pagers associated with the given database connection. The
12764 ** highwater mark is meaningless and is returned as zero.
12766 case SQLITE_DBSTATUS_CACHE_USED: {
12767 int totalUsed = 0;
12768 int i;
12769 sqlite3BtreeEnterAll(db);
12770 for(i=0; i<db->nDb; i++){
12771 Btree *pBt = db->aDb[i].pBt;
12772 if( pBt ){
12773 Pager *pPager = sqlite3BtreePager(pBt);
12774 totalUsed += sqlite3PagerMemUsed(pPager);
12777 sqlite3BtreeLeaveAll(db);
12778 *pCurrent = totalUsed;
12779 *pHighwater = 0;
12780 break;
12784 ** *pCurrent gets an accurate estimate of the amount of memory used
12785 ** to store the schema for all databases (main, temp, and any ATTACHed
12786 ** databases. *pHighwater is set to zero.
12788 case SQLITE_DBSTATUS_SCHEMA_USED: {
12789 int i; /* Used to iterate through schemas */
12790 int nByte = 0; /* Used to accumulate return value */
12792 sqlite3BtreeEnterAll(db);
12793 db->pnBytesFreed = &nByte;
12794 for(i=0; i<db->nDb; i++){
12795 Schema *pSchema = db->aDb[i].pSchema;
12796 if( ALWAYS(pSchema!=0) ){
12797 HashElem *p;
12799 nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
12800 pSchema->tblHash.count
12801 + pSchema->trigHash.count
12802 + pSchema->idxHash.count
12803 + pSchema->fkeyHash.count
12805 nByte += sqlite3MallocSize(pSchema->tblHash.ht);
12806 nByte += sqlite3MallocSize(pSchema->trigHash.ht);
12807 nByte += sqlite3MallocSize(pSchema->idxHash.ht);
12808 nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
12810 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
12811 sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
12813 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
12814 sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
12818 db->pnBytesFreed = 0;
12819 sqlite3BtreeLeaveAll(db);
12821 *pHighwater = 0;
12822 *pCurrent = nByte;
12823 break;
12827 ** *pCurrent gets an accurate estimate of the amount of memory used
12828 ** to store all prepared statements.
12829 ** *pHighwater is set to zero.
12831 case SQLITE_DBSTATUS_STMT_USED: {
12832 struct Vdbe *pVdbe; /* Used to iterate through VMs */
12833 int nByte = 0; /* Used to accumulate return value */
12835 db->pnBytesFreed = &nByte;
12836 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
12837 sqlite3VdbeDeleteObject(db, pVdbe);
12839 db->pnBytesFreed = 0;
12841 *pHighwater = 0;
12842 *pCurrent = nByte;
12844 break;
12847 default: {
12848 rc = SQLITE_ERROR;
12851 sqlite3_mutex_leave(db->mutex);
12852 return rc;
12855 /************** End of status.c **********************************************/
12856 /************** Begin file date.c ********************************************/
12858 ** 2003 October 31
12860 ** The author disclaims copyright to this source code. In place of
12861 ** a legal notice, here is a blessing:
12863 ** May you do good and not evil.
12864 ** May you find forgiveness for yourself and forgive others.
12865 ** May you share freely, never taking more than you give.
12867 *************************************************************************
12868 ** This file contains the C functions that implement date and time
12869 ** functions for SQLite.
12871 ** There is only one exported symbol in this file - the function
12872 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
12873 ** All other code has file scope.
12875 ** SQLite processes all times and dates as Julian Day numbers. The
12876 ** dates and times are stored as the number of days since noon
12877 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
12878 ** calendar system.
12880 ** 1970-01-01 00:00:00 is JD 2440587.5
12881 ** 2000-01-01 00:00:00 is JD 2451544.5
12883 ** This implemention requires years to be expressed as a 4-digit number
12884 ** which means that only dates between 0000-01-01 and 9999-12-31 can
12885 ** be represented, even though julian day numbers allow a much wider
12886 ** range of dates.
12888 ** The Gregorian calendar system is used for all dates and times,
12889 ** even those that predate the Gregorian calendar. Historians usually
12890 ** use the Julian calendar for dates prior to 1582-10-15 and for some
12891 ** dates afterwards, depending on locale. Beware of this difference.
12893 ** The conversion algorithms are implemented based on descriptions
12894 ** in the following text:
12896 ** Jean Meeus
12897 ** Astronomical Algorithms, 2nd Edition, 1998
12898 ** ISBM 0-943396-61-1
12899 ** Willmann-Bell, Inc
12900 ** Richmond, Virginia (USA)
12902 #include <time.h>
12904 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12907 ** On recent Windows platforms, the localtime_s() function is available
12908 ** as part of the "Secure CRT". It is essentially equivalent to
12909 ** localtime_r() available under most POSIX platforms, except that the
12910 ** order of the parameters is reversed.
12912 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
12914 ** If the user has not indicated to use localtime_r() or localtime_s()
12915 ** already, check for an MSVC build environment that provides
12916 ** localtime_s().
12918 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
12919 defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
12920 #define HAVE_LOCALTIME_S 1
12921 #endif
12924 ** A structure for holding a single date and time.
12926 typedef struct DateTime DateTime;
12927 struct DateTime {
12928 sqlite3_int64 iJD; /* The julian day number times 86400000 */
12929 int Y, M, D; /* Year, month, and day */
12930 int h, m; /* Hour and minutes */
12931 int tz; /* Timezone offset in minutes */
12932 double s; /* Seconds */
12933 char validYMD; /* True (1) if Y,M,D are valid */
12934 char validHMS; /* True (1) if h,m,s are valid */
12935 char validJD; /* True (1) if iJD is valid */
12936 char validTZ; /* True (1) if tz is valid */
12941 ** Convert zDate into one or more integers. Additional arguments
12942 ** come in groups of 5 as follows:
12944 ** N number of digits in the integer
12945 ** min minimum allowed value of the integer
12946 ** max maximum allowed value of the integer
12947 ** nextC first character after the integer
12948 ** pVal where to write the integers value.
12950 ** Conversions continue until one with nextC==0 is encountered.
12951 ** The function returns the number of successful conversions.
12953 static int getDigits(const char *zDate, ...){
12954 va_list ap;
12955 int val;
12956 int N;
12957 int min;
12958 int max;
12959 int nextC;
12960 int *pVal;
12961 int cnt = 0;
12962 va_start(ap, zDate);
12964 N = va_arg(ap, int);
12965 min = va_arg(ap, int);
12966 max = va_arg(ap, int);
12967 nextC = va_arg(ap, int);
12968 pVal = va_arg(ap, int*);
12969 val = 0;
12970 while( N-- ){
12971 if( !sqlite3Isdigit(*zDate) ){
12972 goto end_getDigits;
12974 val = val*10 + *zDate - '0';
12975 zDate++;
12977 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
12978 goto end_getDigits;
12980 *pVal = val;
12981 zDate++;
12982 cnt++;
12983 }while( nextC );
12984 end_getDigits:
12985 va_end(ap);
12986 return cnt;
12990 ** Parse a timezone extension on the end of a date-time.
12991 ** The extension is of the form:
12993 ** (+/-)HH:MM
12995 ** Or the "zulu" notation:
12997 ** Z
12999 ** If the parse is successful, write the number of minutes
13000 ** of change in p->tz and return 0. If a parser error occurs,
13001 ** return non-zero.
13003 ** A missing specifier is not considered an error.
13005 static int parseTimezone(const char *zDate, DateTime *p){
13006 int sgn = 0;
13007 int nHr, nMn;
13008 int c;
13009 while( sqlite3Isspace(*zDate) ){ zDate++; }
13010 p->tz = 0;
13011 c = *zDate;
13012 if( c=='-' ){
13013 sgn = -1;
13014 }else if( c=='+' ){
13015 sgn = +1;
13016 }else if( c=='Z' || c=='z' ){
13017 zDate++;
13018 goto zulu_time;
13019 }else{
13020 return c!=0;
13022 zDate++;
13023 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13024 return 1;
13026 zDate += 5;
13027 p->tz = sgn*(nMn + nHr*60);
13028 zulu_time:
13029 while( sqlite3Isspace(*zDate) ){ zDate++; }
13030 return *zDate!=0;
13034 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13035 ** The HH, MM, and SS must each be exactly 2 digits. The
13036 ** fractional seconds FFFF can be one or more digits.
13038 ** Return 1 if there is a parsing error and 0 on success.
13040 static int parseHhMmSs(const char *zDate, DateTime *p){
13041 int h, m, s;
13042 double ms = 0.0;
13043 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13044 return 1;
13046 zDate += 5;
13047 if( *zDate==':' ){
13048 zDate++;
13049 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13050 return 1;
13052 zDate += 2;
13053 if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13054 double rScale = 1.0;
13055 zDate++;
13056 while( sqlite3Isdigit(*zDate) ){
13057 ms = ms*10.0 + *zDate - '0';
13058 rScale *= 10.0;
13059 zDate++;
13061 ms /= rScale;
13063 }else{
13064 s = 0;
13066 p->validJD = 0;
13067 p->validHMS = 1;
13068 p->h = h;
13069 p->m = m;
13070 p->s = s + ms;
13071 if( parseTimezone(zDate, p) ) return 1;
13072 p->validTZ = (p->tz!=0)?1:0;
13073 return 0;
13077 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
13078 ** that the YYYY-MM-DD is according to the Gregorian calendar.
13080 ** Reference: Meeus page 61
13082 static void computeJD(DateTime *p){
13083 int Y, M, D, A, B, X1, X2;
13085 if( p->validJD ) return;
13086 if( p->validYMD ){
13087 Y = p->Y;
13088 M = p->M;
13089 D = p->D;
13090 }else{
13091 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
13092 M = 1;
13093 D = 1;
13095 if( M<=2 ){
13096 Y--;
13097 M += 12;
13099 A = Y/100;
13100 B = 2 - A + (A/4);
13101 X1 = 36525*(Y+4716)/100;
13102 X2 = 306001*(M+1)/10000;
13103 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13104 p->validJD = 1;
13105 if( p->validHMS ){
13106 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13107 if( p->validTZ ){
13108 p->iJD -= p->tz*60000;
13109 p->validYMD = 0;
13110 p->validHMS = 0;
13111 p->validTZ = 0;
13117 ** Parse dates of the form
13119 ** YYYY-MM-DD HH:MM:SS.FFF
13120 ** YYYY-MM-DD HH:MM:SS
13121 ** YYYY-MM-DD HH:MM
13122 ** YYYY-MM-DD
13124 ** Write the result into the DateTime structure and return 0
13125 ** on success and 1 if the input string is not a well-formed
13126 ** date.
13128 static int parseYyyyMmDd(const char *zDate, DateTime *p){
13129 int Y, M, D, neg;
13131 if( zDate[0]=='-' ){
13132 zDate++;
13133 neg = 1;
13134 }else{
13135 neg = 0;
13137 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13138 return 1;
13140 zDate += 10;
13141 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13142 if( parseHhMmSs(zDate, p)==0 ){
13143 /* We got the time */
13144 }else if( *zDate==0 ){
13145 p->validHMS = 0;
13146 }else{
13147 return 1;
13149 p->validJD = 0;
13150 p->validYMD = 1;
13151 p->Y = neg ? -Y : Y;
13152 p->M = M;
13153 p->D = D;
13154 if( p->validTZ ){
13155 computeJD(p);
13157 return 0;
13161 ** Set the time to the current time reported by the VFS
13163 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13164 sqlite3 *db = sqlite3_context_db_handle(context);
13165 sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
13166 p->validJD = 1;
13170 ** Attempt to parse the given string into a Julian Day Number. Return
13171 ** the number of errors.
13173 ** The following are acceptable forms for the input string:
13175 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
13176 ** DDDD.DD
13177 ** now
13179 ** In the first form, the +/-HH:MM is always optional. The fractional
13180 ** seconds extension (the ".FFF") is optional. The seconds portion
13181 ** (":SS.FFF") is option. The year and date can be omitted as long
13182 ** as there is a time string. The time string can be omitted as long
13183 ** as there is a year and date.
13185 static int parseDateOrTime(
13186 sqlite3_context *context,
13187 const char *zDate,
13188 DateTime *p
13190 double r;
13191 if( parseYyyyMmDd(zDate,p)==0 ){
13192 return 0;
13193 }else if( parseHhMmSs(zDate, p)==0 ){
13194 return 0;
13195 }else if( sqlite3StrICmp(zDate,"now")==0){
13196 setDateTimeToCurrent(context, p);
13197 return 0;
13198 }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13199 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13200 p->validJD = 1;
13201 return 0;
13203 return 1;
13207 ** Compute the Year, Month, and Day from the julian day number.
13209 static void computeYMD(DateTime *p){
13210 int Z, A, B, C, D, E, X1;
13211 if( p->validYMD ) return;
13212 if( !p->validJD ){
13213 p->Y = 2000;
13214 p->M = 1;
13215 p->D = 1;
13216 }else{
13217 Z = (int)((p->iJD + 43200000)/86400000);
13218 A = (int)((Z - 1867216.25)/36524.25);
13219 A = Z + 1 + A - (A/4);
13220 B = A + 1524;
13221 C = (int)((B - 122.1)/365.25);
13222 D = (36525*C)/100;
13223 E = (int)((B-D)/30.6001);
13224 X1 = (int)(30.6001*E);
13225 p->D = B - D - X1;
13226 p->M = E<14 ? E-1 : E-13;
13227 p->Y = p->M>2 ? C - 4716 : C - 4715;
13229 p->validYMD = 1;
13233 ** Compute the Hour, Minute, and Seconds from the julian day number.
13235 static void computeHMS(DateTime *p){
13236 int s;
13237 if( p->validHMS ) return;
13238 computeJD(p);
13239 s = (int)((p->iJD + 43200000) % 86400000);
13240 p->s = s/1000.0;
13241 s = (int)p->s;
13242 p->s -= s;
13243 p->h = s/3600;
13244 s -= p->h*3600;
13245 p->m = s/60;
13246 p->s += s - p->m*60;
13247 p->validHMS = 1;
13251 ** Compute both YMD and HMS
13253 static void computeYMD_HMS(DateTime *p){
13254 computeYMD(p);
13255 computeHMS(p);
13259 ** Clear the YMD and HMS and the TZ
13261 static void clearYMD_HMS_TZ(DateTime *p){
13262 p->validYMD = 0;
13263 p->validHMS = 0;
13264 p->validTZ = 0;
13267 #ifndef SQLITE_OMIT_LOCALTIME
13269 ** Compute the difference (in milliseconds)
13270 ** between localtime and UTC (a.k.a. GMT)
13271 ** for the time value p where p is in UTC.
13273 static sqlite3_int64 localtimeOffset(DateTime *p){
13274 DateTime x, y;
13275 time_t t;
13276 x = *p;
13277 computeYMD_HMS(&x);
13278 if( x.Y<1971 || x.Y>=2038 ){
13279 x.Y = 2000;
13280 x.M = 1;
13281 x.D = 1;
13282 x.h = 0;
13283 x.m = 0;
13284 x.s = 0.0;
13285 } else {
13286 int s = (int)(x.s + 0.5);
13287 x.s = s;
13289 x.tz = 0;
13290 x.validJD = 0;
13291 computeJD(&x);
13292 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
13293 #ifdef HAVE_LOCALTIME_R
13295 struct tm sLocal;
13296 localtime_r(&t, &sLocal);
13297 y.Y = sLocal.tm_year + 1900;
13298 y.M = sLocal.tm_mon + 1;
13299 y.D = sLocal.tm_mday;
13300 y.h = sLocal.tm_hour;
13301 y.m = sLocal.tm_min;
13302 y.s = sLocal.tm_sec;
13304 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
13306 struct tm sLocal;
13307 localtime_s(&sLocal, &t);
13308 y.Y = sLocal.tm_year + 1900;
13309 y.M = sLocal.tm_mon + 1;
13310 y.D = sLocal.tm_mday;
13311 y.h = sLocal.tm_hour;
13312 y.m = sLocal.tm_min;
13313 y.s = sLocal.tm_sec;
13315 #else
13317 struct tm *pTm;
13318 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13319 pTm = localtime(&t);
13320 y.Y = pTm->tm_year + 1900;
13321 y.M = pTm->tm_mon + 1;
13322 y.D = pTm->tm_mday;
13323 y.h = pTm->tm_hour;
13324 y.m = pTm->tm_min;
13325 y.s = pTm->tm_sec;
13326 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13328 #endif
13329 y.validYMD = 1;
13330 y.validHMS = 1;
13331 y.validJD = 0;
13332 y.validTZ = 0;
13333 computeJD(&y);
13334 return y.iJD - x.iJD;
13336 #endif /* SQLITE_OMIT_LOCALTIME */
13339 ** Process a modifier to a date-time stamp. The modifiers are
13340 ** as follows:
13342 ** NNN days
13343 ** NNN hours
13344 ** NNN minutes
13345 ** NNN.NNNN seconds
13346 ** NNN months
13347 ** NNN years
13348 ** start of month
13349 ** start of year
13350 ** start of week
13351 ** start of day
13352 ** weekday N
13353 ** unixepoch
13354 ** localtime
13355 ** utc
13357 ** Return 0 on success and 1 if there is any kind of error.
13359 static int parseModifier(const char *zMod, DateTime *p){
13360 int rc = 1;
13361 int n;
13362 double r;
13363 char *z, zBuf[30];
13364 z = zBuf;
13365 for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
13366 z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
13368 z[n] = 0;
13369 switch( z[0] ){
13370 #ifndef SQLITE_OMIT_LOCALTIME
13371 case 'l': {
13372 /* localtime
13374 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
13375 ** show local time.
13377 if( strcmp(z, "localtime")==0 ){
13378 computeJD(p);
13379 p->iJD += localtimeOffset(p);
13380 clearYMD_HMS_TZ(p);
13381 rc = 0;
13383 break;
13385 #endif
13386 case 'u': {
13388 ** unixepoch
13390 ** Treat the current value of p->iJD as the number of
13391 ** seconds since 1970. Convert to a real julian day number.
13393 if( strcmp(z, "unixepoch")==0 && p->validJD ){
13394 p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
13395 clearYMD_HMS_TZ(p);
13396 rc = 0;
13398 #ifndef SQLITE_OMIT_LOCALTIME
13399 else if( strcmp(z, "utc")==0 ){
13400 sqlite3_int64 c1;
13401 computeJD(p);
13402 c1 = localtimeOffset(p);
13403 p->iJD -= c1;
13404 clearYMD_HMS_TZ(p);
13405 p->iJD += c1 - localtimeOffset(p);
13406 rc = 0;
13408 #endif
13409 break;
13411 case 'w': {
13413 ** weekday N
13415 ** Move the date to the same time on the next occurrence of
13416 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
13417 ** date is already on the appropriate weekday, this is a no-op.
13419 if( strncmp(z, "weekday ", 8)==0
13420 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
13421 && (n=(int)r)==r && n>=0 && r<7 ){
13422 sqlite3_int64 Z;
13423 computeYMD_HMS(p);
13424 p->validTZ = 0;
13425 p->validJD = 0;
13426 computeJD(p);
13427 Z = ((p->iJD + 129600000)/86400000) % 7;
13428 if( Z>n ) Z -= 7;
13429 p->iJD += (n - Z)*86400000;
13430 clearYMD_HMS_TZ(p);
13431 rc = 0;
13433 break;
13435 case 's': {
13437 ** start of TTTTT
13439 ** Move the date backwards to the beginning of the current day,
13440 ** or month or year.
13442 if( strncmp(z, "start of ", 9)!=0 ) break;
13443 z += 9;
13444 computeYMD(p);
13445 p->validHMS = 1;
13446 p->h = p->m = 0;
13447 p->s = 0.0;
13448 p->validTZ = 0;
13449 p->validJD = 0;
13450 if( strcmp(z,"month")==0 ){
13451 p->D = 1;
13452 rc = 0;
13453 }else if( strcmp(z,"year")==0 ){
13454 computeYMD(p);
13455 p->M = 1;
13456 p->D = 1;
13457 rc = 0;
13458 }else if( strcmp(z,"day")==0 ){
13459 rc = 0;
13461 break;
13463 case '+':
13464 case '-':
13465 case '0':
13466 case '1':
13467 case '2':
13468 case '3':
13469 case '4':
13470 case '5':
13471 case '6':
13472 case '7':
13473 case '8':
13474 case '9': {
13475 double rRounder;
13476 for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
13477 if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
13478 rc = 1;
13479 break;
13481 if( z[n]==':' ){
13482 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
13483 ** specified number of hours, minutes, seconds, and fractional seconds
13484 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
13485 ** omitted.
13487 const char *z2 = z;
13488 DateTime tx;
13489 sqlite3_int64 day;
13490 if( !sqlite3Isdigit(*z2) ) z2++;
13491 memset(&tx, 0, sizeof(tx));
13492 if( parseHhMmSs(z2, &tx) ) break;
13493 computeJD(&tx);
13494 tx.iJD -= 43200000;
13495 day = tx.iJD/86400000;
13496 tx.iJD -= day*86400000;
13497 if( z[0]=='-' ) tx.iJD = -tx.iJD;
13498 computeJD(p);
13499 clearYMD_HMS_TZ(p);
13500 p->iJD += tx.iJD;
13501 rc = 0;
13502 break;
13504 z += n;
13505 while( sqlite3Isspace(*z) ) z++;
13506 n = sqlite3Strlen30(z);
13507 if( n>10 || n<3 ) break;
13508 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
13509 computeJD(p);
13510 rc = 0;
13511 rRounder = r<0 ? -0.5 : +0.5;
13512 if( n==3 && strcmp(z,"day")==0 ){
13513 p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
13514 }else if( n==4 && strcmp(z,"hour")==0 ){
13515 p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
13516 }else if( n==6 && strcmp(z,"minute")==0 ){
13517 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
13518 }else if( n==6 && strcmp(z,"second")==0 ){
13519 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
13520 }else if( n==5 && strcmp(z,"month")==0 ){
13521 int x, y;
13522 computeYMD_HMS(p);
13523 p->M += (int)r;
13524 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
13525 p->Y += x;
13526 p->M -= x*12;
13527 p->validJD = 0;
13528 computeJD(p);
13529 y = (int)r;
13530 if( y!=r ){
13531 p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
13533 }else if( n==4 && strcmp(z,"year")==0 ){
13534 int y = (int)r;
13535 computeYMD_HMS(p);
13536 p->Y += y;
13537 p->validJD = 0;
13538 computeJD(p);
13539 if( y!=r ){
13540 p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
13542 }else{
13543 rc = 1;
13545 clearYMD_HMS_TZ(p);
13546 break;
13548 default: {
13549 break;
13552 return rc;
13556 ** Process time function arguments. argv[0] is a date-time stamp.
13557 ** argv[1] and following are modifiers. Parse them all and write
13558 ** the resulting time into the DateTime structure p. Return 0
13559 ** on success and 1 if there are any errors.
13561 ** If there are zero parameters (if even argv[0] is undefined)
13562 ** then assume a default value of "now" for argv[0].
13564 static int isDate(
13565 sqlite3_context *context,
13566 int argc,
13567 sqlite3_value **argv,
13568 DateTime *p
13570 int i;
13571 const unsigned char *z;
13572 int eType;
13573 memset(p, 0, sizeof(*p));
13574 if( argc==0 ){
13575 setDateTimeToCurrent(context, p);
13576 }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
13577 || eType==SQLITE_INTEGER ){
13578 p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
13579 p->validJD = 1;
13580 }else{
13581 z = sqlite3_value_text(argv[0]);
13582 if( !z || parseDateOrTime(context, (char*)z, p) ){
13583 return 1;
13586 for(i=1; i<argc; i++){
13587 if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
13588 return 1;
13591 return 0;
13596 ** The following routines implement the various date and time functions
13597 ** of SQLite.
13601 ** julianday( TIMESTRING, MOD, MOD, ...)
13603 ** Return the julian day number of the date specified in the arguments
13605 static void juliandayFunc(
13606 sqlite3_context *context,
13607 int argc,
13608 sqlite3_value **argv
13610 DateTime x;
13611 if( isDate(context, argc, argv, &x)==0 ){
13612 computeJD(&x);
13613 sqlite3_result_double(context, x.iJD/86400000.0);
13618 ** datetime( TIMESTRING, MOD, MOD, ...)
13620 ** Return YYYY-MM-DD HH:MM:SS
13622 static void datetimeFunc(
13623 sqlite3_context *context,
13624 int argc,
13625 sqlite3_value **argv
13627 DateTime x;
13628 if( isDate(context, argc, argv, &x)==0 ){
13629 char zBuf[100];
13630 computeYMD_HMS(&x);
13631 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
13632 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
13633 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13638 ** time( TIMESTRING, MOD, MOD, ...)
13640 ** Return HH:MM:SS
13642 static void timeFunc(
13643 sqlite3_context *context,
13644 int argc,
13645 sqlite3_value **argv
13647 DateTime x;
13648 if( isDate(context, argc, argv, &x)==0 ){
13649 char zBuf[100];
13650 computeHMS(&x);
13651 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
13652 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13657 ** date( TIMESTRING, MOD, MOD, ...)
13659 ** Return YYYY-MM-DD
13661 static void dateFunc(
13662 sqlite3_context *context,
13663 int argc,
13664 sqlite3_value **argv
13666 DateTime x;
13667 if( isDate(context, argc, argv, &x)==0 ){
13668 char zBuf[100];
13669 computeYMD(&x);
13670 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
13671 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13676 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
13678 ** Return a string described by FORMAT. Conversions as follows:
13680 ** %d day of month
13681 ** %f ** fractional seconds SS.SSS
13682 ** %H hour 00-24
13683 ** %j day of year 000-366
13684 ** %J ** Julian day number
13685 ** %m month 01-12
13686 ** %M minute 00-59
13687 ** %s seconds since 1970-01-01
13688 ** %S seconds 00-59
13689 ** %w day of week 0-6 sunday==0
13690 ** %W week of year 00-53
13691 ** %Y year 0000-9999
13692 ** %% %
13694 static void strftimeFunc(
13695 sqlite3_context *context,
13696 int argc,
13697 sqlite3_value **argv
13699 DateTime x;
13700 u64 n;
13701 size_t i,j;
13702 char *z;
13703 sqlite3 *db;
13704 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
13705 char zBuf[100];
13706 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
13707 db = sqlite3_context_db_handle(context);
13708 for(i=0, n=1; zFmt[i]; i++, n++){
13709 if( zFmt[i]=='%' ){
13710 switch( zFmt[i+1] ){
13711 case 'd':
13712 case 'H':
13713 case 'm':
13714 case 'M':
13715 case 'S':
13716 case 'W':
13717 n++;
13718 /* fall thru */
13719 case 'w':
13720 case '%':
13721 break;
13722 case 'f':
13723 n += 8;
13724 break;
13725 case 'j':
13726 n += 3;
13727 break;
13728 case 'Y':
13729 n += 8;
13730 break;
13731 case 's':
13732 case 'J':
13733 n += 50;
13734 break;
13735 default:
13736 return; /* ERROR. return a NULL */
13738 i++;
13741 testcase( n==sizeof(zBuf)-1 );
13742 testcase( n==sizeof(zBuf) );
13743 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
13744 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
13745 if( n<sizeof(zBuf) ){
13746 z = zBuf;
13747 }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
13748 sqlite3_result_error_toobig(context);
13749 return;
13750 }else{
13751 z = sqlite3DbMallocRaw(db, (int)n);
13752 if( z==0 ){
13753 sqlite3_result_error_nomem(context);
13754 return;
13757 computeJD(&x);
13758 computeYMD_HMS(&x);
13759 for(i=j=0; zFmt[i]; i++){
13760 if( zFmt[i]!='%' ){
13761 z[j++] = zFmt[i];
13762 }else{
13763 i++;
13764 switch( zFmt[i] ){
13765 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
13766 case 'f': {
13767 double s = x.s;
13768 if( s>59.999 ) s = 59.999;
13769 sqlite3_snprintf(7, &z[j],"%06.3f", s);
13770 j += sqlite3Strlen30(&z[j]);
13771 break;
13773 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
13774 case 'W': /* Fall thru */
13775 case 'j': {
13776 int nDay; /* Number of days since 1st day of year */
13777 DateTime y = x;
13778 y.validJD = 0;
13779 y.M = 1;
13780 y.D = 1;
13781 computeJD(&y);
13782 nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
13783 if( zFmt[i]=='W' ){
13784 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
13785 wd = (int)(((x.iJD+43200000)/86400000)%7);
13786 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
13787 j += 2;
13788 }else{
13789 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
13790 j += 3;
13792 break;
13794 case 'J': {
13795 sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
13796 j+=sqlite3Strlen30(&z[j]);
13797 break;
13799 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
13800 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
13801 case 's': {
13802 sqlite3_snprintf(30,&z[j],"%lld",
13803 (i64)(x.iJD/1000 - 21086676*(i64)10000));
13804 j += sqlite3Strlen30(&z[j]);
13805 break;
13807 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
13808 case 'w': {
13809 z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
13810 break;
13812 case 'Y': {
13813 sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
13814 break;
13816 default: z[j++] = '%'; break;
13820 z[j] = 0;
13821 sqlite3_result_text(context, z, -1,
13822 z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
13826 ** current_time()
13828 ** This function returns the same value as time('now').
13830 static void ctimeFunc(
13831 sqlite3_context *context,
13832 int NotUsed,
13833 sqlite3_value **NotUsed2
13835 UNUSED_PARAMETER2(NotUsed, NotUsed2);
13836 timeFunc(context, 0, 0);
13840 ** current_date()
13842 ** This function returns the same value as date('now').
13844 static void cdateFunc(
13845 sqlite3_context *context,
13846 int NotUsed,
13847 sqlite3_value **NotUsed2
13849 UNUSED_PARAMETER2(NotUsed, NotUsed2);
13850 dateFunc(context, 0, 0);
13854 ** current_timestamp()
13856 ** This function returns the same value as datetime('now').
13858 static void ctimestampFunc(
13859 sqlite3_context *context,
13860 int NotUsed,
13861 sqlite3_value **NotUsed2
13863 UNUSED_PARAMETER2(NotUsed, NotUsed2);
13864 datetimeFunc(context, 0, 0);
13866 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
13868 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13870 ** If the library is compiled to omit the full-scale date and time
13871 ** handling (to get a smaller binary), the following minimal version
13872 ** of the functions current_time(), current_date() and current_timestamp()
13873 ** are included instead. This is to support column declarations that
13874 ** include "DEFAULT CURRENT_TIME" etc.
13876 ** This function uses the C-library functions time(), gmtime()
13877 ** and strftime(). The format string to pass to strftime() is supplied
13878 ** as the user-data for the function.
13880 static void currentTimeFunc(
13881 sqlite3_context *context,
13882 int argc,
13883 sqlite3_value **argv
13885 time_t t;
13886 char *zFormat = (char *)sqlite3_user_data(context);
13887 sqlite3 *db;
13888 sqlite3_int64 iT;
13889 char zBuf[20];
13891 UNUSED_PARAMETER(argc);
13892 UNUSED_PARAMETER(argv);
13894 db = sqlite3_context_db_handle(context);
13895 sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
13896 t = iT/1000 - 10000*(sqlite3_int64)21086676;
13897 #ifdef HAVE_GMTIME_R
13899 struct tm sNow;
13900 gmtime_r(&t, &sNow);
13901 strftime(zBuf, 20, zFormat, &sNow);
13903 #else
13905 struct tm *pTm;
13906 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13907 pTm = gmtime(&t);
13908 strftime(zBuf, 20, zFormat, pTm);
13909 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13911 #endif
13913 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13915 #endif
13918 ** This function registered all of the above C functions as SQL
13919 ** functions. This should be the only routine in this file with
13920 ** external linkage.
13922 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
13923 static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
13924 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13925 FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
13926 FUNCTION(date, -1, 0, 0, dateFunc ),
13927 FUNCTION(time, -1, 0, 0, timeFunc ),
13928 FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
13929 FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
13930 FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
13931 FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
13932 FUNCTION(current_date, 0, 0, 0, cdateFunc ),
13933 #else
13934 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
13935 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
13936 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
13937 #endif
13939 int i;
13940 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
13941 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
13943 for(i=0; i<ArraySize(aDateTimeFuncs); i++){
13944 sqlite3FuncDefInsert(pHash, &aFunc[i]);
13948 /************** End of date.c ************************************************/
13949 /************** Begin file os.c **********************************************/
13951 ** 2005 November 29
13953 ** The author disclaims copyright to this source code. In place of
13954 ** a legal notice, here is a blessing:
13956 ** May you do good and not evil.
13957 ** May you find forgiveness for yourself and forgive others.
13958 ** May you share freely, never taking more than you give.
13960 ******************************************************************************
13962 ** This file contains OS interface code that is common to all
13963 ** architectures.
13965 #define _SQLITE_OS_C_ 1
13966 #undef _SQLITE_OS_C_
13969 ** The default SQLite sqlite3_vfs implementations do not allocate
13970 ** memory (actually, os_unix.c allocates a small amount of memory
13971 ** from within OsOpen()), but some third-party implementations may.
13972 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
13973 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
13975 ** The following functions are instrumented for malloc() failure
13976 ** testing:
13978 ** sqlite3OsOpen()
13979 ** sqlite3OsRead()
13980 ** sqlite3OsWrite()
13981 ** sqlite3OsSync()
13982 ** sqlite3OsLock()
13985 #if defined(SQLITE_TEST)
13986 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
13987 #define DO_OS_MALLOC_TEST(x) \
13988 if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
13989 void *pTstAlloc = sqlite3Malloc(10); \
13990 if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
13991 sqlite3_free(pTstAlloc); \
13993 #else
13994 #define DO_OS_MALLOC_TEST(x)
13995 #endif
13998 ** The following routines are convenience wrappers around methods
13999 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
14000 ** of this would be completely automatic if SQLite were coded using
14001 ** C++ instead of plain old C.
14003 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
14004 int rc = SQLITE_OK;
14005 if( pId->pMethods ){
14006 rc = pId->pMethods->xClose(pId);
14007 pId->pMethods = 0;
14009 return rc;
14011 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
14012 DO_OS_MALLOC_TEST(id);
14013 return id->pMethods->xRead(id, pBuf, amt, offset);
14015 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
14016 DO_OS_MALLOC_TEST(id);
14017 return id->pMethods->xWrite(id, pBuf, amt, offset);
14019 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
14020 return id->pMethods->xTruncate(id, size);
14022 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
14023 DO_OS_MALLOC_TEST(id);
14024 return id->pMethods->xSync(id, flags);
14026 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14027 DO_OS_MALLOC_TEST(id);
14028 return id->pMethods->xFileSize(id, pSize);
14030 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14031 DO_OS_MALLOC_TEST(id);
14032 return id->pMethods->xLock(id, lockType);
14034 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14035 return id->pMethods->xUnlock(id, lockType);
14037 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14038 DO_OS_MALLOC_TEST(id);
14039 return id->pMethods->xCheckReservedLock(id, pResOut);
14041 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14042 return id->pMethods->xFileControl(id, op, pArg);
14044 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14045 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14046 return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14048 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14049 return id->pMethods->xDeviceCharacteristics(id);
14051 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14052 return id->pMethods->xShmLock(id, offset, n, flags);
14054 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14055 id->pMethods->xShmBarrier(id);
14057 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14058 return id->pMethods->xShmUnmap(id, deleteFlag);
14060 SQLITE_PRIVATE int sqlite3OsShmMap(
14061 sqlite3_file *id, /* Database file handle */
14062 int iPage,
14063 int pgsz,
14064 int bExtend, /* True to extend file if necessary */
14065 void volatile **pp /* OUT: Pointer to mapping */
14067 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14071 ** The next group of routines are convenience wrappers around the
14072 ** VFS methods.
14074 SQLITE_PRIVATE int sqlite3OsOpen(
14075 sqlite3_vfs *pVfs,
14076 const char *zPath,
14077 sqlite3_file *pFile,
14078 int flags,
14079 int *pFlagsOut
14081 int rc;
14082 DO_OS_MALLOC_TEST(0);
14083 /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14084 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
14085 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14086 ** reaching the VFS. */
14087 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
14088 assert( rc==SQLITE_OK || pFile->pMethods==0 );
14089 return rc;
14091 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14092 return pVfs->xDelete(pVfs, zPath, dirSync);
14094 SQLITE_PRIVATE int sqlite3OsAccess(
14095 sqlite3_vfs *pVfs,
14096 const char *zPath,
14097 int flags,
14098 int *pResOut
14100 DO_OS_MALLOC_TEST(0);
14101 return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14103 SQLITE_PRIVATE int sqlite3OsFullPathname(
14104 sqlite3_vfs *pVfs,
14105 const char *zPath,
14106 int nPathOut,
14107 char *zPathOut
14109 zPathOut[0] = 0;
14110 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14112 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14113 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14114 return pVfs->xDlOpen(pVfs, zPath);
14116 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14117 pVfs->xDlError(pVfs, nByte, zBufOut);
14119 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
14120 return pVfs->xDlSym(pVfs, pHdle, zSym);
14122 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
14123 pVfs->xDlClose(pVfs, pHandle);
14125 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
14126 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14127 return pVfs->xRandomness(pVfs, nByte, zBufOut);
14129 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
14130 return pVfs->xSleep(pVfs, nMicro);
14132 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
14133 int rc;
14134 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
14135 ** method to get the current date and time if that method is available
14136 ** (if iVersion is 2 or greater and the function pointer is not NULL) and
14137 ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
14138 ** unavailable.
14140 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
14141 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
14142 }else{
14143 double r;
14144 rc = pVfs->xCurrentTime(pVfs, &r);
14145 *pTimeOut = (sqlite3_int64)(r*86400000.0);
14147 return rc;
14150 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
14151 sqlite3_vfs *pVfs,
14152 const char *zFile,
14153 sqlite3_file **ppFile,
14154 int flags,
14155 int *pOutFlags
14157 int rc = SQLITE_NOMEM;
14158 sqlite3_file *pFile;
14159 pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
14160 if( pFile ){
14161 rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
14162 if( rc!=SQLITE_OK ){
14163 sqlite3_free(pFile);
14164 }else{
14165 *ppFile = pFile;
14168 return rc;
14170 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
14171 int rc = SQLITE_OK;
14172 assert( pFile );
14173 rc = sqlite3OsClose(pFile);
14174 sqlite3_free(pFile);
14175 return rc;
14179 ** This function is a wrapper around the OS specific implementation of
14180 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
14181 ** ability to simulate a malloc failure, so that the handling of an
14182 ** error in sqlite3_os_init() by the upper layers can be tested.
14184 SQLITE_PRIVATE int sqlite3OsInit(void){
14185 void *p = sqlite3_malloc(10);
14186 if( p==0 ) return SQLITE_NOMEM;
14187 sqlite3_free(p);
14188 return sqlite3_os_init();
14192 ** The list of all registered VFS implementations.
14194 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
14195 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
14198 ** Locate a VFS by name. If no name is given, simply return the
14199 ** first VFS on the list.
14201 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
14202 sqlite3_vfs *pVfs = 0;
14203 #if SQLITE_THREADSAFE
14204 sqlite3_mutex *mutex;
14205 #endif
14206 #ifndef SQLITE_OMIT_AUTOINIT
14207 int rc = sqlite3_initialize();
14208 if( rc ) return 0;
14209 #endif
14210 #if SQLITE_THREADSAFE
14211 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14212 #endif
14213 sqlite3_mutex_enter(mutex);
14214 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
14215 if( zVfs==0 ) break;
14216 if( strcmp(zVfs, pVfs->zName)==0 ) break;
14218 sqlite3_mutex_leave(mutex);
14219 return pVfs;
14223 ** Unlink a VFS from the linked list
14225 static void vfsUnlink(sqlite3_vfs *pVfs){
14226 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
14227 if( pVfs==0 ){
14228 /* No-op */
14229 }else if( vfsList==pVfs ){
14230 vfsList = pVfs->pNext;
14231 }else if( vfsList ){
14232 sqlite3_vfs *p = vfsList;
14233 while( p->pNext && p->pNext!=pVfs ){
14234 p = p->pNext;
14236 if( p->pNext==pVfs ){
14237 p->pNext = pVfs->pNext;
14243 ** Register a VFS with the system. It is harmless to register the same
14244 ** VFS multiple times. The new VFS becomes the default if makeDflt is
14245 ** true.
14247 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
14248 sqlite3_mutex *mutex = 0;
14249 #ifndef SQLITE_OMIT_AUTOINIT
14250 int rc = sqlite3_initialize();
14251 if( rc ) return rc;
14252 #endif
14253 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14254 sqlite3_mutex_enter(mutex);
14255 vfsUnlink(pVfs);
14256 if( makeDflt || vfsList==0 ){
14257 pVfs->pNext = vfsList;
14258 vfsList = pVfs;
14259 }else{
14260 pVfs->pNext = vfsList->pNext;
14261 vfsList->pNext = pVfs;
14263 assert(vfsList);
14264 sqlite3_mutex_leave(mutex);
14265 return SQLITE_OK;
14269 ** Unregister a VFS so that it is no longer accessible.
14271 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
14272 #if SQLITE_THREADSAFE
14273 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14274 #endif
14275 sqlite3_mutex_enter(mutex);
14276 vfsUnlink(pVfs);
14277 sqlite3_mutex_leave(mutex);
14278 return SQLITE_OK;
14281 /************** End of os.c **************************************************/
14282 /************** Begin file fault.c *******************************************/
14284 ** 2008 Jan 22
14286 ** The author disclaims copyright to this source code. In place of
14287 ** a legal notice, here is a blessing:
14289 ** May you do good and not evil.
14290 ** May you find forgiveness for yourself and forgive others.
14291 ** May you share freely, never taking more than you give.
14293 *************************************************************************
14295 ** This file contains code to support the concept of "benign"
14296 ** malloc failures (when the xMalloc() or xRealloc() method of the
14297 ** sqlite3_mem_methods structure fails to allocate a block of memory
14298 ** and returns 0).
14300 ** Most malloc failures are non-benign. After they occur, SQLite
14301 ** abandons the current operation and returns an error code (usually
14302 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
14303 ** fatal. For example, if a malloc fails while resizing a hash table, this
14304 ** is completely recoverable simply by not carrying out the resize. The
14305 ** hash table will continue to function normally. So a malloc failure
14306 ** during a hash table resize is a benign fault.
14310 #ifndef SQLITE_OMIT_BUILTIN_TEST
14313 ** Global variables.
14315 typedef struct BenignMallocHooks BenignMallocHooks;
14316 static SQLITE_WSD struct BenignMallocHooks {
14317 void (*xBenignBegin)(void);
14318 void (*xBenignEnd)(void);
14319 } sqlite3Hooks = { 0, 0 };
14321 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
14322 ** structure. If writable static data is unsupported on the target,
14323 ** we have to locate the state vector at run-time. In the more common
14324 ** case where writable static data is supported, wsdHooks can refer directly
14325 ** to the "sqlite3Hooks" state vector declared above.
14327 #ifdef SQLITE_OMIT_WSD
14328 # define wsdHooksInit \
14329 BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
14330 # define wsdHooks x[0]
14331 #else
14332 # define wsdHooksInit
14333 # define wsdHooks sqlite3Hooks
14334 #endif
14338 ** Register hooks to call when sqlite3BeginBenignMalloc() and
14339 ** sqlite3EndBenignMalloc() are called, respectively.
14341 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
14342 void (*xBenignBegin)(void),
14343 void (*xBenignEnd)(void)
14345 wsdHooksInit;
14346 wsdHooks.xBenignBegin = xBenignBegin;
14347 wsdHooks.xBenignEnd = xBenignEnd;
14351 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
14352 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
14353 ** indicates that subsequent malloc failures are non-benign.
14355 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
14356 wsdHooksInit;
14357 if( wsdHooks.xBenignBegin ){
14358 wsdHooks.xBenignBegin();
14361 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
14362 wsdHooksInit;
14363 if( wsdHooks.xBenignEnd ){
14364 wsdHooks.xBenignEnd();
14368 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
14370 /************** End of fault.c ***********************************************/
14371 /************** Begin file mem0.c ********************************************/
14373 ** 2008 October 28
14375 ** The author disclaims copyright to this source code. In place of
14376 ** a legal notice, here is a blessing:
14378 ** May you do good and not evil.
14379 ** May you find forgiveness for yourself and forgive others.
14380 ** May you share freely, never taking more than you give.
14382 *************************************************************************
14384 ** This file contains a no-op memory allocation drivers for use when
14385 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
14386 ** here always fail. SQLite will not operate with these drivers. These
14387 ** are merely placeholders. Real drivers must be substituted using
14388 ** sqlite3_config() before SQLite will operate.
14392 ** This version of the memory allocator is the default. It is
14393 ** used when no other memory allocator is specified using compile-time
14394 ** macros.
14396 #ifdef SQLITE_ZERO_MALLOC
14399 ** No-op versions of all memory allocation routines
14401 static void *sqlite3MemMalloc(int nByte){ return 0; }
14402 static void sqlite3MemFree(void *pPrior){ return; }
14403 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
14404 static int sqlite3MemSize(void *pPrior){ return 0; }
14405 static int sqlite3MemRoundup(int n){ return n; }
14406 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
14407 static void sqlite3MemShutdown(void *NotUsed){ return; }
14410 ** This routine is the only routine in this file with external linkage.
14412 ** Populate the low-level memory allocation function pointers in
14413 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14415 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14416 static const sqlite3_mem_methods defaultMethods = {
14417 sqlite3MemMalloc,
14418 sqlite3MemFree,
14419 sqlite3MemRealloc,
14420 sqlite3MemSize,
14421 sqlite3MemRoundup,
14422 sqlite3MemInit,
14423 sqlite3MemShutdown,
14426 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14429 #endif /* SQLITE_ZERO_MALLOC */
14431 /************** End of mem0.c ************************************************/
14432 /************** Begin file mem1.c ********************************************/
14434 ** 2007 August 14
14436 ** The author disclaims copyright to this source code. In place of
14437 ** a legal notice, here is a blessing:
14439 ** May you do good and not evil.
14440 ** May you find forgiveness for yourself and forgive others.
14441 ** May you share freely, never taking more than you give.
14443 *************************************************************************
14445 ** This file contains low-level memory allocation drivers for when
14446 ** SQLite will use the standard C-library malloc/realloc/free interface
14447 ** to obtain the memory it needs.
14449 ** This file contains implementations of the low-level memory allocation
14450 ** routines specified in the sqlite3_mem_methods object.
14454 ** This version of the memory allocator is the default. It is
14455 ** used when no other memory allocator is specified using compile-time
14456 ** macros.
14458 #ifdef SQLITE_SYSTEM_MALLOC
14461 ** Like malloc(), but remember the size of the allocation
14462 ** so that we can find it later using sqlite3MemSize().
14464 ** For this low-level routine, we are guaranteed that nByte>0 because
14465 ** cases of nByte<=0 will be intercepted and dealt with by higher level
14466 ** routines.
14468 static void *sqlite3MemMalloc(int nByte){
14469 sqlite3_int64 *p;
14470 assert( nByte>0 );
14471 nByte = ROUND8(nByte);
14472 p = malloc( nByte+8 );
14473 if( p ){
14474 p[0] = nByte;
14475 p++;
14476 }else{
14477 testcase( sqlite3GlobalConfig.xLog!=0 );
14478 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
14480 return (void *)p;
14484 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
14485 ** or sqlite3MemRealloc().
14487 ** For this low-level routine, we already know that pPrior!=0 since
14488 ** cases where pPrior==0 will have been intecepted and dealt with
14489 ** by higher-level routines.
14491 static void sqlite3MemFree(void *pPrior){
14492 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14493 assert( pPrior!=0 );
14494 p--;
14495 free(p);
14499 ** Report the allocated size of a prior return from xMalloc()
14500 ** or xRealloc().
14502 static int sqlite3MemSize(void *pPrior){
14503 sqlite3_int64 *p;
14504 if( pPrior==0 ) return 0;
14505 p = (sqlite3_int64*)pPrior;
14506 p--;
14507 return (int)p[0];
14511 ** Like realloc(). Resize an allocation previously obtained from
14512 ** sqlite3MemMalloc().
14514 ** For this low-level interface, we know that pPrior!=0. Cases where
14515 ** pPrior==0 while have been intercepted by higher-level routine and
14516 ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
14517 ** cases where nByte<=0 will have been intercepted by higher-level
14518 ** routines and redirected to xFree.
14520 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14521 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14522 assert( pPrior!=0 && nByte>0 );
14523 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14524 p--;
14525 p = realloc(p, nByte+8 );
14526 if( p ){
14527 p[0] = nByte;
14528 p++;
14529 }else{
14530 testcase( sqlite3GlobalConfig.xLog!=0 );
14531 sqlite3_log(SQLITE_NOMEM,
14532 "failed memory resize %u to %u bytes",
14533 sqlite3MemSize(pPrior), nByte);
14535 return (void*)p;
14539 ** Round up a request size to the next valid allocation size.
14541 static int sqlite3MemRoundup(int n){
14542 return ROUND8(n);
14546 ** Initialize this module.
14548 static int sqlite3MemInit(void *NotUsed){
14549 UNUSED_PARAMETER(NotUsed);
14550 return SQLITE_OK;
14554 ** Deinitialize this module.
14556 static void sqlite3MemShutdown(void *NotUsed){
14557 UNUSED_PARAMETER(NotUsed);
14558 return;
14562 ** This routine is the only routine in this file with external linkage.
14564 ** Populate the low-level memory allocation function pointers in
14565 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14567 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14568 static const sqlite3_mem_methods defaultMethods = {
14569 sqlite3MemMalloc,
14570 sqlite3MemFree,
14571 sqlite3MemRealloc,
14572 sqlite3MemSize,
14573 sqlite3MemRoundup,
14574 sqlite3MemInit,
14575 sqlite3MemShutdown,
14578 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14581 #endif /* SQLITE_SYSTEM_MALLOC */
14583 /************** End of mem1.c ************************************************/
14584 /************** Begin file mem2.c ********************************************/
14586 ** 2007 August 15
14588 ** The author disclaims copyright to this source code. In place of
14589 ** a legal notice, here is a blessing:
14591 ** May you do good and not evil.
14592 ** May you find forgiveness for yourself and forgive others.
14593 ** May you share freely, never taking more than you give.
14595 *************************************************************************
14597 ** This file contains low-level memory allocation drivers for when
14598 ** SQLite will use the standard C-library malloc/realloc/free interface
14599 ** to obtain the memory it needs while adding lots of additional debugging
14600 ** information to each allocation in order to help detect and fix memory
14601 ** leaks and memory usage errors.
14603 ** This file contains implementations of the low-level memory allocation
14604 ** routines specified in the sqlite3_mem_methods object.
14608 ** This version of the memory allocator is used only if the
14609 ** SQLITE_MEMDEBUG macro is defined
14611 #ifdef SQLITE_MEMDEBUG
14614 ** The backtrace functionality is only available with GLIBC
14616 #ifdef __GLIBC__
14617 extern int backtrace(void**,int);
14618 extern void backtrace_symbols_fd(void*const*,int,int);
14619 #else
14620 # define backtrace(A,B) 1
14621 # define backtrace_symbols_fd(A,B,C)
14622 #endif
14625 ** Each memory allocation looks like this:
14627 ** ------------------------------------------------------------------------
14628 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
14629 ** ------------------------------------------------------------------------
14631 ** The application code sees only a pointer to the allocation. We have
14632 ** to back up from the allocation pointer to find the MemBlockHdr. The
14633 ** MemBlockHdr tells us the size of the allocation and the number of
14634 ** backtrace pointers. There is also a guard word at the end of the
14635 ** MemBlockHdr.
14637 struct MemBlockHdr {
14638 i64 iSize; /* Size of this allocation */
14639 struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
14640 char nBacktrace; /* Number of backtraces on this alloc */
14641 char nBacktraceSlots; /* Available backtrace slots */
14642 u8 nTitle; /* Bytes of title; includes '\0' */
14643 u8 eType; /* Allocation type code */
14644 int iForeGuard; /* Guard word for sanity */
14648 ** Guard words
14650 #define FOREGUARD 0x80F5E153
14651 #define REARGUARD 0xE4676B53
14654 ** Number of malloc size increments to track.
14656 #define NCSIZE 1000
14659 ** All of the static variables used by this module are collected
14660 ** into a single structure named "mem". This is to keep the
14661 ** static variables organized and to reduce namespace pollution
14662 ** when this module is combined with other in the amalgamation.
14664 static struct {
14667 ** Mutex to control access to the memory allocation subsystem.
14669 sqlite3_mutex *mutex;
14672 ** Head and tail of a linked list of all outstanding allocations
14674 struct MemBlockHdr *pFirst;
14675 struct MemBlockHdr *pLast;
14678 ** The number of levels of backtrace to save in new allocations.
14680 int nBacktrace;
14681 void (*xBacktrace)(int, int, void **);
14684 ** Title text to insert in front of each block
14686 int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
14687 char zTitle[100]; /* The title text */
14690 ** sqlite3MallocDisallow() increments the following counter.
14691 ** sqlite3MallocAllow() decrements it.
14693 int disallow; /* Do not allow memory allocation */
14696 ** Gather statistics on the sizes of memory allocations.
14697 ** nAlloc[i] is the number of allocation attempts of i*8
14698 ** bytes. i==NCSIZE is the number of allocation attempts for
14699 ** sizes more than NCSIZE*8 bytes.
14701 int nAlloc[NCSIZE]; /* Total number of allocations */
14702 int nCurrent[NCSIZE]; /* Current number of allocations */
14703 int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
14705 } mem;
14709 ** Adjust memory usage statistics
14711 static void adjustStats(int iSize, int increment){
14712 int i = ROUND8(iSize)/8;
14713 if( i>NCSIZE-1 ){
14714 i = NCSIZE - 1;
14716 if( increment>0 ){
14717 mem.nAlloc[i]++;
14718 mem.nCurrent[i]++;
14719 if( mem.nCurrent[i]>mem.mxCurrent[i] ){
14720 mem.mxCurrent[i] = mem.nCurrent[i];
14722 }else{
14723 mem.nCurrent[i]--;
14724 assert( mem.nCurrent[i]>=0 );
14729 ** Given an allocation, find the MemBlockHdr for that allocation.
14731 ** This routine checks the guards at either end of the allocation and
14732 ** if they are incorrect it asserts.
14734 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
14735 struct MemBlockHdr *p;
14736 int *pInt;
14737 u8 *pU8;
14738 int nReserve;
14740 p = (struct MemBlockHdr*)pAllocation;
14741 p--;
14742 assert( p->iForeGuard==(int)FOREGUARD );
14743 nReserve = ROUND8(p->iSize);
14744 pInt = (int*)pAllocation;
14745 pU8 = (u8*)pAllocation;
14746 assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
14747 /* This checks any of the "extra" bytes allocated due
14748 ** to rounding up to an 8 byte boundary to ensure
14749 ** they haven't been overwritten.
14751 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
14752 return p;
14756 ** Return the number of bytes currently allocated at address p.
14758 static int sqlite3MemSize(void *p){
14759 struct MemBlockHdr *pHdr;
14760 if( !p ){
14761 return 0;
14763 pHdr = sqlite3MemsysGetHeader(p);
14764 return pHdr->iSize;
14768 ** Initialize the memory allocation subsystem.
14770 static int sqlite3MemInit(void *NotUsed){
14771 UNUSED_PARAMETER(NotUsed);
14772 assert( (sizeof(struct MemBlockHdr)&7) == 0 );
14773 if( !sqlite3GlobalConfig.bMemstat ){
14774 /* If memory status is enabled, then the malloc.c wrapper will already
14775 ** hold the STATIC_MEM mutex when the routines here are invoked. */
14776 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14778 return SQLITE_OK;
14782 ** Deinitialize the memory allocation subsystem.
14784 static void sqlite3MemShutdown(void *NotUsed){
14785 UNUSED_PARAMETER(NotUsed);
14786 mem.mutex = 0;
14790 ** Round up a request size to the next valid allocation size.
14792 static int sqlite3MemRoundup(int n){
14793 return ROUND8(n);
14797 ** Fill a buffer with pseudo-random bytes. This is used to preset
14798 ** the content of a new memory allocation to unpredictable values and
14799 ** to clear the content of a freed allocation to unpredictable values.
14801 static void randomFill(char *pBuf, int nByte){
14802 unsigned int x, y, r;
14803 x = SQLITE_PTR_TO_INT(pBuf);
14804 y = nByte | 1;
14805 while( nByte >= 4 ){
14806 x = (x>>1) ^ (-(x&1) & 0xd0000001);
14807 y = y*1103515245 + 12345;
14808 r = x ^ y;
14809 *(int*)pBuf = r;
14810 pBuf += 4;
14811 nByte -= 4;
14813 while( nByte-- > 0 ){
14814 x = (x>>1) ^ (-(x&1) & 0xd0000001);
14815 y = y*1103515245 + 12345;
14816 r = x ^ y;
14817 *(pBuf++) = r & 0xff;
14822 ** Allocate nByte bytes of memory.
14824 static void *sqlite3MemMalloc(int nByte){
14825 struct MemBlockHdr *pHdr;
14826 void **pBt;
14827 char *z;
14828 int *pInt;
14829 void *p = 0;
14830 int totalSize;
14831 int nReserve;
14832 sqlite3_mutex_enter(mem.mutex);
14833 assert( mem.disallow==0 );
14834 nReserve = ROUND8(nByte);
14835 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
14836 mem.nBacktrace*sizeof(void*) + mem.nTitle;
14837 p = malloc(totalSize);
14838 if( p ){
14839 z = p;
14840 pBt = (void**)&z[mem.nTitle];
14841 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
14842 pHdr->pNext = 0;
14843 pHdr->pPrev = mem.pLast;
14844 if( mem.pLast ){
14845 mem.pLast->pNext = pHdr;
14846 }else{
14847 mem.pFirst = pHdr;
14849 mem.pLast = pHdr;
14850 pHdr->iForeGuard = FOREGUARD;
14851 pHdr->eType = MEMTYPE_HEAP;
14852 pHdr->nBacktraceSlots = mem.nBacktrace;
14853 pHdr->nTitle = mem.nTitle;
14854 if( mem.nBacktrace ){
14855 void *aAddr[40];
14856 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
14857 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
14858 assert(pBt[0]);
14859 if( mem.xBacktrace ){
14860 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
14862 }else{
14863 pHdr->nBacktrace = 0;
14865 if( mem.nTitle ){
14866 memcpy(z, mem.zTitle, mem.nTitle);
14868 pHdr->iSize = nByte;
14869 adjustStats(nByte, +1);
14870 pInt = (int*)&pHdr[1];
14871 pInt[nReserve/sizeof(int)] = REARGUARD;
14872 randomFill((char*)pInt, nByte);
14873 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
14874 p = (void*)pInt;
14876 sqlite3_mutex_leave(mem.mutex);
14877 return p;
14881 ** Free memory.
14883 static void sqlite3MemFree(void *pPrior){
14884 struct MemBlockHdr *pHdr;
14885 void **pBt;
14886 char *z;
14887 assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
14888 || mem.mutex!=0 );
14889 pHdr = sqlite3MemsysGetHeader(pPrior);
14890 pBt = (void**)pHdr;
14891 pBt -= pHdr->nBacktraceSlots;
14892 sqlite3_mutex_enter(mem.mutex);
14893 if( pHdr->pPrev ){
14894 assert( pHdr->pPrev->pNext==pHdr );
14895 pHdr->pPrev->pNext = pHdr->pNext;
14896 }else{
14897 assert( mem.pFirst==pHdr );
14898 mem.pFirst = pHdr->pNext;
14900 if( pHdr->pNext ){
14901 assert( pHdr->pNext->pPrev==pHdr );
14902 pHdr->pNext->pPrev = pHdr->pPrev;
14903 }else{
14904 assert( mem.pLast==pHdr );
14905 mem.pLast = pHdr->pPrev;
14907 z = (char*)pBt;
14908 z -= pHdr->nTitle;
14909 adjustStats(pHdr->iSize, -1);
14910 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
14911 pHdr->iSize + sizeof(int) + pHdr->nTitle);
14912 free(z);
14913 sqlite3_mutex_leave(mem.mutex);
14917 ** Change the size of an existing memory allocation.
14919 ** For this debugging implementation, we *always* make a copy of the
14920 ** allocation into a new place in memory. In this way, if the
14921 ** higher level code is using pointer to the old allocation, it is
14922 ** much more likely to break and we are much more liking to find
14923 ** the error.
14925 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14926 struct MemBlockHdr *pOldHdr;
14927 void *pNew;
14928 assert( mem.disallow==0 );
14929 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
14930 pOldHdr = sqlite3MemsysGetHeader(pPrior);
14931 pNew = sqlite3MemMalloc(nByte);
14932 if( pNew ){
14933 memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14934 if( nByte>pOldHdr->iSize ){
14935 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
14937 sqlite3MemFree(pPrior);
14939 return pNew;
14943 ** Populate the low-level memory allocation function pointers in
14944 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14946 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14947 static const sqlite3_mem_methods defaultMethods = {
14948 sqlite3MemMalloc,
14949 sqlite3MemFree,
14950 sqlite3MemRealloc,
14951 sqlite3MemSize,
14952 sqlite3MemRoundup,
14953 sqlite3MemInit,
14954 sqlite3MemShutdown,
14957 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14961 ** Set the "type" of an allocation.
14963 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
14964 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14965 struct MemBlockHdr *pHdr;
14966 pHdr = sqlite3MemsysGetHeader(p);
14967 assert( pHdr->iForeGuard==FOREGUARD );
14968 pHdr->eType = eType;
14973 ** Return TRUE if the mask of type in eType matches the type of the
14974 ** allocation p. Also return true if p==NULL.
14976 ** This routine is designed for use within an assert() statement, to
14977 ** verify the type of an allocation. For example:
14979 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
14981 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
14982 int rc = 1;
14983 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14984 struct MemBlockHdr *pHdr;
14985 pHdr = sqlite3MemsysGetHeader(p);
14986 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
14987 if( (pHdr->eType&eType)==0 ){
14988 rc = 0;
14991 return rc;
14995 ** Return TRUE if the mask of type in eType matches no bits of the type of the
14996 ** allocation p. Also return true if p==NULL.
14998 ** This routine is designed for use within an assert() statement, to
14999 ** verify the type of an allocation. For example:
15001 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
15003 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
15004 int rc = 1;
15005 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15006 struct MemBlockHdr *pHdr;
15007 pHdr = sqlite3MemsysGetHeader(p);
15008 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
15009 if( (pHdr->eType&eType)!=0 ){
15010 rc = 0;
15013 return rc;
15017 ** Set the number of backtrace levels kept for each allocation.
15018 ** A value of zero turns off backtracing. The number is always rounded
15019 ** up to a multiple of 2.
15021 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
15022 if( depth<0 ){ depth = 0; }
15023 if( depth>20 ){ depth = 20; }
15024 depth = (depth+1)&0xfe;
15025 mem.nBacktrace = depth;
15028 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
15029 mem.xBacktrace = xBacktrace;
15033 ** Set the title string for subsequent allocations.
15035 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
15036 unsigned int n = sqlite3Strlen30(zTitle) + 1;
15037 sqlite3_mutex_enter(mem.mutex);
15038 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
15039 memcpy(mem.zTitle, zTitle, n);
15040 mem.zTitle[n] = 0;
15041 mem.nTitle = ROUND8(n);
15042 sqlite3_mutex_leave(mem.mutex);
15045 SQLITE_PRIVATE void sqlite3MemdebugSync(){
15046 struct MemBlockHdr *pHdr;
15047 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15048 void **pBt = (void**)pHdr;
15049 pBt -= pHdr->nBacktraceSlots;
15050 mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
15055 ** Open the file indicated and write a log of all unfreed memory
15056 ** allocations into that log.
15058 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
15059 FILE *out;
15060 struct MemBlockHdr *pHdr;
15061 void **pBt;
15062 int i;
15063 out = fopen(zFilename, "w");
15064 if( out==0 ){
15065 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15066 zFilename);
15067 return;
15069 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15070 char *z = (char*)pHdr;
15071 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
15072 fprintf(out, "**** %lld bytes at %p from %s ****\n",
15073 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
15074 if( pHdr->nBacktrace ){
15075 fflush(out);
15076 pBt = (void**)pHdr;
15077 pBt -= pHdr->nBacktraceSlots;
15078 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
15079 fprintf(out, "\n");
15082 fprintf(out, "COUNTS:\n");
15083 for(i=0; i<NCSIZE-1; i++){
15084 if( mem.nAlloc[i] ){
15085 fprintf(out, " %5d: %10d %10d %10d\n",
15086 i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
15089 if( mem.nAlloc[NCSIZE-1] ){
15090 fprintf(out, " %5d: %10d %10d %10d\n",
15091 NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
15092 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
15094 fclose(out);
15098 ** Return the number of times sqlite3MemMalloc() has been called.
15100 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
15101 int i;
15102 int nTotal = 0;
15103 for(i=0; i<NCSIZE; i++){
15104 nTotal += mem.nAlloc[i];
15106 return nTotal;
15110 #endif /* SQLITE_MEMDEBUG */
15112 /************** End of mem2.c ************************************************/
15113 /************** Begin file mem3.c ********************************************/
15115 ** 2007 October 14
15117 ** The author disclaims copyright to this source code. In place of
15118 ** a legal notice, here is a blessing:
15120 ** May you do good and not evil.
15121 ** May you find forgiveness for yourself and forgive others.
15122 ** May you share freely, never taking more than you give.
15124 *************************************************************************
15125 ** This file contains the C functions that implement a memory
15126 ** allocation subsystem for use by SQLite.
15128 ** This version of the memory allocation subsystem omits all
15129 ** use of malloc(). The SQLite user supplies a block of memory
15130 ** before calling sqlite3_initialize() from which allocations
15131 ** are made and returned by the xMalloc() and xRealloc()
15132 ** implementations. Once sqlite3_initialize() has been called,
15133 ** the amount of memory available to SQLite is fixed and cannot
15134 ** be changed.
15136 ** This version of the memory allocation subsystem is included
15137 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
15141 ** This version of the memory allocator is only built into the library
15142 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
15143 ** mean that the library will use a memory-pool by default, just that
15144 ** it is available. The mempool allocator is activated by calling
15145 ** sqlite3_config().
15147 #ifdef SQLITE_ENABLE_MEMSYS3
15150 ** Maximum size (in Mem3Blocks) of a "small" chunk.
15152 #define MX_SMALL 10
15156 ** Number of freelist hash slots
15158 #define N_HASH 61
15161 ** A memory allocation (also called a "chunk") consists of two or
15162 ** more blocks where each block is 8 bytes. The first 8 bytes are
15163 ** a header that is not returned to the user.
15165 ** A chunk is two or more blocks that is either checked out or
15166 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
15167 ** size of the allocation in blocks if the allocation is free.
15168 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
15169 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
15170 ** is true if the previous chunk is checked out and false if the
15171 ** previous chunk is free. The u.hdr.prevSize field is the size of
15172 ** the previous chunk in blocks if the previous chunk is on the
15173 ** freelist. If the previous chunk is checked out, then
15174 ** u.hdr.prevSize can be part of the data for that chunk and should
15175 ** not be read or written.
15177 ** We often identify a chunk by its index in mem3.aPool[]. When
15178 ** this is done, the chunk index refers to the second block of
15179 ** the chunk. In this way, the first chunk has an index of 1.
15180 ** A chunk index of 0 means "no such chunk" and is the equivalent
15181 ** of a NULL pointer.
15183 ** The second block of free chunks is of the form u.list. The
15184 ** two fields form a double-linked list of chunks of related sizes.
15185 ** Pointers to the head of the list are stored in mem3.aiSmall[]
15186 ** for smaller chunks and mem3.aiHash[] for larger chunks.
15188 ** The second block of a chunk is user data if the chunk is checked
15189 ** out. If a chunk is checked out, the user data may extend into
15190 ** the u.hdr.prevSize value of the following chunk.
15192 typedef struct Mem3Block Mem3Block;
15193 struct Mem3Block {
15194 union {
15195 struct {
15196 u32 prevSize; /* Size of previous chunk in Mem3Block elements */
15197 u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
15198 } hdr;
15199 struct {
15200 u32 next; /* Index in mem3.aPool[] of next free chunk */
15201 u32 prev; /* Index in mem3.aPool[] of previous free chunk */
15202 } list;
15203 } u;
15207 ** All of the static variables used by this module are collected
15208 ** into a single structure named "mem3". This is to keep the
15209 ** static variables organized and to reduce namespace pollution
15210 ** when this module is combined with other in the amalgamation.
15212 static SQLITE_WSD struct Mem3Global {
15214 ** Memory available for allocation. nPool is the size of the array
15215 ** (in Mem3Blocks) pointed to by aPool less 2.
15217 u32 nPool;
15218 Mem3Block *aPool;
15221 ** True if we are evaluating an out-of-memory callback.
15223 int alarmBusy;
15226 ** Mutex to control access to the memory allocation subsystem.
15228 sqlite3_mutex *mutex;
15231 ** The minimum amount of free space that we have seen.
15233 u32 mnMaster;
15236 ** iMaster is the index of the master chunk. Most new allocations
15237 ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
15238 ** of the current master. iMaster is 0 if there is not master chunk.
15239 ** The master chunk is not in either the aiHash[] or aiSmall[].
15241 u32 iMaster;
15242 u32 szMaster;
15245 ** Array of lists of free blocks according to the block size
15246 ** for smaller chunks, or a hash on the block size for larger
15247 ** chunks.
15249 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
15250 u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
15251 } mem3 = { 97535575 };
15253 #define mem3 GLOBAL(struct Mem3Global, mem3)
15256 ** Unlink the chunk at mem3.aPool[i] from list it is currently
15257 ** on. *pRoot is the list that i is a member of.
15259 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
15260 u32 next = mem3.aPool[i].u.list.next;
15261 u32 prev = mem3.aPool[i].u.list.prev;
15262 assert( sqlite3_mutex_held(mem3.mutex) );
15263 if( prev==0 ){
15264 *pRoot = next;
15265 }else{
15266 mem3.aPool[prev].u.list.next = next;
15268 if( next ){
15269 mem3.aPool[next].u.list.prev = prev;
15271 mem3.aPool[i].u.list.next = 0;
15272 mem3.aPool[i].u.list.prev = 0;
15276 ** Unlink the chunk at index i from
15277 ** whatever list is currently a member of.
15279 static void memsys3Unlink(u32 i){
15280 u32 size, hash;
15281 assert( sqlite3_mutex_held(mem3.mutex) );
15282 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15283 assert( i>=1 );
15284 size = mem3.aPool[i-1].u.hdr.size4x/4;
15285 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15286 assert( size>=2 );
15287 if( size <= MX_SMALL ){
15288 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
15289 }else{
15290 hash = size % N_HASH;
15291 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15296 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
15297 ** at *pRoot.
15299 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
15300 assert( sqlite3_mutex_held(mem3.mutex) );
15301 mem3.aPool[i].u.list.next = *pRoot;
15302 mem3.aPool[i].u.list.prev = 0;
15303 if( *pRoot ){
15304 mem3.aPool[*pRoot].u.list.prev = i;
15306 *pRoot = i;
15310 ** Link the chunk at index i into either the appropriate
15311 ** small chunk list, or into the large chunk hash table.
15313 static void memsys3Link(u32 i){
15314 u32 size, hash;
15315 assert( sqlite3_mutex_held(mem3.mutex) );
15316 assert( i>=1 );
15317 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15318 size = mem3.aPool[i-1].u.hdr.size4x/4;
15319 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15320 assert( size>=2 );
15321 if( size <= MX_SMALL ){
15322 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
15323 }else{
15324 hash = size % N_HASH;
15325 memsys3LinkIntoList(i, &mem3.aiHash[hash]);
15330 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15331 ** will already be held (obtained by code in malloc.c) if
15332 ** sqlite3GlobalConfig.bMemStat is true.
15334 static void memsys3Enter(void){
15335 if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
15336 mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15338 sqlite3_mutex_enter(mem3.mutex);
15340 static void memsys3Leave(void){
15341 sqlite3_mutex_leave(mem3.mutex);
15345 ** Called when we are unable to satisfy an allocation of nBytes.
15347 static void memsys3OutOfMemory(int nByte){
15348 if( !mem3.alarmBusy ){
15349 mem3.alarmBusy = 1;
15350 assert( sqlite3_mutex_held(mem3.mutex) );
15351 sqlite3_mutex_leave(mem3.mutex);
15352 sqlite3_release_memory(nByte);
15353 sqlite3_mutex_enter(mem3.mutex);
15354 mem3.alarmBusy = 0;
15360 ** Chunk i is a free chunk that has been unlinked. Adjust its
15361 ** size parameters for check-out and return a pointer to the
15362 ** user portion of the chunk.
15364 static void *memsys3Checkout(u32 i, u32 nBlock){
15365 u32 x;
15366 assert( sqlite3_mutex_held(mem3.mutex) );
15367 assert( i>=1 );
15368 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
15369 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
15370 x = mem3.aPool[i-1].u.hdr.size4x;
15371 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
15372 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
15373 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
15374 return &mem3.aPool[i];
15378 ** Carve a piece off of the end of the mem3.iMaster free chunk.
15379 ** Return a pointer to the new allocation. Or, if the master chunk
15380 ** is not large enough, return 0.
15382 static void *memsys3FromMaster(u32 nBlock){
15383 assert( sqlite3_mutex_held(mem3.mutex) );
15384 assert( mem3.szMaster>=nBlock );
15385 if( nBlock>=mem3.szMaster-1 ){
15386 /* Use the entire master */
15387 void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
15388 mem3.iMaster = 0;
15389 mem3.szMaster = 0;
15390 mem3.mnMaster = 0;
15391 return p;
15392 }else{
15393 /* Split the master block. Return the tail. */
15394 u32 newi, x;
15395 newi = mem3.iMaster + mem3.szMaster - nBlock;
15396 assert( newi > mem3.iMaster+1 );
15397 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
15398 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
15399 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
15400 mem3.szMaster -= nBlock;
15401 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
15402 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15403 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15404 if( mem3.szMaster < mem3.mnMaster ){
15405 mem3.mnMaster = mem3.szMaster;
15407 return (void*)&mem3.aPool[newi];
15412 ** *pRoot is the head of a list of free chunks of the same size
15413 ** or same size hash. In other words, *pRoot is an entry in either
15414 ** mem3.aiSmall[] or mem3.aiHash[].
15416 ** This routine examines all entries on the given list and tries
15417 ** to coalesce each entries with adjacent free chunks.
15419 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
15420 ** the current mem3.iMaster with the new larger chunk. In order for
15421 ** this mem3.iMaster replacement to work, the master chunk must be
15422 ** linked into the hash tables. That is not the normal state of
15423 ** affairs, of course. The calling routine must link the master
15424 ** chunk before invoking this routine, then must unlink the (possibly
15425 ** changed) master chunk once this routine has finished.
15427 static void memsys3Merge(u32 *pRoot){
15428 u32 iNext, prev, size, i, x;
15430 assert( sqlite3_mutex_held(mem3.mutex) );
15431 for(i=*pRoot; i>0; i=iNext){
15432 iNext = mem3.aPool[i].u.list.next;
15433 size = mem3.aPool[i-1].u.hdr.size4x;
15434 assert( (size&1)==0 );
15435 if( (size&2)==0 ){
15436 memsys3UnlinkFromList(i, pRoot);
15437 assert( i > mem3.aPool[i-1].u.hdr.prevSize );
15438 prev = i - mem3.aPool[i-1].u.hdr.prevSize;
15439 if( prev==iNext ){
15440 iNext = mem3.aPool[prev].u.list.next;
15442 memsys3Unlink(prev);
15443 size = i + size/4 - prev;
15444 x = mem3.aPool[prev-1].u.hdr.size4x & 2;
15445 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
15446 mem3.aPool[prev+size-1].u.hdr.prevSize = size;
15447 memsys3Link(prev);
15448 i = prev;
15449 }else{
15450 size /= 4;
15452 if( size>mem3.szMaster ){
15453 mem3.iMaster = i;
15454 mem3.szMaster = size;
15460 ** Return a block of memory of at least nBytes in size.
15461 ** Return NULL if unable.
15463 ** This function assumes that the necessary mutexes, if any, are
15464 ** already held by the caller. Hence "Unsafe".
15466 static void *memsys3MallocUnsafe(int nByte){
15467 u32 i;
15468 u32 nBlock;
15469 u32 toFree;
15471 assert( sqlite3_mutex_held(mem3.mutex) );
15472 assert( sizeof(Mem3Block)==8 );
15473 if( nByte<=12 ){
15474 nBlock = 2;
15475 }else{
15476 nBlock = (nByte + 11)/8;
15478 assert( nBlock>=2 );
15480 /* STEP 1:
15481 ** Look for an entry of the correct size in either the small
15482 ** chunk table or in the large chunk hash table. This is
15483 ** successful most of the time (about 9 times out of 10).
15485 if( nBlock <= MX_SMALL ){
15486 i = mem3.aiSmall[nBlock-2];
15487 if( i>0 ){
15488 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
15489 return memsys3Checkout(i, nBlock);
15491 }else{
15492 int hash = nBlock % N_HASH;
15493 for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
15494 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
15495 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15496 return memsys3Checkout(i, nBlock);
15501 /* STEP 2:
15502 ** Try to satisfy the allocation by carving a piece off of the end
15503 ** of the master chunk. This step usually works if step 1 fails.
15505 if( mem3.szMaster>=nBlock ){
15506 return memsys3FromMaster(nBlock);
15510 /* STEP 3:
15511 ** Loop through the entire memory pool. Coalesce adjacent free
15512 ** chunks. Recompute the master chunk as the largest free chunk.
15513 ** Then try again to satisfy the allocation by carving a piece off
15514 ** of the end of the master chunk. This step happens very
15515 ** rarely (we hope!)
15517 for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
15518 memsys3OutOfMemory(toFree);
15519 if( mem3.iMaster ){
15520 memsys3Link(mem3.iMaster);
15521 mem3.iMaster = 0;
15522 mem3.szMaster = 0;
15524 for(i=0; i<N_HASH; i++){
15525 memsys3Merge(&mem3.aiHash[i]);
15527 for(i=0; i<MX_SMALL-1; i++){
15528 memsys3Merge(&mem3.aiSmall[i]);
15530 if( mem3.szMaster ){
15531 memsys3Unlink(mem3.iMaster);
15532 if( mem3.szMaster>=nBlock ){
15533 return memsys3FromMaster(nBlock);
15538 /* If none of the above worked, then we fail. */
15539 return 0;
15543 ** Free an outstanding memory allocation.
15545 ** This function assumes that the necessary mutexes, if any, are
15546 ** already held by the caller. Hence "Unsafe".
15548 void memsys3FreeUnsafe(void *pOld){
15549 Mem3Block *p = (Mem3Block*)pOld;
15550 int i;
15551 u32 size, x;
15552 assert( sqlite3_mutex_held(mem3.mutex) );
15553 assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
15554 i = p - mem3.aPool;
15555 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
15556 size = mem3.aPool[i-1].u.hdr.size4x/4;
15557 assert( i+size<=mem3.nPool+1 );
15558 mem3.aPool[i-1].u.hdr.size4x &= ~1;
15559 mem3.aPool[i+size-1].u.hdr.prevSize = size;
15560 mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
15561 memsys3Link(i);
15563 /* Try to expand the master using the newly freed chunk */
15564 if( mem3.iMaster ){
15565 while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
15566 size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
15567 mem3.iMaster -= size;
15568 mem3.szMaster += size;
15569 memsys3Unlink(mem3.iMaster);
15570 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15571 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15572 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15574 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15575 while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
15576 memsys3Unlink(mem3.iMaster+mem3.szMaster);
15577 mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
15578 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15579 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15585 ** Return the size of an outstanding allocation, in bytes. The
15586 ** size returned omits the 8-byte header overhead. This only
15587 ** works for chunks that are currently checked out.
15589 static int memsys3Size(void *p){
15590 Mem3Block *pBlock;
15591 if( p==0 ) return 0;
15592 pBlock = (Mem3Block*)p;
15593 assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
15594 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
15598 ** Round up a request size to the next valid allocation size.
15600 static int memsys3Roundup(int n){
15601 if( n<=12 ){
15602 return 12;
15603 }else{
15604 return ((n+11)&~7) - 4;
15609 ** Allocate nBytes of memory.
15611 static void *memsys3Malloc(int nBytes){
15612 sqlite3_int64 *p;
15613 assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
15614 memsys3Enter();
15615 p = memsys3MallocUnsafe(nBytes);
15616 memsys3Leave();
15617 return (void*)p;
15621 ** Free memory.
15623 void memsys3Free(void *pPrior){
15624 assert( pPrior );
15625 memsys3Enter();
15626 memsys3FreeUnsafe(pPrior);
15627 memsys3Leave();
15631 ** Change the size of an existing memory allocation
15633 void *memsys3Realloc(void *pPrior, int nBytes){
15634 int nOld;
15635 void *p;
15636 if( pPrior==0 ){
15637 return sqlite3_malloc(nBytes);
15639 if( nBytes<=0 ){
15640 sqlite3_free(pPrior);
15641 return 0;
15643 nOld = memsys3Size(pPrior);
15644 if( nBytes<=nOld && nBytes>=nOld-128 ){
15645 return pPrior;
15647 memsys3Enter();
15648 p = memsys3MallocUnsafe(nBytes);
15649 if( p ){
15650 if( nOld<nBytes ){
15651 memcpy(p, pPrior, nOld);
15652 }else{
15653 memcpy(p, pPrior, nBytes);
15655 memsys3FreeUnsafe(pPrior);
15657 memsys3Leave();
15658 return p;
15662 ** Initialize this module.
15664 static int memsys3Init(void *NotUsed){
15665 UNUSED_PARAMETER(NotUsed);
15666 if( !sqlite3GlobalConfig.pHeap ){
15667 return SQLITE_ERROR;
15670 /* Store a pointer to the memory block in global structure mem3. */
15671 assert( sizeof(Mem3Block)==8 );
15672 mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
15673 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
15675 /* Initialize the master block. */
15676 mem3.szMaster = mem3.nPool;
15677 mem3.mnMaster = mem3.szMaster;
15678 mem3.iMaster = 1;
15679 mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
15680 mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
15681 mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
15683 return SQLITE_OK;
15687 ** Deinitialize this module.
15689 static void memsys3Shutdown(void *NotUsed){
15690 UNUSED_PARAMETER(NotUsed);
15691 mem3.mutex = 0;
15692 return;
15698 ** Open the file indicated and write a log of all unfreed memory
15699 ** allocations into that log.
15701 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
15702 #ifdef SQLITE_DEBUG
15703 FILE *out;
15704 u32 i, j;
15705 u32 size;
15706 if( zFilename==0 || zFilename[0]==0 ){
15707 out = stdout;
15708 }else{
15709 out = fopen(zFilename, "w");
15710 if( out==0 ){
15711 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15712 zFilename);
15713 return;
15716 memsys3Enter();
15717 fprintf(out, "CHUNKS:\n");
15718 for(i=1; i<=mem3.nPool; i+=size/4){
15719 size = mem3.aPool[i-1].u.hdr.size4x;
15720 if( size/4<=1 ){
15721 fprintf(out, "%p size error\n", &mem3.aPool[i]);
15722 assert( 0 );
15723 break;
15725 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
15726 fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
15727 assert( 0 );
15728 break;
15730 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
15731 fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
15732 assert( 0 );
15733 break;
15735 if( size&1 ){
15736 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
15737 }else{
15738 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
15739 i==mem3.iMaster ? " **master**" : "");
15742 for(i=0; i<MX_SMALL-1; i++){
15743 if( mem3.aiSmall[i]==0 ) continue;
15744 fprintf(out, "small(%2d):", i);
15745 for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
15746 fprintf(out, " %p(%d)", &mem3.aPool[j],
15747 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15749 fprintf(out, "\n");
15751 for(i=0; i<N_HASH; i++){
15752 if( mem3.aiHash[i]==0 ) continue;
15753 fprintf(out, "hash(%2d):", i);
15754 for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
15755 fprintf(out, " %p(%d)", &mem3.aPool[j],
15756 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15758 fprintf(out, "\n");
15760 fprintf(out, "master=%d\n", mem3.iMaster);
15761 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
15762 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
15763 sqlite3_mutex_leave(mem3.mutex);
15764 if( out==stdout ){
15765 fflush(stdout);
15766 }else{
15767 fclose(out);
15769 #else
15770 UNUSED_PARAMETER(zFilename);
15771 #endif
15775 ** This routine is the only routine in this file with external
15776 ** linkage.
15778 ** Populate the low-level memory allocation function pointers in
15779 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
15780 ** arguments specify the block of memory to manage.
15782 ** This routine is only called by sqlite3_config(), and therefore
15783 ** is not required to be threadsafe (it is not).
15785 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
15786 static const sqlite3_mem_methods mempoolMethods = {
15787 memsys3Malloc,
15788 memsys3Free,
15789 memsys3Realloc,
15790 memsys3Size,
15791 memsys3Roundup,
15792 memsys3Init,
15793 memsys3Shutdown,
15796 return &mempoolMethods;
15799 #endif /* SQLITE_ENABLE_MEMSYS3 */
15801 /************** End of mem3.c ************************************************/
15802 /************** Begin file mem5.c ********************************************/
15804 ** 2007 October 14
15806 ** The author disclaims copyright to this source code. In place of
15807 ** a legal notice, here is a blessing:
15809 ** May you do good and not evil.
15810 ** May you find forgiveness for yourself and forgive others.
15811 ** May you share freely, never taking more than you give.
15813 *************************************************************************
15814 ** This file contains the C functions that implement a memory
15815 ** allocation subsystem for use by SQLite.
15817 ** This version of the memory allocation subsystem omits all
15818 ** use of malloc(). The application gives SQLite a block of memory
15819 ** before calling sqlite3_initialize() from which allocations
15820 ** are made and returned by the xMalloc() and xRealloc()
15821 ** implementations. Once sqlite3_initialize() has been called,
15822 ** the amount of memory available to SQLite is fixed and cannot
15823 ** be changed.
15825 ** This version of the memory allocation subsystem is included
15826 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
15828 ** This memory allocator uses the following algorithm:
15830 ** 1. All memory allocations sizes are rounded up to a power of 2.
15832 ** 2. If two adjacent free blocks are the halves of a larger block,
15833 ** then the two blocks are coalesed into the single larger block.
15835 ** 3. New memory is allocated from the first available free block.
15837 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
15838 ** Concerning Dynamic Storage Allocation". Journal of the Association for
15839 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
15841 ** Let n be the size of the largest allocation divided by the minimum
15842 ** allocation size (after rounding all sizes up to a power of 2.) Let M
15843 ** be the maximum amount of memory ever outstanding at one time. Let
15844 ** N be the total amount of memory available for allocation. Robson
15845 ** proved that this memory allocator will never breakdown due to
15846 ** fragmentation as long as the following constraint holds:
15848 ** N >= M*(1 + log2(n)/2) - n + 1
15850 ** The sqlite3_status() logic tracks the maximum values of n and M so
15851 ** that an application can, at any time, verify this constraint.
15855 ** This version of the memory allocator is used only when
15856 ** SQLITE_ENABLE_MEMSYS5 is defined.
15858 #ifdef SQLITE_ENABLE_MEMSYS5
15861 ** A minimum allocation is an instance of the following structure.
15862 ** Larger allocations are an array of these structures where the
15863 ** size of the array is a power of 2.
15865 ** The size of this object must be a power of two. That fact is
15866 ** verified in memsys5Init().
15868 typedef struct Mem5Link Mem5Link;
15869 struct Mem5Link {
15870 int next; /* Index of next free chunk */
15871 int prev; /* Index of previous free chunk */
15875 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
15876 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
15877 ** it is not actually possible to reach this limit.
15879 #define LOGMAX 30
15882 ** Masks used for mem5.aCtrl[] elements.
15884 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
15885 #define CTRL_FREE 0x20 /* True if not checked out */
15888 ** All of the static variables used by this module are collected
15889 ** into a single structure named "mem5". This is to keep the
15890 ** static variables organized and to reduce namespace pollution
15891 ** when this module is combined with other in the amalgamation.
15893 static SQLITE_WSD struct Mem5Global {
15895 ** Memory available for allocation
15897 int szAtom; /* Smallest possible allocation in bytes */
15898 int nBlock; /* Number of szAtom sized blocks in zPool */
15899 u8 *zPool; /* Memory available to be allocated */
15902 ** Mutex to control access to the memory allocation subsystem.
15904 sqlite3_mutex *mutex;
15907 ** Performance statistics
15909 u64 nAlloc; /* Total number of calls to malloc */
15910 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
15911 u64 totalExcess; /* Total internal fragmentation */
15912 u32 currentOut; /* Current checkout, including internal fragmentation */
15913 u32 currentCount; /* Current number of distinct checkouts */
15914 u32 maxOut; /* Maximum instantaneous currentOut */
15915 u32 maxCount; /* Maximum instantaneous currentCount */
15916 u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
15919 ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
15920 ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
15921 ** and so forth.
15923 int aiFreelist[LOGMAX+1];
15926 ** Space for tracking which blocks are checked out and the size
15927 ** of each block. One byte per block.
15929 u8 *aCtrl;
15931 } mem5;
15934 ** Access the static variable through a macro for SQLITE_OMIT_WSD
15936 #define mem5 GLOBAL(struct Mem5Global, mem5)
15939 ** Assuming mem5.zPool is divided up into an array of Mem5Link
15940 ** structures, return a pointer to the idx-th such lik.
15942 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
15945 ** Unlink the chunk at mem5.aPool[i] from list it is currently
15946 ** on. It should be found on mem5.aiFreelist[iLogsize].
15948 static void memsys5Unlink(int i, int iLogsize){
15949 int next, prev;
15950 assert( i>=0 && i<mem5.nBlock );
15951 assert( iLogsize>=0 && iLogsize<=LOGMAX );
15952 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15954 next = MEM5LINK(i)->next;
15955 prev = MEM5LINK(i)->prev;
15956 if( prev<0 ){
15957 mem5.aiFreelist[iLogsize] = next;
15958 }else{
15959 MEM5LINK(prev)->next = next;
15961 if( next>=0 ){
15962 MEM5LINK(next)->prev = prev;
15967 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
15968 ** free list.
15970 static void memsys5Link(int i, int iLogsize){
15971 int x;
15972 assert( sqlite3_mutex_held(mem5.mutex) );
15973 assert( i>=0 && i<mem5.nBlock );
15974 assert( iLogsize>=0 && iLogsize<=LOGMAX );
15975 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15977 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
15978 MEM5LINK(i)->prev = -1;
15979 if( x>=0 ){
15980 assert( x<mem5.nBlock );
15981 MEM5LINK(x)->prev = i;
15983 mem5.aiFreelist[iLogsize] = i;
15987 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15988 ** will already be held (obtained by code in malloc.c) if
15989 ** sqlite3GlobalConfig.bMemStat is true.
15991 static void memsys5Enter(void){
15992 sqlite3_mutex_enter(mem5.mutex);
15994 static void memsys5Leave(void){
15995 sqlite3_mutex_leave(mem5.mutex);
15999 ** Return the size of an outstanding allocation, in bytes. The
16000 ** size returned omits the 8-byte header overhead. This only
16001 ** works for chunks that are currently checked out.
16003 static int memsys5Size(void *p){
16004 int iSize = 0;
16005 if( p ){
16006 int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
16007 assert( i>=0 && i<mem5.nBlock );
16008 iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
16010 return iSize;
16014 ** Find the first entry on the freelist iLogsize. Unlink that
16015 ** entry and return its index.
16017 static int memsys5UnlinkFirst(int iLogsize){
16018 int i;
16019 int iFirst;
16021 assert( iLogsize>=0 && iLogsize<=LOGMAX );
16022 i = iFirst = mem5.aiFreelist[iLogsize];
16023 assert( iFirst>=0 );
16024 while( i>0 ){
16025 if( i<iFirst ) iFirst = i;
16026 i = MEM5LINK(i)->next;
16028 memsys5Unlink(iFirst, iLogsize);
16029 return iFirst;
16033 ** Return a block of memory of at least nBytes in size.
16034 ** Return NULL if unable. Return NULL if nBytes==0.
16036 ** The caller guarantees that nByte positive.
16038 ** The caller has obtained a mutex prior to invoking this
16039 ** routine so there is never any chance that two or more
16040 ** threads can be in this routine at the same time.
16042 static void *memsys5MallocUnsafe(int nByte){
16043 int i; /* Index of a mem5.aPool[] slot */
16044 int iBin; /* Index into mem5.aiFreelist[] */
16045 int iFullSz; /* Size of allocation rounded up to power of 2 */
16046 int iLogsize; /* Log2 of iFullSz/POW2_MIN */
16048 /* nByte must be a positive */
16049 assert( nByte>0 );
16051 /* Keep track of the maximum allocation request. Even unfulfilled
16052 ** requests are counted */
16053 if( (u32)nByte>mem5.maxRequest ){
16054 mem5.maxRequest = nByte;
16057 /* Abort if the requested allocation size is larger than the largest
16058 ** power of two that we can represent using 32-bit signed integers.
16060 if( nByte > 0x40000000 ){
16061 return 0;
16064 /* Round nByte up to the next valid power of two */
16065 for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
16067 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
16068 ** block. If not, then split a block of the next larger power of
16069 ** two in order to create a new free block of size iLogsize.
16071 for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
16072 if( iBin>LOGMAX ){
16073 testcase( sqlite3GlobalConfig.xLog!=0 );
16074 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
16075 return 0;
16077 i = memsys5UnlinkFirst(iBin);
16078 while( iBin>iLogsize ){
16079 int newSize;
16081 iBin--;
16082 newSize = 1 << iBin;
16083 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
16084 memsys5Link(i+newSize, iBin);
16086 mem5.aCtrl[i] = iLogsize;
16088 /* Update allocator performance statistics. */
16089 mem5.nAlloc++;
16090 mem5.totalAlloc += iFullSz;
16091 mem5.totalExcess += iFullSz - nByte;
16092 mem5.currentCount++;
16093 mem5.currentOut += iFullSz;
16094 if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
16095 if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
16097 /* Return a pointer to the allocated memory. */
16098 return (void*)&mem5.zPool[i*mem5.szAtom];
16102 ** Free an outstanding memory allocation.
16104 static void memsys5FreeUnsafe(void *pOld){
16105 u32 size, iLogsize;
16106 int iBlock;
16108 /* Set iBlock to the index of the block pointed to by pOld in
16109 ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
16111 iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
16113 /* Check that the pointer pOld points to a valid, non-free block. */
16114 assert( iBlock>=0 && iBlock<mem5.nBlock );
16115 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
16116 assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
16118 iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
16119 size = 1<<iLogsize;
16120 assert( iBlock+size-1<(u32)mem5.nBlock );
16122 mem5.aCtrl[iBlock] |= CTRL_FREE;
16123 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
16124 assert( mem5.currentCount>0 );
16125 assert( mem5.currentOut>=(size*mem5.szAtom) );
16126 mem5.currentCount--;
16127 mem5.currentOut -= size*mem5.szAtom;
16128 assert( mem5.currentOut>0 || mem5.currentCount==0 );
16129 assert( mem5.currentCount>0 || mem5.currentOut==0 );
16131 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16132 while( ALWAYS(iLogsize<LOGMAX) ){
16133 int iBuddy;
16134 if( (iBlock>>iLogsize) & 1 ){
16135 iBuddy = iBlock - size;
16136 }else{
16137 iBuddy = iBlock + size;
16139 assert( iBuddy>=0 );
16140 if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
16141 if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
16142 memsys5Unlink(iBuddy, iLogsize);
16143 iLogsize++;
16144 if( iBuddy<iBlock ){
16145 mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
16146 mem5.aCtrl[iBlock] = 0;
16147 iBlock = iBuddy;
16148 }else{
16149 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16150 mem5.aCtrl[iBuddy] = 0;
16152 size *= 2;
16154 memsys5Link(iBlock, iLogsize);
16158 ** Allocate nBytes of memory
16160 static void *memsys5Malloc(int nBytes){
16161 sqlite3_int64 *p = 0;
16162 if( nBytes>0 ){
16163 memsys5Enter();
16164 p = memsys5MallocUnsafe(nBytes);
16165 memsys5Leave();
16167 return (void*)p;
16171 ** Free memory.
16173 ** The outer layer memory allocator prevents this routine from
16174 ** being called with pPrior==0.
16176 static void memsys5Free(void *pPrior){
16177 assert( pPrior!=0 );
16178 memsys5Enter();
16179 memsys5FreeUnsafe(pPrior);
16180 memsys5Leave();
16184 ** Change the size of an existing memory allocation.
16186 ** The outer layer memory allocator prevents this routine from
16187 ** being called with pPrior==0.
16189 ** nBytes is always a value obtained from a prior call to
16190 ** memsys5Round(). Hence nBytes is always a non-negative power
16191 ** of two. If nBytes==0 that means that an oversize allocation
16192 ** (an allocation larger than 0x40000000) was requested and this
16193 ** routine should return 0 without freeing pPrior.
16195 static void *memsys5Realloc(void *pPrior, int nBytes){
16196 int nOld;
16197 void *p;
16198 assert( pPrior!=0 );
16199 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
16200 assert( nBytes>=0 );
16201 if( nBytes==0 ){
16202 return 0;
16204 nOld = memsys5Size(pPrior);
16205 if( nBytes<=nOld ){
16206 return pPrior;
16208 memsys5Enter();
16209 p = memsys5MallocUnsafe(nBytes);
16210 if( p ){
16211 memcpy(p, pPrior, nOld);
16212 memsys5FreeUnsafe(pPrior);
16214 memsys5Leave();
16215 return p;
16219 ** Round up a request size to the next valid allocation size. If
16220 ** the allocation is too large to be handled by this allocation system,
16221 ** return 0.
16223 ** All allocations must be a power of two and must be expressed by a
16224 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
16225 ** or 1073741824 bytes.
16227 static int memsys5Roundup(int n){
16228 int iFullSz;
16229 if( n > 0x40000000 ) return 0;
16230 for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
16231 return iFullSz;
16235 ** Return the ceiling of the logarithm base 2 of iValue.
16237 ** Examples: memsys5Log(1) -> 0
16238 ** memsys5Log(2) -> 1
16239 ** memsys5Log(4) -> 2
16240 ** memsys5Log(5) -> 3
16241 ** memsys5Log(8) -> 3
16242 ** memsys5Log(9) -> 4
16244 static int memsys5Log(int iValue){
16245 int iLog;
16246 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
16247 return iLog;
16251 ** Initialize the memory allocator.
16253 ** This routine is not threadsafe. The caller must be holding a mutex
16254 ** to prevent multiple threads from entering at the same time.
16256 static int memsys5Init(void *NotUsed){
16257 int ii; /* Loop counter */
16258 int nByte; /* Number of bytes of memory available to this allocator */
16259 u8 *zByte; /* Memory usable by this allocator */
16260 int nMinLog; /* Log base 2 of minimum allocation size in bytes */
16261 int iOffset; /* An offset into mem5.aCtrl[] */
16263 UNUSED_PARAMETER(NotUsed);
16265 /* For the purposes of this routine, disable the mutex */
16266 mem5.mutex = 0;
16268 /* The size of a Mem5Link object must be a power of two. Verify that
16269 ** this is case.
16271 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
16273 nByte = sqlite3GlobalConfig.nHeap;
16274 zByte = (u8*)sqlite3GlobalConfig.pHeap;
16275 assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
16277 /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
16278 nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
16279 mem5.szAtom = (1<<nMinLog);
16280 while( (int)sizeof(Mem5Link)>mem5.szAtom ){
16281 mem5.szAtom = mem5.szAtom << 1;
16284 mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
16285 mem5.zPool = zByte;
16286 mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
16288 for(ii=0; ii<=LOGMAX; ii++){
16289 mem5.aiFreelist[ii] = -1;
16292 iOffset = 0;
16293 for(ii=LOGMAX; ii>=0; ii--){
16294 int nAlloc = (1<<ii);
16295 if( (iOffset+nAlloc)<=mem5.nBlock ){
16296 mem5.aCtrl[iOffset] = ii | CTRL_FREE;
16297 memsys5Link(iOffset, ii);
16298 iOffset += nAlloc;
16300 assert((iOffset+nAlloc)>mem5.nBlock);
16303 /* If a mutex is required for normal operation, allocate one */
16304 if( sqlite3GlobalConfig.bMemstat==0 ){
16305 mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16308 return SQLITE_OK;
16312 ** Deinitialize this module.
16314 static void memsys5Shutdown(void *NotUsed){
16315 UNUSED_PARAMETER(NotUsed);
16316 mem5.mutex = 0;
16317 return;
16320 #ifdef SQLITE_TEST
16322 ** Open the file indicated and write a log of all unfreed memory
16323 ** allocations into that log.
16325 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
16326 FILE *out;
16327 int i, j, n;
16328 int nMinLog;
16330 if( zFilename==0 || zFilename[0]==0 ){
16331 out = stdout;
16332 }else{
16333 out = fopen(zFilename, "w");
16334 if( out==0 ){
16335 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16336 zFilename);
16337 return;
16340 memsys5Enter();
16341 nMinLog = memsys5Log(mem5.szAtom);
16342 for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
16343 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
16344 fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
16346 fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
16347 fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
16348 fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
16349 fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
16350 fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
16351 fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
16352 fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
16353 fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
16354 memsys5Leave();
16355 if( out==stdout ){
16356 fflush(stdout);
16357 }else{
16358 fclose(out);
16361 #endif
16364 ** This routine is the only routine in this file with external
16365 ** linkage. It returns a pointer to a static sqlite3_mem_methods
16366 ** struct populated with the memsys5 methods.
16368 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
16369 static const sqlite3_mem_methods memsys5Methods = {
16370 memsys5Malloc,
16371 memsys5Free,
16372 memsys5Realloc,
16373 memsys5Size,
16374 memsys5Roundup,
16375 memsys5Init,
16376 memsys5Shutdown,
16379 return &memsys5Methods;
16382 #endif /* SQLITE_ENABLE_MEMSYS5 */
16384 /************** End of mem5.c ************************************************/
16385 /************** Begin file mutex.c *******************************************/
16387 ** 2007 August 14
16389 ** The author disclaims copyright to this source code. In place of
16390 ** a legal notice, here is a blessing:
16392 ** May you do good and not evil.
16393 ** May you find forgiveness for yourself and forgive others.
16394 ** May you share freely, never taking more than you give.
16396 *************************************************************************
16397 ** This file contains the C functions that implement mutexes.
16399 ** This file contains code that is common across all mutex implementations.
16402 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
16404 ** For debugging purposes, record when the mutex subsystem is initialized
16405 ** and uninitialized so that we can assert() if there is an attempt to
16406 ** allocate a mutex while the system is uninitialized.
16408 static SQLITE_WSD int mutexIsInit = 0;
16409 #endif /* SQLITE_DEBUG */
16412 #ifndef SQLITE_MUTEX_OMIT
16414 ** Initialize the mutex system.
16416 SQLITE_PRIVATE int sqlite3MutexInit(void){
16417 int rc = SQLITE_OK;
16418 if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
16419 /* If the xMutexAlloc method has not been set, then the user did not
16420 ** install a mutex implementation via sqlite3_config() prior to
16421 ** sqlite3_initialize() being called. This block copies pointers to
16422 ** the default implementation into the sqlite3GlobalConfig structure.
16424 sqlite3_mutex_methods const *pFrom;
16425 sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
16427 if( sqlite3GlobalConfig.bCoreMutex ){
16428 pFrom = sqlite3DefaultMutex();
16429 }else{
16430 pFrom = sqlite3NoopMutex();
16432 memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
16433 memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
16434 sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
16435 pTo->xMutexAlloc = pFrom->xMutexAlloc;
16437 rc = sqlite3GlobalConfig.mutex.xMutexInit();
16439 #ifdef SQLITE_DEBUG
16440 GLOBAL(int, mutexIsInit) = 1;
16441 #endif
16443 return rc;
16447 ** Shutdown the mutex system. This call frees resources allocated by
16448 ** sqlite3MutexInit().
16450 SQLITE_PRIVATE int sqlite3MutexEnd(void){
16451 int rc = SQLITE_OK;
16452 if( sqlite3GlobalConfig.mutex.xMutexEnd ){
16453 rc = sqlite3GlobalConfig.mutex.xMutexEnd();
16456 #ifdef SQLITE_DEBUG
16457 GLOBAL(int, mutexIsInit) = 0;
16458 #endif
16460 return rc;
16464 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
16466 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
16467 #ifndef SQLITE_OMIT_AUTOINIT
16468 if( sqlite3_initialize() ) return 0;
16469 #endif
16470 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16473 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
16474 if( !sqlite3GlobalConfig.bCoreMutex ){
16475 return 0;
16477 assert( GLOBAL(int, mutexIsInit) );
16478 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16482 ** Free a dynamic mutex.
16484 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
16485 if( p ){
16486 sqlite3GlobalConfig.mutex.xMutexFree(p);
16491 ** Obtain the mutex p. If some other thread already has the mutex, block
16492 ** until it can be obtained.
16494 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
16495 if( p ){
16496 sqlite3GlobalConfig.mutex.xMutexEnter(p);
16501 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
16502 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
16504 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
16505 int rc = SQLITE_OK;
16506 if( p ){
16507 return sqlite3GlobalConfig.mutex.xMutexTry(p);
16509 return rc;
16513 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
16514 ** entered by the same thread. The behavior is undefined if the mutex
16515 ** is not currently entered. If a NULL pointer is passed as an argument
16516 ** this function is a no-op.
16518 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
16519 if( p ){
16520 sqlite3GlobalConfig.mutex.xMutexLeave(p);
16524 #ifndef NDEBUG
16526 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16527 ** intended for use inside assert() statements.
16529 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
16530 return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
16532 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
16533 return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
16535 #endif
16537 #endif /* SQLITE_MUTEX_OMIT */
16539 /************** End of mutex.c ***********************************************/
16540 /************** Begin file mutex_noop.c **************************************/
16542 ** 2008 October 07
16544 ** The author disclaims copyright to this source code. In place of
16545 ** a legal notice, here is a blessing:
16547 ** May you do good and not evil.
16548 ** May you find forgiveness for yourself and forgive others.
16549 ** May you share freely, never taking more than you give.
16551 *************************************************************************
16552 ** This file contains the C functions that implement mutexes.
16554 ** This implementation in this file does not provide any mutual
16555 ** exclusion and is thus suitable for use only in applications
16556 ** that use SQLite in a single thread. The routines defined
16557 ** here are place-holders. Applications can substitute working
16558 ** mutex routines at start-time using the
16560 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
16562 ** interface.
16564 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
16565 ** that does error checking on mutexes to make sure they are being
16566 ** called correctly.
16569 #ifndef SQLITE_MUTEX_OMIT
16571 #ifndef SQLITE_DEBUG
16573 ** Stub routines for all mutex methods.
16575 ** This routines provide no mutual exclusion or error checking.
16577 static int noopMutexInit(void){ return SQLITE_OK; }
16578 static int noopMutexEnd(void){ return SQLITE_OK; }
16579 static sqlite3_mutex *noopMutexAlloc(int id){
16580 UNUSED_PARAMETER(id);
16581 return (sqlite3_mutex*)8;
16583 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16584 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16585 static int noopMutexTry(sqlite3_mutex *p){
16586 UNUSED_PARAMETER(p);
16587 return SQLITE_OK;
16589 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16591 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16592 static const sqlite3_mutex_methods sMutex = {
16593 noopMutexInit,
16594 noopMutexEnd,
16595 noopMutexAlloc,
16596 noopMutexFree,
16597 noopMutexEnter,
16598 noopMutexTry,
16599 noopMutexLeave,
16605 return &sMutex;
16607 #endif /* !SQLITE_DEBUG */
16609 #ifdef SQLITE_DEBUG
16611 ** In this implementation, error checking is provided for testing
16612 ** and debugging purposes. The mutexes still do not provide any
16613 ** mutual exclusion.
16617 ** The mutex object
16619 typedef struct sqlite3_debug_mutex {
16620 int id; /* The mutex type */
16621 int cnt; /* Number of entries without a matching leave */
16622 } sqlite3_debug_mutex;
16625 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16626 ** intended for use inside assert() statements.
16628 static int debugMutexHeld(sqlite3_mutex *pX){
16629 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16630 return p==0 || p->cnt>0;
16632 static int debugMutexNotheld(sqlite3_mutex *pX){
16633 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16634 return p==0 || p->cnt==0;
16638 ** Initialize and deinitialize the mutex subsystem.
16640 static int debugMutexInit(void){ return SQLITE_OK; }
16641 static int debugMutexEnd(void){ return SQLITE_OK; }
16644 ** The sqlite3_mutex_alloc() routine allocates a new
16645 ** mutex and returns a pointer to it. If it returns NULL
16646 ** that means that a mutex could not be allocated.
16648 static sqlite3_mutex *debugMutexAlloc(int id){
16649 static sqlite3_debug_mutex aStatic[6];
16650 sqlite3_debug_mutex *pNew = 0;
16651 switch( id ){
16652 case SQLITE_MUTEX_FAST:
16653 case SQLITE_MUTEX_RECURSIVE: {
16654 pNew = sqlite3Malloc(sizeof(*pNew));
16655 if( pNew ){
16656 pNew->id = id;
16657 pNew->cnt = 0;
16659 break;
16661 default: {
16662 assert( id-2 >= 0 );
16663 assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
16664 pNew = &aStatic[id-2];
16665 pNew->id = id;
16666 break;
16669 return (sqlite3_mutex*)pNew;
16673 ** This routine deallocates a previously allocated mutex.
16675 static void debugMutexFree(sqlite3_mutex *pX){
16676 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16677 assert( p->cnt==0 );
16678 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16679 sqlite3_free(p);
16683 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16684 ** to enter a mutex. If another thread is already within the mutex,
16685 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16686 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
16687 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
16688 ** be entered multiple times by the same thread. In such cases the,
16689 ** mutex must be exited an equal number of times before another thread
16690 ** can enter. If the same thread tries to enter any other kind of mutex
16691 ** more than once, the behavior is undefined.
16693 static void debugMutexEnter(sqlite3_mutex *pX){
16694 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16695 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16696 p->cnt++;
16698 static int debugMutexTry(sqlite3_mutex *pX){
16699 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16700 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16701 p->cnt++;
16702 return SQLITE_OK;
16706 ** The sqlite3_mutex_leave() routine exits a mutex that was
16707 ** previously entered by the same thread. The behavior
16708 ** is undefined if the mutex is not currently entered or
16709 ** is not currently allocated. SQLite will never do either.
16711 static void debugMutexLeave(sqlite3_mutex *pX){
16712 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16713 assert( debugMutexHeld(pX) );
16714 p->cnt--;
16715 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16718 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16719 static const sqlite3_mutex_methods sMutex = {
16720 debugMutexInit,
16721 debugMutexEnd,
16722 debugMutexAlloc,
16723 debugMutexFree,
16724 debugMutexEnter,
16725 debugMutexTry,
16726 debugMutexLeave,
16728 debugMutexHeld,
16729 debugMutexNotheld
16732 return &sMutex;
16734 #endif /* SQLITE_DEBUG */
16737 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
16738 ** is used regardless of the run-time threadsafety setting.
16740 #ifdef SQLITE_MUTEX_NOOP
16741 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16742 return sqlite3NoopMutex();
16744 #endif /* SQLITE_MUTEX_NOOP */
16745 #endif /* SQLITE_MUTEX_OMIT */
16747 /************** End of mutex_noop.c ******************************************/
16748 /************** Begin file mutex_os2.c ***************************************/
16750 ** 2007 August 28
16752 ** The author disclaims copyright to this source code. In place of
16753 ** a legal notice, here is a blessing:
16755 ** May you do good and not evil.
16756 ** May you find forgiveness for yourself and forgive others.
16757 ** May you share freely, never taking more than you give.
16759 *************************************************************************
16760 ** This file contains the C functions that implement mutexes for OS/2
16764 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
16765 ** See the mutex.h file for details.
16767 #ifdef SQLITE_MUTEX_OS2
16769 /********************** OS/2 Mutex Implementation **********************
16771 ** This implementation of mutexes is built using the OS/2 API.
16775 ** The mutex object
16776 ** Each recursive mutex is an instance of the following structure.
16778 struct sqlite3_mutex {
16779 HMTX mutex; /* Mutex controlling the lock */
16780 int id; /* Mutex type */
16781 #ifdef SQLITE_DEBUG
16782 int trace; /* True to trace changes */
16783 #endif
16786 #ifdef SQLITE_DEBUG
16787 #define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
16788 #else
16789 #define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
16790 #endif
16793 ** Initialize and deinitialize the mutex subsystem.
16795 static int os2MutexInit(void){ return SQLITE_OK; }
16796 static int os2MutexEnd(void){ return SQLITE_OK; }
16799 ** The sqlite3_mutex_alloc() routine allocates a new
16800 ** mutex and returns a pointer to it. If it returns NULL
16801 ** that means that a mutex could not be allocated.
16802 ** SQLite will unwind its stack and return an error. The argument
16803 ** to sqlite3_mutex_alloc() is one of these integer constants:
16805 ** <ul>
16806 ** <li> SQLITE_MUTEX_FAST
16807 ** <li> SQLITE_MUTEX_RECURSIVE
16808 ** <li> SQLITE_MUTEX_STATIC_MASTER
16809 ** <li> SQLITE_MUTEX_STATIC_MEM
16810 ** <li> SQLITE_MUTEX_STATIC_MEM2
16811 ** <li> SQLITE_MUTEX_STATIC_PRNG
16812 ** <li> SQLITE_MUTEX_STATIC_LRU
16813 ** <li> SQLITE_MUTEX_STATIC_LRU2
16814 ** </ul>
16816 ** The first two constants cause sqlite3_mutex_alloc() to create
16817 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16818 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16819 ** The mutex implementation does not need to make a distinction
16820 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16821 ** not want to. But SQLite will only request a recursive mutex in
16822 ** cases where it really needs one. If a faster non-recursive mutex
16823 ** implementation is available on the host platform, the mutex subsystem
16824 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16826 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16827 ** a pointer to a static preexisting mutex. Six static mutexes are
16828 ** used by the current version of SQLite. Future versions of SQLite
16829 ** may add additional static mutexes. Static mutexes are for internal
16830 ** use by SQLite only. Applications that use SQLite mutexes should
16831 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16832 ** SQLITE_MUTEX_RECURSIVE.
16834 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16835 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16836 ** returns a different mutex on every call. But for the static
16837 ** mutex types, the same mutex is returned on every call that has
16838 ** the same type number.
16840 static sqlite3_mutex *os2MutexAlloc(int iType){
16841 sqlite3_mutex *p = NULL;
16842 switch( iType ){
16843 case SQLITE_MUTEX_FAST:
16844 case SQLITE_MUTEX_RECURSIVE: {
16845 p = sqlite3MallocZero( sizeof(*p) );
16846 if( p ){
16847 p->id = iType;
16848 if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
16849 sqlite3_free( p );
16850 p = NULL;
16853 break;
16855 default: {
16856 static volatile int isInit = 0;
16857 static sqlite3_mutex staticMutexes[6] = {
16858 SQLITE3_MUTEX_INITIALIZER,
16859 SQLITE3_MUTEX_INITIALIZER,
16860 SQLITE3_MUTEX_INITIALIZER,
16861 SQLITE3_MUTEX_INITIALIZER,
16862 SQLITE3_MUTEX_INITIALIZER,
16863 SQLITE3_MUTEX_INITIALIZER,
16865 if ( !isInit ){
16866 APIRET rc;
16867 PTIB ptib;
16868 PPIB ppib;
16869 HMTX mutex;
16870 char name[32];
16871 DosGetInfoBlocks( &ptib, &ppib );
16872 sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
16873 ppib->pib_ulpid );
16874 while( !isInit ){
16875 mutex = 0;
16876 rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
16877 if( rc == NO_ERROR ){
16878 unsigned int i;
16879 if( !isInit ){
16880 for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
16881 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
16883 isInit = 1;
16885 DosCloseMutexSem( mutex );
16886 }else if( rc == ERROR_DUPLICATE_NAME ){
16887 DosSleep( 1 );
16888 }else{
16889 return p;
16893 assert( iType-2 >= 0 );
16894 assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
16895 p = &staticMutexes[iType-2];
16896 p->id = iType;
16897 break;
16900 return p;
16905 ** This routine deallocates a previously allocated mutex.
16906 ** SQLite is careful to deallocate every mutex that it allocates.
16908 static void os2MutexFree(sqlite3_mutex *p){
16909 #ifdef SQLITE_DEBUG
16910 TID tid;
16911 PID pid;
16912 ULONG ulCount;
16913 DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16914 assert( ulCount==0 );
16915 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16916 #endif
16917 DosCloseMutexSem( p->mutex );
16918 sqlite3_free( p );
16921 #ifdef SQLITE_DEBUG
16923 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16924 ** intended for use inside assert() statements.
16926 static int os2MutexHeld(sqlite3_mutex *p){
16927 TID tid;
16928 PID pid;
16929 ULONG ulCount;
16930 PTIB ptib;
16931 DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16932 if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
16933 return 0;
16934 DosGetInfoBlocks(&ptib, NULL);
16935 return tid==ptib->tib_ptib2->tib2_ultid;
16937 static int os2MutexNotheld(sqlite3_mutex *p){
16938 TID tid;
16939 PID pid;
16940 ULONG ulCount;
16941 PTIB ptib;
16942 DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16943 if( ulCount==0 )
16944 return 1;
16945 DosGetInfoBlocks(&ptib, NULL);
16946 return tid!=ptib->tib_ptib2->tib2_ultid;
16948 static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
16949 TID tid;
16950 PID pid;
16951 ULONG ulCount;
16952 DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16953 printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
16955 #endif
16958 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16959 ** to enter a mutex. If another thread is already within the mutex,
16960 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16961 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
16962 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
16963 ** be entered multiple times by the same thread. In such cases the,
16964 ** mutex must be exited an equal number of times before another thread
16965 ** can enter. If the same thread tries to enter any other kind of mutex
16966 ** more than once, the behavior is undefined.
16968 static void os2MutexEnter(sqlite3_mutex *p){
16969 assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16970 DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
16971 #ifdef SQLITE_DEBUG
16972 if( p->trace ) os2MutexTrace(p, "enter");
16973 #endif
16975 static int os2MutexTry(sqlite3_mutex *p){
16976 int rc = SQLITE_BUSY;
16977 assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16978 if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
16979 rc = SQLITE_OK;
16980 #ifdef SQLITE_DEBUG
16981 if( p->trace ) os2MutexTrace(p, "try");
16982 #endif
16984 return rc;
16988 ** The sqlite3_mutex_leave() routine exits a mutex that was
16989 ** previously entered by the same thread. The behavior
16990 ** is undefined if the mutex is not currently entered or
16991 ** is not currently allocated. SQLite will never do either.
16993 static void os2MutexLeave(sqlite3_mutex *p){
16994 assert( os2MutexHeld(p) );
16995 DosReleaseMutexSem(p->mutex);
16996 #ifdef SQLITE_DEBUG
16997 if( p->trace ) os2MutexTrace(p, "leave");
16998 #endif
17001 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17002 static const sqlite3_mutex_methods sMutex = {
17003 os2MutexInit,
17004 os2MutexEnd,
17005 os2MutexAlloc,
17006 os2MutexFree,
17007 os2MutexEnter,
17008 os2MutexTry,
17009 os2MutexLeave,
17010 #ifdef SQLITE_DEBUG
17011 os2MutexHeld,
17012 os2MutexNotheld
17013 #else
17016 #endif
17019 return &sMutex;
17021 #endif /* SQLITE_MUTEX_OS2 */
17023 /************** End of mutex_os2.c *******************************************/
17024 /************** Begin file mutex_unix.c **************************************/
17026 ** 2007 August 28
17028 ** The author disclaims copyright to this source code. In place of
17029 ** a legal notice, here is a blessing:
17031 ** May you do good and not evil.
17032 ** May you find forgiveness for yourself and forgive others.
17033 ** May you share freely, never taking more than you give.
17035 *************************************************************************
17036 ** This file contains the C functions that implement mutexes for pthreads
17040 ** The code in this file is only used if we are compiling threadsafe
17041 ** under unix with pthreads.
17043 ** Note that this implementation requires a version of pthreads that
17044 ** supports recursive mutexes.
17046 #ifdef SQLITE_MUTEX_PTHREADS
17048 #include <pthread.h>
17051 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17052 ** are necessary under two condidtions: (1) Debug builds and (2) using
17053 ** home-grown mutexes. Encapsulate these conditions into a single #define.
17055 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17056 # define SQLITE_MUTEX_NREF 1
17057 #else
17058 # define SQLITE_MUTEX_NREF 0
17059 #endif
17062 ** Each recursive mutex is an instance of the following structure.
17064 struct sqlite3_mutex {
17065 pthread_mutex_t mutex; /* Mutex controlling the lock */
17066 #if SQLITE_MUTEX_NREF
17067 int id; /* Mutex type */
17068 volatile int nRef; /* Number of entrances */
17069 volatile pthread_t owner; /* Thread that is within this mutex */
17070 int trace; /* True to trace changes */
17071 #endif
17073 #if SQLITE_MUTEX_NREF
17074 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17075 #else
17076 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17077 #endif
17080 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17081 ** intended for use only inside assert() statements. On some platforms,
17082 ** there might be race conditions that can cause these routines to
17083 ** deliver incorrect results. In particular, if pthread_equal() is
17084 ** not an atomic operation, then these routines might delivery
17085 ** incorrect results. On most platforms, pthread_equal() is a
17086 ** comparison of two integers and is therefore atomic. But we are
17087 ** told that HPUX is not such a platform. If so, then these routines
17088 ** will not always work correctly on HPUX.
17090 ** On those platforms where pthread_equal() is not atomic, SQLite
17091 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17092 ** make sure no assert() statements are evaluated and hence these
17093 ** routines are never called.
17095 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17096 static int pthreadMutexHeld(sqlite3_mutex *p){
17097 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17099 static int pthreadMutexNotheld(sqlite3_mutex *p){
17100 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17102 #endif
17105 ** Initialize and deinitialize the mutex subsystem.
17107 static int pthreadMutexInit(void){ return SQLITE_OK; }
17108 static int pthreadMutexEnd(void){ return SQLITE_OK; }
17111 ** The sqlite3_mutex_alloc() routine allocates a new
17112 ** mutex and returns a pointer to it. If it returns NULL
17113 ** that means that a mutex could not be allocated. SQLite
17114 ** will unwind its stack and return an error. The argument
17115 ** to sqlite3_mutex_alloc() is one of these integer constants:
17117 ** <ul>
17118 ** <li> SQLITE_MUTEX_FAST
17119 ** <li> SQLITE_MUTEX_RECURSIVE
17120 ** <li> SQLITE_MUTEX_STATIC_MASTER
17121 ** <li> SQLITE_MUTEX_STATIC_MEM
17122 ** <li> SQLITE_MUTEX_STATIC_MEM2
17123 ** <li> SQLITE_MUTEX_STATIC_PRNG
17124 ** <li> SQLITE_MUTEX_STATIC_LRU
17125 ** <li> SQLITE_MUTEX_STATIC_PMEM
17126 ** </ul>
17128 ** The first two constants cause sqlite3_mutex_alloc() to create
17129 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17130 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17131 ** The mutex implementation does not need to make a distinction
17132 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17133 ** not want to. But SQLite will only request a recursive mutex in
17134 ** cases where it really needs one. If a faster non-recursive mutex
17135 ** implementation is available on the host platform, the mutex subsystem
17136 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17138 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17139 ** a pointer to a static preexisting mutex. Six static mutexes are
17140 ** used by the current version of SQLite. Future versions of SQLite
17141 ** may add additional static mutexes. Static mutexes are for internal
17142 ** use by SQLite only. Applications that use SQLite mutexes should
17143 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17144 ** SQLITE_MUTEX_RECURSIVE.
17146 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17147 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17148 ** returns a different mutex on every call. But for the static
17149 ** mutex types, the same mutex is returned on every call that has
17150 ** the same type number.
17152 static sqlite3_mutex *pthreadMutexAlloc(int iType){
17153 static sqlite3_mutex staticMutexes[] = {
17154 SQLITE3_MUTEX_INITIALIZER,
17155 SQLITE3_MUTEX_INITIALIZER,
17156 SQLITE3_MUTEX_INITIALIZER,
17157 SQLITE3_MUTEX_INITIALIZER,
17158 SQLITE3_MUTEX_INITIALIZER,
17159 SQLITE3_MUTEX_INITIALIZER
17161 sqlite3_mutex *p;
17162 switch( iType ){
17163 case SQLITE_MUTEX_RECURSIVE: {
17164 p = sqlite3MallocZero( sizeof(*p) );
17165 if( p ){
17166 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17167 /* If recursive mutexes are not available, we will have to
17168 ** build our own. See below. */
17169 pthread_mutex_init(&p->mutex, 0);
17170 #else
17171 /* Use a recursive mutex if it is available */
17172 pthread_mutexattr_t recursiveAttr;
17173 pthread_mutexattr_init(&recursiveAttr);
17174 pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
17175 pthread_mutex_init(&p->mutex, &recursiveAttr);
17176 pthread_mutexattr_destroy(&recursiveAttr);
17177 #endif
17178 #if SQLITE_MUTEX_NREF
17179 p->id = iType;
17180 #endif
17182 break;
17184 case SQLITE_MUTEX_FAST: {
17185 p = sqlite3MallocZero( sizeof(*p) );
17186 if( p ){
17187 #if SQLITE_MUTEX_NREF
17188 p->id = iType;
17189 #endif
17190 pthread_mutex_init(&p->mutex, 0);
17192 break;
17194 default: {
17195 assert( iType-2 >= 0 );
17196 assert( iType-2 < ArraySize(staticMutexes) );
17197 p = &staticMutexes[iType-2];
17198 #if SQLITE_MUTEX_NREF
17199 p->id = iType;
17200 #endif
17201 break;
17204 return p;
17209 ** This routine deallocates a previously
17210 ** allocated mutex. SQLite is careful to deallocate every
17211 ** mutex that it allocates.
17213 static void pthreadMutexFree(sqlite3_mutex *p){
17214 assert( p->nRef==0 );
17215 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17216 pthread_mutex_destroy(&p->mutex);
17217 sqlite3_free(p);
17221 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17222 ** to enter a mutex. If another thread is already within the mutex,
17223 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17224 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
17225 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
17226 ** be entered multiple times by the same thread. In such cases the,
17227 ** mutex must be exited an equal number of times before another thread
17228 ** can enter. If the same thread tries to enter any other kind of mutex
17229 ** more than once, the behavior is undefined.
17231 static void pthreadMutexEnter(sqlite3_mutex *p){
17232 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17234 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17235 /* If recursive mutexes are not available, then we have to grow
17236 ** our own. This implementation assumes that pthread_equal()
17237 ** is atomic - that it cannot be deceived into thinking self
17238 ** and p->owner are equal if p->owner changes between two values
17239 ** that are not equal to self while the comparison is taking place.
17240 ** This implementation also assumes a coherent cache - that
17241 ** separate processes cannot read different values from the same
17242 ** address at the same time. If either of these two conditions
17243 ** are not met, then the mutexes will fail and problems will result.
17246 pthread_t self = pthread_self();
17247 if( p->nRef>0 && pthread_equal(p->owner, self) ){
17248 p->nRef++;
17249 }else{
17250 pthread_mutex_lock(&p->mutex);
17251 assert( p->nRef==0 );
17252 p->owner = self;
17253 p->nRef = 1;
17256 #else
17257 /* Use the built-in recursive mutexes if they are available.
17259 pthread_mutex_lock(&p->mutex);
17260 #if SQLITE_MUTEX_NREF
17261 assert( p->nRef>0 || p->owner==0 );
17262 p->owner = pthread_self();
17263 p->nRef++;
17264 #endif
17265 #endif
17267 #ifdef SQLITE_DEBUG
17268 if( p->trace ){
17269 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17271 #endif
17273 static int pthreadMutexTry(sqlite3_mutex *p){
17274 int rc;
17275 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17277 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17278 /* If recursive mutexes are not available, then we have to grow
17279 ** our own. This implementation assumes that pthread_equal()
17280 ** is atomic - that it cannot be deceived into thinking self
17281 ** and p->owner are equal if p->owner changes between two values
17282 ** that are not equal to self while the comparison is taking place.
17283 ** This implementation also assumes a coherent cache - that
17284 ** separate processes cannot read different values from the same
17285 ** address at the same time. If either of these two conditions
17286 ** are not met, then the mutexes will fail and problems will result.
17289 pthread_t self = pthread_self();
17290 if( p->nRef>0 && pthread_equal(p->owner, self) ){
17291 p->nRef++;
17292 rc = SQLITE_OK;
17293 }else if( pthread_mutex_trylock(&p->mutex)==0 ){
17294 assert( p->nRef==0 );
17295 p->owner = self;
17296 p->nRef = 1;
17297 rc = SQLITE_OK;
17298 }else{
17299 rc = SQLITE_BUSY;
17302 #else
17303 /* Use the built-in recursive mutexes if they are available.
17305 if( pthread_mutex_trylock(&p->mutex)==0 ){
17306 #if SQLITE_MUTEX_NREF
17307 p->owner = pthread_self();
17308 p->nRef++;
17309 #endif
17310 rc = SQLITE_OK;
17311 }else{
17312 rc = SQLITE_BUSY;
17314 #endif
17316 #ifdef SQLITE_DEBUG
17317 if( rc==SQLITE_OK && p->trace ){
17318 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17320 #endif
17321 return rc;
17325 ** The sqlite3_mutex_leave() routine exits a mutex that was
17326 ** previously entered by the same thread. The behavior
17327 ** is undefined if the mutex is not currently entered or
17328 ** is not currently allocated. SQLite will never do either.
17330 static void pthreadMutexLeave(sqlite3_mutex *p){
17331 assert( pthreadMutexHeld(p) );
17332 #if SQLITE_MUTEX_NREF
17333 p->nRef--;
17334 if( p->nRef==0 ) p->owner = 0;
17335 #endif
17336 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17338 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17339 if( p->nRef==0 ){
17340 pthread_mutex_unlock(&p->mutex);
17342 #else
17343 pthread_mutex_unlock(&p->mutex);
17344 #endif
17346 #ifdef SQLITE_DEBUG
17347 if( p->trace ){
17348 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17350 #endif
17353 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17354 static const sqlite3_mutex_methods sMutex = {
17355 pthreadMutexInit,
17356 pthreadMutexEnd,
17357 pthreadMutexAlloc,
17358 pthreadMutexFree,
17359 pthreadMutexEnter,
17360 pthreadMutexTry,
17361 pthreadMutexLeave,
17362 #ifdef SQLITE_DEBUG
17363 pthreadMutexHeld,
17364 pthreadMutexNotheld
17365 #else
17368 #endif
17371 return &sMutex;
17374 #endif /* SQLITE_MUTEX_PTHREAD */
17376 /************** End of mutex_unix.c ******************************************/
17377 /************** Begin file mutex_w32.c ***************************************/
17379 ** 2007 August 14
17381 ** The author disclaims copyright to this source code. In place of
17382 ** a legal notice, here is a blessing:
17384 ** May you do good and not evil.
17385 ** May you find forgiveness for yourself and forgive others.
17386 ** May you share freely, never taking more than you give.
17388 *************************************************************************
17389 ** This file contains the C functions that implement mutexes for win32
17393 ** The code in this file is only used if we are compiling multithreaded
17394 ** on a win32 system.
17396 #ifdef SQLITE_MUTEX_W32
17399 ** Each recursive mutex is an instance of the following structure.
17401 struct sqlite3_mutex {
17402 CRITICAL_SECTION mutex; /* Mutex controlling the lock */
17403 int id; /* Mutex type */
17404 #ifdef SQLITE_DEBUG
17405 volatile int nRef; /* Number of enterances */
17406 volatile DWORD owner; /* Thread holding this mutex */
17407 int trace; /* True to trace changes */
17408 #endif
17410 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
17411 #ifdef SQLITE_DEBUG
17412 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
17413 #else
17414 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
17415 #endif
17418 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
17419 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
17421 ** Here is an interesting observation: Win95, Win98, and WinME lack
17422 ** the LockFileEx() API. But we can still statically link against that
17423 ** API as long as we don't call it win running Win95/98/ME. A call to
17424 ** this routine is used to determine if the host is Win95/98/ME or
17425 ** WinNT/2K/XP so that we will know whether or not we can safely call
17426 ** the LockFileEx() API.
17428 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
17429 ** which is only available if your application was compiled with
17430 ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
17431 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
17432 ** this out as well.
17434 #if 0
17435 #if SQLITE_OS_WINCE
17436 # define mutexIsNT() (1)
17437 #else
17438 static int mutexIsNT(void){
17439 static int osType = 0;
17440 if( osType==0 ){
17441 OSVERSIONINFO sInfo;
17442 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
17443 GetVersionEx(&sInfo);
17444 osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
17446 return osType==2;
17448 #endif /* SQLITE_OS_WINCE */
17449 #endif
17451 #ifdef SQLITE_DEBUG
17453 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17454 ** intended for use only inside assert() statements.
17456 static int winMutexHeld(sqlite3_mutex *p){
17457 return p->nRef!=0 && p->owner==GetCurrentThreadId();
17459 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
17460 return p->nRef==0 || p->owner!=tid;
17462 static int winMutexNotheld(sqlite3_mutex *p){
17463 DWORD tid = GetCurrentThreadId();
17464 return winMutexNotheld2(p, tid);
17466 #endif
17470 ** Initialize and deinitialize the mutex subsystem.
17472 static sqlite3_mutex winMutex_staticMutexes[6] = {
17473 SQLITE3_MUTEX_INITIALIZER,
17474 SQLITE3_MUTEX_INITIALIZER,
17475 SQLITE3_MUTEX_INITIALIZER,
17476 SQLITE3_MUTEX_INITIALIZER,
17477 SQLITE3_MUTEX_INITIALIZER,
17478 SQLITE3_MUTEX_INITIALIZER
17480 static int winMutex_isInit = 0;
17481 /* As winMutexInit() and winMutexEnd() are called as part
17482 ** of the sqlite3_initialize and sqlite3_shutdown()
17483 ** processing, the "interlocked" magic is probably not
17484 ** strictly necessary.
17486 static long winMutex_lock = 0;
17488 static int winMutexInit(void){
17489 /* The first to increment to 1 does actual initialization */
17490 if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
17491 int i;
17492 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17493 InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
17495 winMutex_isInit = 1;
17496 }else{
17497 /* Someone else is in the process of initing the static mutexes */
17498 while( !winMutex_isInit ){
17499 Sleep(1);
17502 return SQLITE_OK;
17505 static int winMutexEnd(void){
17506 /* The first to decrement to 0 does actual shutdown
17507 ** (which should be the last to shutdown.) */
17508 if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
17509 if( winMutex_isInit==1 ){
17510 int i;
17511 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17512 DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
17514 winMutex_isInit = 0;
17517 return SQLITE_OK;
17521 ** The sqlite3_mutex_alloc() routine allocates a new
17522 ** mutex and returns a pointer to it. If it returns NULL
17523 ** that means that a mutex could not be allocated. SQLite
17524 ** will unwind its stack and return an error. The argument
17525 ** to sqlite3_mutex_alloc() is one of these integer constants:
17527 ** <ul>
17528 ** <li> SQLITE_MUTEX_FAST
17529 ** <li> SQLITE_MUTEX_RECURSIVE
17530 ** <li> SQLITE_MUTEX_STATIC_MASTER
17531 ** <li> SQLITE_MUTEX_STATIC_MEM
17532 ** <li> SQLITE_MUTEX_STATIC_MEM2
17533 ** <li> SQLITE_MUTEX_STATIC_PRNG
17534 ** <li> SQLITE_MUTEX_STATIC_LRU
17535 ** <li> SQLITE_MUTEX_STATIC_PMEM
17536 ** </ul>
17538 ** The first two constants cause sqlite3_mutex_alloc() to create
17539 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17540 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17541 ** The mutex implementation does not need to make a distinction
17542 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17543 ** not want to. But SQLite will only request a recursive mutex in
17544 ** cases where it really needs one. If a faster non-recursive mutex
17545 ** implementation is available on the host platform, the mutex subsystem
17546 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17548 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17549 ** a pointer to a static preexisting mutex. Six static mutexes are
17550 ** used by the current version of SQLite. Future versions of SQLite
17551 ** may add additional static mutexes. Static mutexes are for internal
17552 ** use by SQLite only. Applications that use SQLite mutexes should
17553 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17554 ** SQLITE_MUTEX_RECURSIVE.
17556 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17557 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17558 ** returns a different mutex on every call. But for the static
17559 ** mutex types, the same mutex is returned on every call that has
17560 ** the same type number.
17562 static sqlite3_mutex *winMutexAlloc(int iType){
17563 sqlite3_mutex *p;
17565 switch( iType ){
17566 case SQLITE_MUTEX_FAST:
17567 case SQLITE_MUTEX_RECURSIVE: {
17568 p = sqlite3MallocZero( sizeof(*p) );
17569 if( p ){
17570 #ifdef SQLITE_DEBUG
17571 p->id = iType;
17572 #endif
17573 InitializeCriticalSection(&p->mutex);
17575 break;
17577 default: {
17578 assert( winMutex_isInit==1 );
17579 assert( iType-2 >= 0 );
17580 assert( iType-2 < ArraySize(winMutex_staticMutexes) );
17581 p = &winMutex_staticMutexes[iType-2];
17582 #ifdef SQLITE_DEBUG
17583 p->id = iType;
17584 #endif
17585 break;
17588 return p;
17593 ** This routine deallocates a previously
17594 ** allocated mutex. SQLite is careful to deallocate every
17595 ** mutex that it allocates.
17597 static void winMutexFree(sqlite3_mutex *p){
17598 assert( p );
17599 assert( p->nRef==0 && p->owner==0 );
17600 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17601 DeleteCriticalSection(&p->mutex);
17602 sqlite3_free(p);
17606 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17607 ** to enter a mutex. If another thread is already within the mutex,
17608 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17609 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
17610 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
17611 ** be entered multiple times by the same thread. In such cases the,
17612 ** mutex must be exited an equal number of times before another thread
17613 ** can enter. If the same thread tries to enter any other kind of mutex
17614 ** more than once, the behavior is undefined.
17616 static void winMutexEnter(sqlite3_mutex *p){
17617 #ifdef SQLITE_DEBUG
17618 DWORD tid = GetCurrentThreadId();
17619 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17620 #endif
17621 EnterCriticalSection(&p->mutex);
17622 #ifdef SQLITE_DEBUG
17623 assert( p->nRef>0 || p->owner==0 );
17624 p->owner = tid;
17625 p->nRef++;
17626 if( p->trace ){
17627 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17629 #endif
17631 static int winMutexTry(sqlite3_mutex *p){
17632 #ifndef NDEBUG
17633 DWORD tid = GetCurrentThreadId();
17634 #endif
17635 int rc = SQLITE_BUSY;
17636 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17638 ** The sqlite3_mutex_try() routine is very rarely used, and when it
17639 ** is used it is merely an optimization. So it is OK for it to always
17640 ** fail.
17642 ** The TryEnterCriticalSection() interface is only available on WinNT.
17643 ** And some windows compilers complain if you try to use it without
17644 ** first doing some #defines that prevent SQLite from building on Win98.
17645 ** For that reason, we will omit this optimization for now. See
17646 ** ticket #2685.
17648 #if 0
17649 if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
17650 p->owner = tid;
17651 p->nRef++;
17652 rc = SQLITE_OK;
17654 #else
17655 UNUSED_PARAMETER(p);
17656 #endif
17657 #ifdef SQLITE_DEBUG
17658 if( rc==SQLITE_OK && p->trace ){
17659 printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17661 #endif
17662 return rc;
17666 ** The sqlite3_mutex_leave() routine exits a mutex that was
17667 ** previously entered by the same thread. The behavior
17668 ** is undefined if the mutex is not currently entered or
17669 ** is not currently allocated. SQLite will never do either.
17671 static void winMutexLeave(sqlite3_mutex *p){
17672 #ifndef NDEBUG
17673 DWORD tid = GetCurrentThreadId();
17674 assert( p->nRef>0 );
17675 assert( p->owner==tid );
17676 p->nRef--;
17677 if( p->nRef==0 ) p->owner = 0;
17678 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17679 #endif
17680 LeaveCriticalSection(&p->mutex);
17681 #ifdef SQLITE_DEBUG
17682 if( p->trace ){
17683 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17685 #endif
17688 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17689 static const sqlite3_mutex_methods sMutex = {
17690 winMutexInit,
17691 winMutexEnd,
17692 winMutexAlloc,
17693 winMutexFree,
17694 winMutexEnter,
17695 winMutexTry,
17696 winMutexLeave,
17697 #ifdef SQLITE_DEBUG
17698 winMutexHeld,
17699 winMutexNotheld
17700 #else
17703 #endif
17706 return &sMutex;
17708 #endif /* SQLITE_MUTEX_W32 */
17710 /************** End of mutex_w32.c *******************************************/
17711 /************** Begin file malloc.c ******************************************/
17713 ** 2001 September 15
17715 ** The author disclaims copyright to this source code. In place of
17716 ** a legal notice, here is a blessing:
17718 ** May you do good and not evil.
17719 ** May you find forgiveness for yourself and forgive others.
17720 ** May you share freely, never taking more than you give.
17722 *************************************************************************
17724 ** Memory allocation functions used throughout sqlite.
17728 ** Attempt to release up to n bytes of non-essential memory currently
17729 ** held by SQLite. An example of non-essential memory is memory used to
17730 ** cache database pages that are not currently in use.
17732 SQLITE_API int sqlite3_release_memory(int n){
17733 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17734 return sqlite3PcacheReleaseMemory(n);
17735 #else
17736 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
17737 ** is a no-op returning zero if SQLite is not compiled with
17738 ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
17739 UNUSED_PARAMETER(n);
17740 return 0;
17741 #endif
17745 ** An instance of the following object records the location of
17746 ** each unused scratch buffer.
17748 typedef struct ScratchFreeslot {
17749 struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
17750 } ScratchFreeslot;
17753 ** State information local to the memory allocation subsystem.
17755 static SQLITE_WSD struct Mem0Global {
17756 sqlite3_mutex *mutex; /* Mutex to serialize access */
17759 ** The alarm callback and its arguments. The mem0.mutex lock will
17760 ** be held while the callback is running. Recursive calls into
17761 ** the memory subsystem are allowed, but no new callbacks will be
17762 ** issued.
17764 sqlite3_int64 alarmThreshold;
17765 void (*alarmCallback)(void*, sqlite3_int64,int);
17766 void *alarmArg;
17769 ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
17770 ** (so that a range test can be used to determine if an allocation
17771 ** being freed came from pScratch) and a pointer to the list of
17772 ** unused scratch allocations.
17774 void *pScratchEnd;
17775 ScratchFreeslot *pScratchFree;
17776 u32 nScratchFree;
17779 ** True if heap is nearly "full" where "full" is defined by the
17780 ** sqlite3_soft_heap_limit() setting.
17782 int nearlyFull;
17783 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17785 #define mem0 GLOBAL(struct Mem0Global, mem0)
17788 ** This routine runs when the memory allocator sees that the
17789 ** total memory allocation is about to exceed the soft heap
17790 ** limit.
17792 static void softHeapLimitEnforcer(
17793 void *NotUsed,
17794 sqlite3_int64 NotUsed2,
17795 int allocSize
17797 UNUSED_PARAMETER2(NotUsed, NotUsed2);
17798 sqlite3_release_memory(allocSize);
17802 ** Change the alarm callback
17804 static int sqlite3MemoryAlarm(
17805 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17806 void *pArg,
17807 sqlite3_int64 iThreshold
17809 int nUsed;
17810 sqlite3_mutex_enter(mem0.mutex);
17811 mem0.alarmCallback = xCallback;
17812 mem0.alarmArg = pArg;
17813 mem0.alarmThreshold = iThreshold;
17814 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17815 mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
17816 sqlite3_mutex_leave(mem0.mutex);
17817 return SQLITE_OK;
17820 #ifndef SQLITE_OMIT_DEPRECATED
17822 ** Deprecated external interface. Internal/core SQLite code
17823 ** should call sqlite3MemoryAlarm.
17825 SQLITE_API int sqlite3_memory_alarm(
17826 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17827 void *pArg,
17828 sqlite3_int64 iThreshold
17830 return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17832 #endif
17835 ** Set the soft heap-size limit for the library. Passing a zero or
17836 ** negative value indicates no limit.
17838 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
17839 sqlite3_int64 priorLimit;
17840 sqlite3_int64 excess;
17841 #ifndef SQLITE_OMIT_AUTOINIT
17842 sqlite3_initialize();
17843 #endif
17844 sqlite3_mutex_enter(mem0.mutex);
17845 priorLimit = mem0.alarmThreshold;
17846 sqlite3_mutex_leave(mem0.mutex);
17847 if( n<0 ) return priorLimit;
17848 if( n>0 ){
17849 sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
17850 }else{
17851 sqlite3MemoryAlarm(0, 0, 0);
17853 excess = sqlite3_memory_used() - n;
17854 if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
17855 return priorLimit;
17857 SQLITE_API void sqlite3_soft_heap_limit(int n){
17858 if( n<0 ) n = 0;
17859 sqlite3_soft_heap_limit64(n);
17863 ** Initialize the memory allocation subsystem.
17865 SQLITE_PRIVATE int sqlite3MallocInit(void){
17866 if( sqlite3GlobalConfig.m.xMalloc==0 ){
17867 sqlite3MemSetDefault();
17869 memset(&mem0, 0, sizeof(mem0));
17870 if( sqlite3GlobalConfig.bCoreMutex ){
17871 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17873 if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17874 && sqlite3GlobalConfig.nScratch>0 ){
17875 int i, n, sz;
17876 ScratchFreeslot *pSlot;
17877 sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
17878 sqlite3GlobalConfig.szScratch = sz;
17879 pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
17880 n = sqlite3GlobalConfig.nScratch;
17881 mem0.pScratchFree = pSlot;
17882 mem0.nScratchFree = n;
17883 for(i=0; i<n-1; i++){
17884 pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
17885 pSlot = pSlot->pNext;
17887 pSlot->pNext = 0;
17888 mem0.pScratchEnd = (void*)&pSlot[1];
17889 }else{
17890 mem0.pScratchEnd = 0;
17891 sqlite3GlobalConfig.pScratch = 0;
17892 sqlite3GlobalConfig.szScratch = 0;
17893 sqlite3GlobalConfig.nScratch = 0;
17895 if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
17896 || sqlite3GlobalConfig.nPage<1 ){
17897 sqlite3GlobalConfig.pPage = 0;
17898 sqlite3GlobalConfig.szPage = 0;
17899 sqlite3GlobalConfig.nPage = 0;
17901 return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17905 ** Return true if the heap is currently under memory pressure - in other
17906 ** words if the amount of heap used is close to the limit set by
17907 ** sqlite3_soft_heap_limit().
17909 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
17910 return mem0.nearlyFull;
17914 ** Deinitialize the memory allocation subsystem.
17916 SQLITE_PRIVATE void sqlite3MallocEnd(void){
17917 if( sqlite3GlobalConfig.m.xShutdown ){
17918 sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
17920 memset(&mem0, 0, sizeof(mem0));
17924 ** Return the amount of memory currently checked out.
17926 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
17927 int n, mx;
17928 sqlite3_int64 res;
17929 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
17930 res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
17931 return res;
17935 ** Return the maximum amount of memory that has ever been
17936 ** checked out since either the beginning of this process
17937 ** or since the most recent reset.
17939 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
17940 int n, mx;
17941 sqlite3_int64 res;
17942 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17943 res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
17944 return res;
17948 ** Trigger the alarm
17950 static void sqlite3MallocAlarm(int nByte){
17951 void (*xCallback)(void*,sqlite3_int64,int);
17952 sqlite3_int64 nowUsed;
17953 void *pArg;
17954 if( mem0.alarmCallback==0 ) return;
17955 xCallback = mem0.alarmCallback;
17956 nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17957 pArg = mem0.alarmArg;
17958 mem0.alarmCallback = 0;
17959 sqlite3_mutex_leave(mem0.mutex);
17960 xCallback(pArg, nowUsed, nByte);
17961 sqlite3_mutex_enter(mem0.mutex);
17962 mem0.alarmCallback = xCallback;
17963 mem0.alarmArg = pArg;
17967 ** Do a memory allocation with statistics and alarms. Assume the
17968 ** lock is already held.
17970 static int mallocWithAlarm(int n, void **pp){
17971 int nFull;
17972 void *p;
17973 assert( sqlite3_mutex_held(mem0.mutex) );
17974 nFull = sqlite3GlobalConfig.m.xRoundup(n);
17975 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17976 if( mem0.alarmCallback!=0 ){
17977 int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17978 if( nUsed+nFull >= mem0.alarmThreshold ){
17979 mem0.nearlyFull = 1;
17980 sqlite3MallocAlarm(nFull);
17981 }else{
17982 mem0.nearlyFull = 0;
17985 p = sqlite3GlobalConfig.m.xMalloc(nFull);
17986 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17987 if( p==0 && mem0.alarmCallback ){
17988 sqlite3MallocAlarm(nFull);
17989 p = sqlite3GlobalConfig.m.xMalloc(nFull);
17991 #endif
17992 if( p ){
17993 nFull = sqlite3MallocSize(p);
17994 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
17995 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
17997 *pp = p;
17998 return nFull;
18002 ** Allocate memory. This routine is like sqlite3_malloc() except that it
18003 ** assumes the memory subsystem has already been initialized.
18005 SQLITE_PRIVATE void *sqlite3Malloc(int n){
18006 void *p;
18007 if( n<=0 /* IMP: R-65312-04917 */
18008 || n>=0x7fffff00
18010 /* A memory allocation of a number of bytes which is near the maximum
18011 ** signed integer value might cause an integer overflow inside of the
18012 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
18013 ** 255 bytes of overhead. SQLite itself will never use anything near
18014 ** this amount. The only way to reach the limit is with sqlite3_malloc() */
18015 p = 0;
18016 }else if( sqlite3GlobalConfig.bMemstat ){
18017 sqlite3_mutex_enter(mem0.mutex);
18018 mallocWithAlarm(n, &p);
18019 sqlite3_mutex_leave(mem0.mutex);
18020 }else{
18021 p = sqlite3GlobalConfig.m.xMalloc(n);
18023 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
18024 return p;
18028 ** This version of the memory allocation is for use by the application.
18029 ** First make sure the memory subsystem is initialized, then do the
18030 ** allocation.
18032 SQLITE_API void *sqlite3_malloc(int n){
18033 #ifndef SQLITE_OMIT_AUTOINIT
18034 if( sqlite3_initialize() ) return 0;
18035 #endif
18036 return sqlite3Malloc(n);
18040 ** Each thread may only have a single outstanding allocation from
18041 ** xScratchMalloc(). We verify this constraint in the single-threaded
18042 ** case by setting scratchAllocOut to 1 when an allocation
18043 ** is outstanding clearing it when the allocation is freed.
18045 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18046 static int scratchAllocOut = 0;
18047 #endif
18051 ** Allocate memory that is to be used and released right away.
18052 ** This routine is similar to alloca() in that it is not intended
18053 ** for situations where the memory might be held long-term. This
18054 ** routine is intended to get memory to old large transient data
18055 ** structures that would not normally fit on the stack of an
18056 ** embedded processor.
18058 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18059 void *p;
18060 assert( n>0 );
18062 sqlite3_mutex_enter(mem0.mutex);
18063 if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18064 p = mem0.pScratchFree;
18065 mem0.pScratchFree = mem0.pScratchFree->pNext;
18066 mem0.nScratchFree--;
18067 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18068 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18069 sqlite3_mutex_leave(mem0.mutex);
18070 }else{
18071 if( sqlite3GlobalConfig.bMemstat ){
18072 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18073 n = mallocWithAlarm(n, &p);
18074 if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18075 sqlite3_mutex_leave(mem0.mutex);
18076 }else{
18077 sqlite3_mutex_leave(mem0.mutex);
18078 p = sqlite3GlobalConfig.m.xMalloc(n);
18080 sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18082 assert( sqlite3_mutex_notheld(mem0.mutex) );
18085 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18086 /* Verify that no more than two scratch allocations per thread
18087 ** are outstanding at one time. (This is only checked in the
18088 ** single-threaded case since checking in the multi-threaded case
18089 ** would be much more complicated.) */
18090 assert( scratchAllocOut<=1 );
18091 if( p ) scratchAllocOut++;
18092 #endif
18094 return p;
18096 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18097 if( p ){
18099 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18100 /* Verify that no more than two scratch allocation per thread
18101 ** is outstanding at one time. (This is only checked in the
18102 ** single-threaded case since checking in the multi-threaded case
18103 ** would be much more complicated.) */
18104 assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18105 scratchAllocOut--;
18106 #endif
18108 if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18109 /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18110 ScratchFreeslot *pSlot;
18111 pSlot = (ScratchFreeslot*)p;
18112 sqlite3_mutex_enter(mem0.mutex);
18113 pSlot->pNext = mem0.pScratchFree;
18114 mem0.pScratchFree = pSlot;
18115 mem0.nScratchFree++;
18116 assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18117 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18118 sqlite3_mutex_leave(mem0.mutex);
18119 }else{
18120 /* Release memory back to the heap */
18121 assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18122 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
18123 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18124 if( sqlite3GlobalConfig.bMemstat ){
18125 int iSize = sqlite3MallocSize(p);
18126 sqlite3_mutex_enter(mem0.mutex);
18127 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
18128 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
18129 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18130 sqlite3GlobalConfig.m.xFree(p);
18131 sqlite3_mutex_leave(mem0.mutex);
18132 }else{
18133 sqlite3GlobalConfig.m.xFree(p);
18140 ** TRUE if p is a lookaside memory allocation from db
18142 #ifndef SQLITE_OMIT_LOOKASIDE
18143 static int isLookaside(sqlite3 *db, void *p){
18144 return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
18146 #else
18147 #define isLookaside(A,B) 0
18148 #endif
18151 ** Return the size of a memory allocation previously obtained from
18152 ** sqlite3Malloc() or sqlite3_malloc().
18154 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
18155 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18156 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18157 return sqlite3GlobalConfig.m.xSize(p);
18159 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
18160 assert( db==0 || sqlite3_mutex_held(db->mutex) );
18161 if( db && isLookaside(db, p) ){
18162 return db->lookaside.sz;
18163 }else{
18164 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18165 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18166 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18167 return sqlite3GlobalConfig.m.xSize(p);
18172 ** Free memory previously obtained from sqlite3Malloc().
18174 SQLITE_API void sqlite3_free(void *p){
18175 if( p==0 ) return; /* IMP: R-49053-54554 */
18176 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18177 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18178 if( sqlite3GlobalConfig.bMemstat ){
18179 sqlite3_mutex_enter(mem0.mutex);
18180 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
18181 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18182 sqlite3GlobalConfig.m.xFree(p);
18183 sqlite3_mutex_leave(mem0.mutex);
18184 }else{
18185 sqlite3GlobalConfig.m.xFree(p);
18190 ** Free memory that might be associated with a particular database
18191 ** connection.
18193 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
18194 assert( db==0 || sqlite3_mutex_held(db->mutex) );
18195 if( db ){
18196 if( db->pnBytesFreed ){
18197 *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
18198 return;
18200 if( isLookaside(db, p) ){
18201 LookasideSlot *pBuf = (LookasideSlot*)p;
18202 pBuf->pNext = db->lookaside.pFree;
18203 db->lookaside.pFree = pBuf;
18204 db->lookaside.nOut--;
18205 return;
18208 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18209 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18210 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18211 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18212 sqlite3_free(p);
18216 ** Change the size of an existing memory allocation
18218 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
18219 int nOld, nNew;
18220 void *pNew;
18221 if( pOld==0 ){
18222 return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
18224 if( nBytes<=0 ){
18225 sqlite3_free(pOld); /* IMP: R-31593-10574 */
18226 return 0;
18228 if( nBytes>=0x7fffff00 ){
18229 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
18230 return 0;
18232 nOld = sqlite3MallocSize(pOld);
18233 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
18234 ** argument to xRealloc is always a value returned by a prior call to
18235 ** xRoundup. */
18236 nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
18237 if( nOld==nNew ){
18238 pNew = pOld;
18239 }else if( sqlite3GlobalConfig.bMemstat ){
18240 sqlite3_mutex_enter(mem0.mutex);
18241 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
18242 if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
18243 mem0.alarmThreshold ){
18244 sqlite3MallocAlarm(nNew-nOld);
18246 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
18247 assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
18248 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18249 if( pNew==0 && mem0.alarmCallback ){
18250 sqlite3MallocAlarm(nBytes);
18251 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18253 if( pNew ){
18254 nNew = sqlite3MallocSize(pNew);
18255 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
18257 sqlite3_mutex_leave(mem0.mutex);
18258 }else{
18259 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18261 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
18262 return pNew;
18266 ** The public interface to sqlite3Realloc. Make sure that the memory
18267 ** subsystem is initialized prior to invoking sqliteRealloc.
18269 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
18270 #ifndef SQLITE_OMIT_AUTOINIT
18271 if( sqlite3_initialize() ) return 0;
18272 #endif
18273 return sqlite3Realloc(pOld, n);
18278 ** Allocate and zero memory.
18280 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
18281 void *p = sqlite3Malloc(n);
18282 if( p ){
18283 memset(p, 0, n);
18285 return p;
18289 ** Allocate and zero memory. If the allocation fails, make
18290 ** the mallocFailed flag in the connection pointer.
18292 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
18293 void *p = sqlite3DbMallocRaw(db, n);
18294 if( p ){
18295 memset(p, 0, n);
18297 return p;
18301 ** Allocate and zero memory. If the allocation fails, make
18302 ** the mallocFailed flag in the connection pointer.
18304 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
18305 ** failure on the same database connection) then always return 0.
18306 ** Hence for a particular database connection, once malloc starts
18307 ** failing, it fails consistently until mallocFailed is reset.
18308 ** This is an important assumption. There are many places in the
18309 ** code that do things like this:
18311 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
18312 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
18313 ** if( b ) a[10] = 9;
18315 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
18316 ** that all prior mallocs (ex: "a") worked too.
18318 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
18319 void *p;
18320 assert( db==0 || sqlite3_mutex_held(db->mutex) );
18321 assert( db==0 || db->pnBytesFreed==0 );
18322 #ifndef SQLITE_OMIT_LOOKASIDE
18323 if( db ){
18324 LookasideSlot *pBuf;
18325 if( db->mallocFailed ){
18326 return 0;
18328 if( db->lookaside.bEnabled ){
18329 if( n>db->lookaside.sz ){
18330 db->lookaside.anStat[1]++;
18331 }else if( (pBuf = db->lookaside.pFree)==0 ){
18332 db->lookaside.anStat[2]++;
18333 }else{
18334 db->lookaside.pFree = pBuf->pNext;
18335 db->lookaside.nOut++;
18336 db->lookaside.anStat[0]++;
18337 if( db->lookaside.nOut>db->lookaside.mxOut ){
18338 db->lookaside.mxOut = db->lookaside.nOut;
18340 return (void*)pBuf;
18344 #else
18345 if( db && db->mallocFailed ){
18346 return 0;
18348 #endif
18349 p = sqlite3Malloc(n);
18350 if( !p && db ){
18351 db->mallocFailed = 1;
18353 sqlite3MemdebugSetType(p, MEMTYPE_DB |
18354 ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18355 return p;
18359 ** Resize the block of memory pointed to by p to n bytes. If the
18360 ** resize fails, set the mallocFailed flag in the connection object.
18362 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
18363 void *pNew = 0;
18364 assert( db!=0 );
18365 assert( sqlite3_mutex_held(db->mutex) );
18366 if( db->mallocFailed==0 ){
18367 if( p==0 ){
18368 return sqlite3DbMallocRaw(db, n);
18370 if( isLookaside(db, p) ){
18371 if( n<=db->lookaside.sz ){
18372 return p;
18374 pNew = sqlite3DbMallocRaw(db, n);
18375 if( pNew ){
18376 memcpy(pNew, p, db->lookaside.sz);
18377 sqlite3DbFree(db, p);
18379 }else{
18380 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18381 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18382 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18383 pNew = sqlite3_realloc(p, n);
18384 if( !pNew ){
18385 sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
18386 db->mallocFailed = 1;
18388 sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
18389 (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18392 return pNew;
18396 ** Attempt to reallocate p. If the reallocation fails, then free p
18397 ** and set the mallocFailed flag in the database connection.
18399 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
18400 void *pNew;
18401 pNew = sqlite3DbRealloc(db, p, n);
18402 if( !pNew ){
18403 sqlite3DbFree(db, p);
18405 return pNew;
18409 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
18410 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
18411 ** is because when memory debugging is turned on, these two functions are
18412 ** called via macros that record the current file and line number in the
18413 ** ThreadData structure.
18415 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
18416 char *zNew;
18417 size_t n;
18418 if( z==0 ){
18419 return 0;
18421 n = sqlite3Strlen30(z) + 1;
18422 assert( (n&0x7fffffff)==n );
18423 zNew = sqlite3DbMallocRaw(db, (int)n);
18424 if( zNew ){
18425 memcpy(zNew, z, n);
18427 return zNew;
18429 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
18430 char *zNew;
18431 if( z==0 ){
18432 return 0;
18434 assert( (n&0x7fffffff)==n );
18435 zNew = sqlite3DbMallocRaw(db, n+1);
18436 if( zNew ){
18437 memcpy(zNew, z, n);
18438 zNew[n] = 0;
18440 return zNew;
18444 ** Create a string from the zFromat argument and the va_list that follows.
18445 ** Store the string in memory obtained from sqliteMalloc() and make *pz
18446 ** point to that string.
18448 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
18449 va_list ap;
18450 char *z;
18452 va_start(ap, zFormat);
18453 z = sqlite3VMPrintf(db, zFormat, ap);
18454 va_end(ap);
18455 sqlite3DbFree(db, *pz);
18456 *pz = z;
18461 ** This function must be called before exiting any API function (i.e.
18462 ** returning control to the user) that has called sqlite3_malloc or
18463 ** sqlite3_realloc.
18465 ** The returned value is normally a copy of the second argument to this
18466 ** function. However, if a malloc() failure has occurred since the previous
18467 ** invocation SQLITE_NOMEM is returned instead.
18469 ** If the first argument, db, is not NULL and a malloc() error has occurred,
18470 ** then the connection error-code (the value returned by sqlite3_errcode())
18471 ** is set to SQLITE_NOMEM.
18473 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
18474 /* If the db handle is not NULL, then we must hold the connection handle
18475 ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
18476 ** is unsafe, as is the call to sqlite3Error().
18478 assert( !db || sqlite3_mutex_held(db->mutex) );
18479 if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
18480 sqlite3Error(db, SQLITE_NOMEM, 0);
18481 db->mallocFailed = 0;
18482 rc = SQLITE_NOMEM;
18484 return rc & (db ? db->errMask : 0xff);
18487 /************** End of malloc.c **********************************************/
18488 /************** Begin file printf.c ******************************************/
18490 ** The "printf" code that follows dates from the 1980's. It is in
18491 ** the public domain. The original comments are included here for
18492 ** completeness. They are very out-of-date but might be useful as
18493 ** an historical reference. Most of the "enhancements" have been backed
18494 ** out so that the functionality is now the same as standard printf().
18496 **************************************************************************
18498 ** The following modules is an enhanced replacement for the "printf" subroutines
18499 ** found in the standard C library. The following enhancements are
18500 ** supported:
18502 ** + Additional functions. The standard set of "printf" functions
18503 ** includes printf, fprintf, sprintf, vprintf, vfprintf, and
18504 ** vsprintf. This module adds the following:
18506 ** * snprintf -- Works like sprintf, but has an extra argument
18507 ** which is the size of the buffer written to.
18509 ** * mprintf -- Similar to sprintf. Writes output to memory
18510 ** obtained from malloc.
18512 ** * xprintf -- Calls a function to dispose of output.
18514 ** * nprintf -- No output, but returns the number of characters
18515 ** that would have been output by printf.
18517 ** * A v- version (ex: vsnprintf) of every function is also
18518 ** supplied.
18520 ** + A few extensions to the formatting notation are supported:
18522 ** * The "=" flag (similar to "-") causes the output to be
18523 ** be centered in the appropriately sized field.
18525 ** * The %b field outputs an integer in binary notation.
18527 ** * The %c field now accepts a precision. The character output
18528 ** is repeated by the number of times the precision specifies.
18530 ** * The %' field works like %c, but takes as its character the
18531 ** next character of the format string, instead of the next
18532 ** argument. For example, printf("%.78'-") prints 78 minus
18533 ** signs, the same as printf("%.78c",'-').
18535 ** + When compiled using GCC on a SPARC, this version of printf is
18536 ** faster than the library printf for SUN OS 4.1.
18538 ** + All functions are fully reentrant.
18543 ** Conversion types fall into various categories as defined by the
18544 ** following enumeration.
18546 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
18547 #define etFLOAT 2 /* Floating point. %f */
18548 #define etEXP 3 /* Exponentional notation. %e and %E */
18549 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
18550 #define etSIZE 5 /* Return number of characters processed so far. %n */
18551 #define etSTRING 6 /* Strings. %s */
18552 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
18553 #define etPERCENT 8 /* Percent symbol. %% */
18554 #define etCHARX 9 /* Characters. %c */
18555 /* The rest are extensions, not normally found in printf() */
18556 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
18557 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
18558 NULL pointers replaced by SQL NULL. %Q */
18559 #define etTOKEN 12 /* a pointer to a Token structure */
18560 #define etSRCLIST 13 /* a pointer to a SrcList */
18561 #define etPOINTER 14 /* The %p conversion */
18562 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
18563 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
18565 #define etINVALID 0 /* Any unrecognized conversion type */
18569 ** An "etByte" is an 8-bit unsigned value.
18571 typedef unsigned char etByte;
18574 ** Each builtin conversion character (ex: the 'd' in "%d") is described
18575 ** by an instance of the following structure
18577 typedef struct et_info { /* Information about each format field */
18578 char fmttype; /* The format field code letter */
18579 etByte base; /* The base for radix conversion */
18580 etByte flags; /* One or more of FLAG_ constants below */
18581 etByte type; /* Conversion paradigm */
18582 etByte charset; /* Offset into aDigits[] of the digits string */
18583 etByte prefix; /* Offset into aPrefix[] of the prefix string */
18584 } et_info;
18587 ** Allowed values for et_info.flags
18589 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
18590 #define FLAG_INTERN 2 /* True if for internal use only */
18591 #define FLAG_STRING 4 /* Allow infinity precision */
18595 ** The following table is searched linearly, so it is good to put the
18596 ** most frequently used conversion types first.
18598 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
18599 static const char aPrefix[] = "-x0\000X0";
18600 static const et_info fmtinfo[] = {
18601 { 'd', 10, 1, etRADIX, 0, 0 },
18602 { 's', 0, 4, etSTRING, 0, 0 },
18603 { 'g', 0, 1, etGENERIC, 30, 0 },
18604 { 'z', 0, 4, etDYNSTRING, 0, 0 },
18605 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
18606 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
18607 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
18608 { 'c', 0, 0, etCHARX, 0, 0 },
18609 { 'o', 8, 0, etRADIX, 0, 2 },
18610 { 'u', 10, 0, etRADIX, 0, 0 },
18611 { 'x', 16, 0, etRADIX, 16, 1 },
18612 { 'X', 16, 0, etRADIX, 0, 4 },
18613 #ifndef SQLITE_OMIT_FLOATING_POINT
18614 { 'f', 0, 1, etFLOAT, 0, 0 },
18615 { 'e', 0, 1, etEXP, 30, 0 },
18616 { 'E', 0, 1, etEXP, 14, 0 },
18617 { 'G', 0, 1, etGENERIC, 14, 0 },
18618 #endif
18619 { 'i', 10, 1, etRADIX, 0, 0 },
18620 { 'n', 0, 0, etSIZE, 0, 0 },
18621 { '%', 0, 0, etPERCENT, 0, 0 },
18622 { 'p', 16, 0, etPOINTER, 0, 1 },
18624 /* All the rest have the FLAG_INTERN bit set and are thus for internal
18625 ** use only */
18626 { 'T', 0, 2, etTOKEN, 0, 0 },
18627 { 'S', 0, 2, etSRCLIST, 0, 0 },
18628 { 'r', 10, 3, etORDINAL, 0, 0 },
18632 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
18633 ** conversions will work.
18635 #ifndef SQLITE_OMIT_FLOATING_POINT
18637 ** "*val" is a double such that 0.1 <= *val < 10.0
18638 ** Return the ascii code for the leading digit of *val, then
18639 ** multiply "*val" by 10.0 to renormalize.
18641 ** Example:
18642 ** input: *val = 3.14159
18643 ** output: *val = 1.4159 function return = '3'
18645 ** The counter *cnt is incremented each time. After counter exceeds
18646 ** 16 (the number of significant digits in a 64-bit float) '0' is
18647 ** always returned.
18649 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
18650 int digit;
18651 LONGDOUBLE_TYPE d;
18652 if( (*cnt)++ >= 16 ) return '0';
18653 digit = (int)*val;
18654 d = digit;
18655 digit += '0';
18656 *val = (*val - d)*10.0;
18657 return (char)digit;
18659 #endif /* SQLITE_OMIT_FLOATING_POINT */
18662 ** Append N space characters to the given string buffer.
18664 static void appendSpace(StrAccum *pAccum, int N){
18665 static const char zSpaces[] = " ";
18666 while( N>=(int)sizeof(zSpaces)-1 ){
18667 sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
18668 N -= sizeof(zSpaces)-1;
18670 if( N>0 ){
18671 sqlite3StrAccumAppend(pAccum, zSpaces, N);
18676 ** On machines with a small stack size, you can redefine the
18677 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
18679 #ifndef SQLITE_PRINT_BUF_SIZE
18680 # if defined(SQLITE_SMALL_STACK)
18681 # define SQLITE_PRINT_BUF_SIZE 50
18682 # else
18683 # define SQLITE_PRINT_BUF_SIZE 350
18684 # endif
18685 #endif
18686 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
18689 ** The root program. All variations call this core.
18691 ** INPUTS:
18692 ** func This is a pointer to a function taking three arguments
18693 ** 1. A pointer to anything. Same as the "arg" parameter.
18694 ** 2. A pointer to the list of characters to be output
18695 ** (Note, this list is NOT null terminated.)
18696 ** 3. An integer number of characters to be output.
18697 ** (Note: This number might be zero.)
18699 ** arg This is the pointer to anything which will be passed as the
18700 ** first argument to "func". Use it for whatever you like.
18702 ** fmt This is the format string, as in the usual print.
18704 ** ap This is a pointer to a list of arguments. Same as in
18705 ** vfprint.
18707 ** OUTPUTS:
18708 ** The return value is the total number of characters sent to
18709 ** the function "func". Returns -1 on a error.
18711 ** Note that the order in which automatic variables are declared below
18712 ** seems to make a big difference in determining how fast this beast
18713 ** will run.
18715 SQLITE_PRIVATE void sqlite3VXPrintf(
18716 StrAccum *pAccum, /* Accumulate results here */
18717 int useExtended, /* Allow extended %-conversions */
18718 const char *fmt, /* Format string */
18719 va_list ap /* arguments */
18721 int c; /* Next character in the format string */
18722 char *bufpt; /* Pointer to the conversion buffer */
18723 int precision; /* Precision of the current field */
18724 int length; /* Length of the field */
18725 int idx; /* A general purpose loop counter */
18726 int width; /* Width of the current field */
18727 etByte flag_leftjustify; /* True if "-" flag is present */
18728 etByte flag_plussign; /* True if "+" flag is present */
18729 etByte flag_blanksign; /* True if " " flag is present */
18730 etByte flag_alternateform; /* True if "#" flag is present */
18731 etByte flag_altform2; /* True if "!" flag is present */
18732 etByte flag_zeropad; /* True if field width constant starts with zero */
18733 etByte flag_long; /* True if "l" flag is present */
18734 etByte flag_longlong; /* True if the "ll" flag is present */
18735 etByte done; /* Loop termination flag */
18736 sqlite_uint64 longvalue; /* Value for integer types */
18737 LONGDOUBLE_TYPE realvalue; /* Value for real types */
18738 const et_info *infop; /* Pointer to the appropriate info structure */
18739 char buf[etBUFSIZE]; /* Conversion buffer */
18740 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
18741 etByte xtype = 0; /* Conversion paradigm */
18742 char *zExtra; /* Extra memory used for etTCLESCAPE conversions */
18743 #ifndef SQLITE_OMIT_FLOATING_POINT
18744 int exp, e2; /* exponent of real numbers */
18745 double rounder; /* Used for rounding floating point values */
18746 etByte flag_dp; /* True if decimal point should be shown */
18747 etByte flag_rtz; /* True if trailing zeros should be removed */
18748 etByte flag_exp; /* True to force display of the exponent */
18749 int nsd; /* Number of significant digits returned */
18750 #endif
18752 length = 0;
18753 bufpt = 0;
18754 for(; (c=(*fmt))!=0; ++fmt){
18755 if( c!='%' ){
18756 int amt;
18757 bufpt = (char *)fmt;
18758 amt = 1;
18759 while( (c=(*++fmt))!='%' && c!=0 ) amt++;
18760 sqlite3StrAccumAppend(pAccum, bufpt, amt);
18761 if( c==0 ) break;
18763 if( (c=(*++fmt))==0 ){
18764 sqlite3StrAccumAppend(pAccum, "%", 1);
18765 break;
18767 /* Find out what flags are present */
18768 flag_leftjustify = flag_plussign = flag_blanksign =
18769 flag_alternateform = flag_altform2 = flag_zeropad = 0;
18770 done = 0;
18772 switch( c ){
18773 case '-': flag_leftjustify = 1; break;
18774 case '+': flag_plussign = 1; break;
18775 case ' ': flag_blanksign = 1; break;
18776 case '#': flag_alternateform = 1; break;
18777 case '!': flag_altform2 = 1; break;
18778 case '0': flag_zeropad = 1; break;
18779 default: done = 1; break;
18781 }while( !done && (c=(*++fmt))!=0 );
18782 /* Get the field width */
18783 width = 0;
18784 if( c=='*' ){
18785 width = va_arg(ap,int);
18786 if( width<0 ){
18787 flag_leftjustify = 1;
18788 width = -width;
18790 c = *++fmt;
18791 }else{
18792 while( c>='0' && c<='9' ){
18793 width = width*10 + c - '0';
18794 c = *++fmt;
18797 if( width > etBUFSIZE-10 ){
18798 width = etBUFSIZE-10;
18800 /* Get the precision */
18801 if( c=='.' ){
18802 precision = 0;
18803 c = *++fmt;
18804 if( c=='*' ){
18805 precision = va_arg(ap,int);
18806 if( precision<0 ) precision = -precision;
18807 c = *++fmt;
18808 }else{
18809 while( c>='0' && c<='9' ){
18810 precision = precision*10 + c - '0';
18811 c = *++fmt;
18814 }else{
18815 precision = -1;
18817 /* Get the conversion type modifier */
18818 if( c=='l' ){
18819 flag_long = 1;
18820 c = *++fmt;
18821 if( c=='l' ){
18822 flag_longlong = 1;
18823 c = *++fmt;
18824 }else{
18825 flag_longlong = 0;
18827 }else{
18828 flag_long = flag_longlong = 0;
18830 /* Fetch the info entry for the field */
18831 infop = &fmtinfo[0];
18832 xtype = etINVALID;
18833 for(idx=0; idx<ArraySize(fmtinfo); idx++){
18834 if( c==fmtinfo[idx].fmttype ){
18835 infop = &fmtinfo[idx];
18836 if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
18837 xtype = infop->type;
18838 }else{
18839 return;
18841 break;
18844 zExtra = 0;
18847 /* Limit the precision to prevent overflowing buf[] during conversion */
18848 if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
18849 precision = etBUFSIZE-40;
18853 ** At this point, variables are initialized as follows:
18855 ** flag_alternateform TRUE if a '#' is present.
18856 ** flag_altform2 TRUE if a '!' is present.
18857 ** flag_plussign TRUE if a '+' is present.
18858 ** flag_leftjustify TRUE if a '-' is present or if the
18859 ** field width was negative.
18860 ** flag_zeropad TRUE if the width began with 0.
18861 ** flag_long TRUE if the letter 'l' (ell) prefixed
18862 ** the conversion character.
18863 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
18864 ** the conversion character.
18865 ** flag_blanksign TRUE if a ' ' is present.
18866 ** width The specified field width. This is
18867 ** always non-negative. Zero is the default.
18868 ** precision The specified precision. The default
18869 ** is -1.
18870 ** xtype The class of the conversion.
18871 ** infop Pointer to the appropriate info struct.
18873 switch( xtype ){
18874 case etPOINTER:
18875 flag_longlong = sizeof(char*)==sizeof(i64);
18876 flag_long = sizeof(char*)==sizeof(long int);
18877 /* Fall through into the next case */
18878 case etORDINAL:
18879 case etRADIX:
18880 if( infop->flags & FLAG_SIGNED ){
18881 i64 v;
18882 if( flag_longlong ){
18883 v = va_arg(ap,i64);
18884 }else if( flag_long ){
18885 v = va_arg(ap,long int);
18886 }else{
18887 v = va_arg(ap,int);
18889 if( v<0 ){
18890 if( v==SMALLEST_INT64 ){
18891 longvalue = ((u64)1)<<63;
18892 }else{
18893 longvalue = -v;
18895 prefix = '-';
18896 }else{
18897 longvalue = v;
18898 if( flag_plussign ) prefix = '+';
18899 else if( flag_blanksign ) prefix = ' ';
18900 else prefix = 0;
18902 }else{
18903 if( flag_longlong ){
18904 longvalue = va_arg(ap,u64);
18905 }else if( flag_long ){
18906 longvalue = va_arg(ap,unsigned long int);
18907 }else{
18908 longvalue = va_arg(ap,unsigned int);
18910 prefix = 0;
18912 if( longvalue==0 ) flag_alternateform = 0;
18913 if( flag_zeropad && precision<width-(prefix!=0) ){
18914 precision = width-(prefix!=0);
18916 bufpt = &buf[etBUFSIZE-1];
18917 if( xtype==etORDINAL ){
18918 static const char zOrd[] = "thstndrd";
18919 int x = (int)(longvalue % 10);
18920 if( x>=4 || (longvalue/10)%10==1 ){
18921 x = 0;
18923 buf[etBUFSIZE-3] = zOrd[x*2];
18924 buf[etBUFSIZE-2] = zOrd[x*2+1];
18925 bufpt -= 2;
18928 register const char *cset; /* Use registers for speed */
18929 register int base;
18930 cset = &aDigits[infop->charset];
18931 base = infop->base;
18932 do{ /* Convert to ascii */
18933 *(--bufpt) = cset[longvalue%base];
18934 longvalue = longvalue/base;
18935 }while( longvalue>0 );
18937 length = (int)(&buf[etBUFSIZE-1]-bufpt);
18938 for(idx=precision-length; idx>0; idx--){
18939 *(--bufpt) = '0'; /* Zero pad */
18941 if( prefix ) *(--bufpt) = prefix; /* Add sign */
18942 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
18943 const char *pre;
18944 char x;
18945 pre = &aPrefix[infop->prefix];
18946 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
18948 length = (int)(&buf[etBUFSIZE-1]-bufpt);
18949 break;
18950 case etFLOAT:
18951 case etEXP:
18952 case etGENERIC:
18953 realvalue = va_arg(ap,double);
18954 #ifdef SQLITE_OMIT_FLOATING_POINT
18955 length = 0;
18956 #else
18957 if( precision<0 ) precision = 6; /* Set default precision */
18958 if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
18959 if( realvalue<0.0 ){
18960 realvalue = -realvalue;
18961 prefix = '-';
18962 }else{
18963 if( flag_plussign ) prefix = '+';
18964 else if( flag_blanksign ) prefix = ' ';
18965 else prefix = 0;
18967 if( xtype==etGENERIC && precision>0 ) precision--;
18968 #if 0
18969 /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
18970 for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
18971 #else
18972 /* It makes more sense to use 0.5 */
18973 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
18974 #endif
18975 if( xtype==etFLOAT ) realvalue += rounder;
18976 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
18977 exp = 0;
18978 if( sqlite3IsNaN((double)realvalue) ){
18979 bufpt = "NaN";
18980 length = 3;
18981 break;
18983 if( realvalue>0.0 ){
18984 while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
18985 while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
18986 while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
18987 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
18988 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
18989 if( exp>350 ){
18990 if( prefix=='-' ){
18991 bufpt = "-Inf";
18992 }else if( prefix=='+' ){
18993 bufpt = "+Inf";
18994 }else{
18995 bufpt = "Inf";
18997 length = sqlite3Strlen30(bufpt);
18998 break;
19001 bufpt = buf;
19003 ** If the field type is etGENERIC, then convert to either etEXP
19004 ** or etFLOAT, as appropriate.
19006 flag_exp = xtype==etEXP;
19007 if( xtype!=etFLOAT ){
19008 realvalue += rounder;
19009 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19011 if( xtype==etGENERIC ){
19012 flag_rtz = !flag_alternateform;
19013 if( exp<-4 || exp>precision ){
19014 xtype = etEXP;
19015 }else{
19016 precision = precision - exp;
19017 xtype = etFLOAT;
19019 }else{
19020 flag_rtz = 0;
19022 if( xtype==etEXP ){
19023 e2 = 0;
19024 }else{
19025 e2 = exp;
19027 nsd = 0;
19028 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19029 /* The sign in front of the number */
19030 if( prefix ){
19031 *(bufpt++) = prefix;
19033 /* Digits prior to the decimal point */
19034 if( e2<0 ){
19035 *(bufpt++) = '0';
19036 }else{
19037 for(; e2>=0; e2--){
19038 *(bufpt++) = et_getdigit(&realvalue,&nsd);
19041 /* The decimal point */
19042 if( flag_dp ){
19043 *(bufpt++) = '.';
19045 /* "0" digits after the decimal point but before the first
19046 ** significant digit of the number */
19047 for(e2++; e2<0; precision--, e2++){
19048 assert( precision>0 );
19049 *(bufpt++) = '0';
19051 /* Significant digits after the decimal point */
19052 while( (precision--)>0 ){
19053 *(bufpt++) = et_getdigit(&realvalue,&nsd);
19055 /* Remove trailing zeros and the "." if no digits follow the "." */
19056 if( flag_rtz && flag_dp ){
19057 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19058 assert( bufpt>buf );
19059 if( bufpt[-1]=='.' ){
19060 if( flag_altform2 ){
19061 *(bufpt++) = '0';
19062 }else{
19063 *(--bufpt) = 0;
19067 /* Add the "eNNN" suffix */
19068 if( flag_exp || xtype==etEXP ){
19069 *(bufpt++) = aDigits[infop->charset];
19070 if( exp<0 ){
19071 *(bufpt++) = '-'; exp = -exp;
19072 }else{
19073 *(bufpt++) = '+';
19075 if( exp>=100 ){
19076 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
19077 exp %= 100;
19079 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
19080 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
19082 *bufpt = 0;
19084 /* The converted number is in buf[] and zero terminated. Output it.
19085 ** Note that the number is in the usual order, not reversed as with
19086 ** integer conversions. */
19087 length = (int)(bufpt-buf);
19088 bufpt = buf;
19090 /* Special case: Add leading zeros if the flag_zeropad flag is
19091 ** set and we are not left justified */
19092 if( flag_zeropad && !flag_leftjustify && length < width){
19093 int i;
19094 int nPad = width - length;
19095 for(i=width; i>=nPad; i--){
19096 bufpt[i] = bufpt[i-nPad];
19098 i = prefix!=0;
19099 while( nPad-- ) bufpt[i++] = '0';
19100 length = width;
19102 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19103 break;
19104 case etSIZE:
19105 *(va_arg(ap,int*)) = pAccum->nChar;
19106 length = width = 0;
19107 break;
19108 case etPERCENT:
19109 buf[0] = '%';
19110 bufpt = buf;
19111 length = 1;
19112 break;
19113 case etCHARX:
19114 c = va_arg(ap,int);
19115 buf[0] = (char)c;
19116 if( precision>=0 ){
19117 for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19118 length = precision;
19119 }else{
19120 length =1;
19122 bufpt = buf;
19123 break;
19124 case etSTRING:
19125 case etDYNSTRING:
19126 bufpt = va_arg(ap,char*);
19127 if( bufpt==0 ){
19128 bufpt = "";
19129 }else if( xtype==etDYNSTRING ){
19130 zExtra = bufpt;
19132 if( precision>=0 ){
19133 for(length=0; length<precision && bufpt[length]; length++){}
19134 }else{
19135 length = sqlite3Strlen30(bufpt);
19137 break;
19138 case etSQLESCAPE:
19139 case etSQLESCAPE2:
19140 case etSQLESCAPE3: {
19141 int i, j, k, n, isnull;
19142 int needQuote;
19143 char ch;
19144 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
19145 char *escarg = va_arg(ap,char*);
19146 isnull = escarg==0;
19147 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19148 k = precision;
19149 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19150 if( ch==q ) n++;
19152 needQuote = !isnull && xtype==etSQLESCAPE2;
19153 n += i + 1 + needQuote*2;
19154 if( n>etBUFSIZE ){
19155 bufpt = zExtra = sqlite3Malloc( n );
19156 if( bufpt==0 ){
19157 pAccum->mallocFailed = 1;
19158 return;
19160 }else{
19161 bufpt = buf;
19163 j = 0;
19164 if( needQuote ) bufpt[j++] = q;
19165 k = i;
19166 for(i=0; i<k; i++){
19167 bufpt[j++] = ch = escarg[i];
19168 if( ch==q ) bufpt[j++] = ch;
19170 if( needQuote ) bufpt[j++] = q;
19171 bufpt[j] = 0;
19172 length = j;
19173 /* The precision in %q and %Q means how many input characters to
19174 ** consume, not the length of the output...
19175 ** if( precision>=0 && precision<length ) length = precision; */
19176 break;
19178 case etTOKEN: {
19179 Token *pToken = va_arg(ap, Token*);
19180 if( pToken ){
19181 sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
19183 length = width = 0;
19184 break;
19186 case etSRCLIST: {
19187 SrcList *pSrc = va_arg(ap, SrcList*);
19188 int k = va_arg(ap, int);
19189 struct SrcList_item *pItem = &pSrc->a[k];
19190 assert( k>=0 && k<pSrc->nSrc );
19191 if( pItem->zDatabase ){
19192 sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
19193 sqlite3StrAccumAppend(pAccum, ".", 1);
19195 sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
19196 length = width = 0;
19197 break;
19199 default: {
19200 assert( xtype==etINVALID );
19201 return;
19203 }/* End switch over the format type */
19205 ** The text of the conversion is pointed to by "bufpt" and is
19206 ** "length" characters long. The field width is "width". Do
19207 ** the output.
19209 if( !flag_leftjustify ){
19210 register int nspace;
19211 nspace = width-length;
19212 if( nspace>0 ){
19213 appendSpace(pAccum, nspace);
19216 if( length>0 ){
19217 sqlite3StrAccumAppend(pAccum, bufpt, length);
19219 if( flag_leftjustify ){
19220 register int nspace;
19221 nspace = width-length;
19222 if( nspace>0 ){
19223 appendSpace(pAccum, nspace);
19226 if( zExtra ){
19227 sqlite3_free(zExtra);
19229 }/* End for loop over the format string */
19230 } /* End of function */
19233 ** Append N bytes of text from z to the StrAccum object.
19235 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
19236 assert( z!=0 || N==0 );
19237 if( p->tooBig | p->mallocFailed ){
19238 testcase(p->tooBig);
19239 testcase(p->mallocFailed);
19240 return;
19242 if( N<0 ){
19243 N = sqlite3Strlen30(z);
19245 if( N==0 || NEVER(z==0) ){
19246 return;
19248 if( p->nChar+N >= p->nAlloc ){
19249 char *zNew;
19250 if( !p->useMalloc ){
19251 p->tooBig = 1;
19252 N = p->nAlloc - p->nChar - 1;
19253 if( N<=0 ){
19254 return;
19256 }else{
19257 char *zOld = (p->zText==p->zBase ? 0 : p->zText);
19258 i64 szNew = p->nChar;
19259 szNew += N + 1;
19260 if( szNew > p->mxAlloc ){
19261 sqlite3StrAccumReset(p);
19262 p->tooBig = 1;
19263 return;
19264 }else{
19265 p->nAlloc = (int)szNew;
19267 if( p->useMalloc==1 ){
19268 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
19269 }else{
19270 zNew = sqlite3_realloc(zOld, p->nAlloc);
19272 if( zNew ){
19273 if( zOld==0 ) memcpy(zNew, p->zText, p->nChar);
19274 p->zText = zNew;
19275 }else{
19276 p->mallocFailed = 1;
19277 sqlite3StrAccumReset(p);
19278 return;
19282 memcpy(&p->zText[p->nChar], z, N);
19283 p->nChar += N;
19287 ** Finish off a string by making sure it is zero-terminated.
19288 ** Return a pointer to the resulting string. Return a NULL
19289 ** pointer if any kind of error was encountered.
19291 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
19292 if( p->zText ){
19293 p->zText[p->nChar] = 0;
19294 if( p->useMalloc && p->zText==p->zBase ){
19295 if( p->useMalloc==1 ){
19296 p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
19297 }else{
19298 p->zText = sqlite3_malloc(p->nChar+1);
19300 if( p->zText ){
19301 memcpy(p->zText, p->zBase, p->nChar+1);
19302 }else{
19303 p->mallocFailed = 1;
19307 return p->zText;
19311 ** Reset an StrAccum string. Reclaim all malloced memory.
19313 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
19314 if( p->zText!=p->zBase ){
19315 if( p->useMalloc==1 ){
19316 sqlite3DbFree(p->db, p->zText);
19317 }else{
19318 sqlite3_free(p->zText);
19321 p->zText = 0;
19325 ** Initialize a string accumulator
19327 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
19328 p->zText = p->zBase = zBase;
19329 p->db = 0;
19330 p->nChar = 0;
19331 p->nAlloc = n;
19332 p->mxAlloc = mx;
19333 p->useMalloc = 1;
19334 p->tooBig = 0;
19335 p->mallocFailed = 0;
19339 ** Print into memory obtained from sqliteMalloc(). Use the internal
19340 ** %-conversion extensions.
19342 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
19343 char *z;
19344 char zBase[SQLITE_PRINT_BUF_SIZE];
19345 StrAccum acc;
19346 assert( db!=0 );
19347 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
19348 db->aLimit[SQLITE_LIMIT_LENGTH]);
19349 acc.db = db;
19350 sqlite3VXPrintf(&acc, 1, zFormat, ap);
19351 z = sqlite3StrAccumFinish(&acc);
19352 if( acc.mallocFailed ){
19353 db->mallocFailed = 1;
19355 return z;
19359 ** Print into memory obtained from sqliteMalloc(). Use the internal
19360 ** %-conversion extensions.
19362 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
19363 va_list ap;
19364 char *z;
19365 va_start(ap, zFormat);
19366 z = sqlite3VMPrintf(db, zFormat, ap);
19367 va_end(ap);
19368 return z;
19372 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
19373 ** the string and before returnning. This routine is intended to be used
19374 ** to modify an existing string. For example:
19376 ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
19379 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
19380 va_list ap;
19381 char *z;
19382 va_start(ap, zFormat);
19383 z = sqlite3VMPrintf(db, zFormat, ap);
19384 va_end(ap);
19385 sqlite3DbFree(db, zStr);
19386 return z;
19390 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
19391 ** %-conversion extensions.
19393 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
19394 char *z;
19395 char zBase[SQLITE_PRINT_BUF_SIZE];
19396 StrAccum acc;
19397 #ifndef SQLITE_OMIT_AUTOINIT
19398 if( sqlite3_initialize() ) return 0;
19399 #endif
19400 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
19401 acc.useMalloc = 2;
19402 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19403 z = sqlite3StrAccumFinish(&acc);
19404 return z;
19408 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
19409 ** %-conversion extensions.
19411 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
19412 va_list ap;
19413 char *z;
19414 #ifndef SQLITE_OMIT_AUTOINIT
19415 if( sqlite3_initialize() ) return 0;
19416 #endif
19417 va_start(ap, zFormat);
19418 z = sqlite3_vmprintf(zFormat, ap);
19419 va_end(ap);
19420 return z;
19424 ** sqlite3_snprintf() works like snprintf() except that it ignores the
19425 ** current locale settings. This is important for SQLite because we
19426 ** are not able to use a "," as the decimal point in place of "." as
19427 ** specified by some locales.
19429 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
19430 ** from the snprintf() standard. Unfortunately, it is too late to change
19431 ** this without breaking compatibility, so we just have to live with the
19432 ** mistake.
19434 ** sqlite3_vsnprintf() is the varargs version.
19436 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
19437 StrAccum acc;
19438 if( n<=0 ) return zBuf;
19439 sqlite3StrAccumInit(&acc, zBuf, n, 0);
19440 acc.useMalloc = 0;
19441 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19442 return sqlite3StrAccumFinish(&acc);
19444 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
19445 char *z;
19446 va_list ap;
19447 va_start(ap,zFormat);
19448 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
19449 va_end(ap);
19450 return z;
19454 ** This is the routine that actually formats the sqlite3_log() message.
19455 ** We house it in a separate routine from sqlite3_log() to avoid using
19456 ** stack space on small-stack systems when logging is disabled.
19458 ** sqlite3_log() must render into a static buffer. It cannot dynamically
19459 ** allocate memory because it might be called while the memory allocator
19460 ** mutex is held.
19462 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
19463 StrAccum acc; /* String accumulator */
19464 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
19466 sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
19467 acc.useMalloc = 0;
19468 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19469 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
19470 sqlite3StrAccumFinish(&acc));
19474 ** Format and write a message to the log if logging is enabled.
19476 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
19477 va_list ap; /* Vararg list */
19478 if( sqlite3GlobalConfig.xLog ){
19479 va_start(ap, zFormat);
19480 renderLogMsg(iErrCode, zFormat, ap);
19481 va_end(ap);
19485 #if defined(SQLITE_DEBUG)
19487 ** A version of printf() that understands %lld. Used for debugging.
19488 ** The printf() built into some versions of windows does not understand %lld
19489 ** and segfaults if you give it a long long int.
19491 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
19492 va_list ap;
19493 StrAccum acc;
19494 char zBuf[500];
19495 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
19496 acc.useMalloc = 0;
19497 va_start(ap,zFormat);
19498 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19499 va_end(ap);
19500 sqlite3StrAccumFinish(&acc);
19501 fprintf(stdout,"%s", zBuf);
19502 fflush(stdout);
19504 #endif
19506 #ifndef SQLITE_OMIT_TRACE
19508 ** variable-argument wrapper around sqlite3VXPrintf().
19510 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
19511 va_list ap;
19512 va_start(ap,zFormat);
19513 sqlite3VXPrintf(p, 1, zFormat, ap);
19514 va_end(ap);
19516 #endif
19518 /************** End of printf.c **********************************************/
19519 /************** Begin file random.c ******************************************/
19521 ** 2001 September 15
19523 ** The author disclaims copyright to this source code. In place of
19524 ** a legal notice, here is a blessing:
19526 ** May you do good and not evil.
19527 ** May you find forgiveness for yourself and forgive others.
19528 ** May you share freely, never taking more than you give.
19530 *************************************************************************
19531 ** This file contains code to implement a pseudo-random number
19532 ** generator (PRNG) for SQLite.
19534 ** Random numbers are used by some of the database backends in order
19535 ** to generate random integer keys for tables or random filenames.
19539 /* All threads share a single random number generator.
19540 ** This structure is the current state of the generator.
19542 static SQLITE_WSD struct sqlite3PrngType {
19543 unsigned char isInit; /* True if initialized */
19544 unsigned char i, j; /* State variables */
19545 unsigned char s[256]; /* State variables */
19546 } sqlite3Prng;
19549 ** Get a single 8-bit random value from the RC4 PRNG. The Mutex
19550 ** must be held while executing this routine.
19552 ** Why not just use a library random generator like lrand48() for this?
19553 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
19554 ** good source of random numbers. The lrand48() library function may
19555 ** well be good enough. But maybe not. Or maybe lrand48() has some
19556 ** subtle problems on some systems that could cause problems. It is hard
19557 ** to know. To minimize the risk of problems due to bad lrand48()
19558 ** implementations, SQLite uses this random number generator based
19559 ** on RC4, which we know works very well.
19561 ** (Later): Actually, OP_NewRowid does not depend on a good source of
19562 ** randomness any more. But we will leave this code in all the same.
19564 static u8 randomByte(void){
19565 unsigned char t;
19568 /* The "wsdPrng" macro will resolve to the pseudo-random number generator
19569 ** state vector. If writable static data is unsupported on the target,
19570 ** we have to locate the state vector at run-time. In the more common
19571 ** case where writable static data is supported, wsdPrng can refer directly
19572 ** to the "sqlite3Prng" state vector declared above.
19574 #ifdef SQLITE_OMIT_WSD
19575 struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
19576 # define wsdPrng p[0]
19577 #else
19578 # define wsdPrng sqlite3Prng
19579 #endif
19582 /* Initialize the state of the random number generator once,
19583 ** the first time this routine is called. The seed value does
19584 ** not need to contain a lot of randomness since we are not
19585 ** trying to do secure encryption or anything like that...
19587 ** Nothing in this file or anywhere else in SQLite does any kind of
19588 ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
19589 ** number generator) not as an encryption device.
19591 if( !wsdPrng.isInit ){
19592 int i;
19593 char k[256];
19594 wsdPrng.j = 0;
19595 wsdPrng.i = 0;
19596 sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
19597 for(i=0; i<256; i++){
19598 wsdPrng.s[i] = (u8)i;
19600 for(i=0; i<256; i++){
19601 wsdPrng.j += wsdPrng.s[i] + k[i];
19602 t = wsdPrng.s[wsdPrng.j];
19603 wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
19604 wsdPrng.s[i] = t;
19606 wsdPrng.isInit = 1;
19609 /* Generate and return single random byte
19611 wsdPrng.i++;
19612 t = wsdPrng.s[wsdPrng.i];
19613 wsdPrng.j += t;
19614 wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
19615 wsdPrng.s[wsdPrng.j] = t;
19616 t += wsdPrng.s[wsdPrng.i];
19617 return wsdPrng.s[t];
19621 ** Return N random bytes.
19623 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
19624 unsigned char *zBuf = pBuf;
19625 #if SQLITE_THREADSAFE
19626 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
19627 #endif
19628 sqlite3_mutex_enter(mutex);
19629 while( N-- ){
19630 *(zBuf++) = randomByte();
19632 sqlite3_mutex_leave(mutex);
19635 #ifndef SQLITE_OMIT_BUILTIN_TEST
19637 ** For testing purposes, we sometimes want to preserve the state of
19638 ** PRNG and restore the PRNG to its saved state at a later time, or
19639 ** to reset the PRNG to its initial state. These routines accomplish
19640 ** those tasks.
19642 ** The sqlite3_test_control() interface calls these routines to
19643 ** control the PRNG.
19645 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
19646 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
19647 memcpy(
19648 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19649 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19650 sizeof(sqlite3Prng)
19653 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
19654 memcpy(
19655 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19656 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19657 sizeof(sqlite3Prng)
19660 SQLITE_PRIVATE void sqlite3PrngResetState(void){
19661 GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
19663 #endif /* SQLITE_OMIT_BUILTIN_TEST */
19665 /************** End of random.c **********************************************/
19666 /************** Begin file utf.c *********************************************/
19668 ** 2004 April 13
19670 ** The author disclaims copyright to this source code. In place of
19671 ** a legal notice, here is a blessing:
19673 ** May you do good and not evil.
19674 ** May you find forgiveness for yourself and forgive others.
19675 ** May you share freely, never taking more than you give.
19677 *************************************************************************
19678 ** This file contains routines used to translate between UTF-8,
19679 ** UTF-16, UTF-16BE, and UTF-16LE.
19681 ** Notes on UTF-8:
19683 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
19684 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
19685 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
19686 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
19687 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
19690 ** Notes on UTF-16: (with wwww+1==uuuuu)
19692 ** Word-0 Word-1 Value
19693 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
19694 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
19697 ** BOM or Byte Order Mark:
19698 ** 0xff 0xfe little-endian utf-16 follows
19699 ** 0xfe 0xff big-endian utf-16 follows
19703 #ifndef SQLITE_AMALGAMATION
19705 ** The following constant value is used by the SQLITE_BIGENDIAN and
19706 ** SQLITE_LITTLEENDIAN macros.
19708 SQLITE_PRIVATE const int sqlite3one = 1;
19709 #endif /* SQLITE_AMALGAMATION */
19712 ** This lookup table is used to help decode the first byte of
19713 ** a multi-byte UTF8 character.
19715 static const unsigned char sqlite3Utf8Trans1[] = {
19716 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19717 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19718 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
19719 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
19720 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19721 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19722 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19723 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
19727 #define WRITE_UTF8(zOut, c) { \
19728 if( c<0x00080 ){ \
19729 *zOut++ = (u8)(c&0xFF); \
19731 else if( c<0x00800 ){ \
19732 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
19733 *zOut++ = 0x80 + (u8)(c & 0x3F); \
19735 else if( c<0x10000 ){ \
19736 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
19737 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
19738 *zOut++ = 0x80 + (u8)(c & 0x3F); \
19739 }else{ \
19740 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
19741 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
19742 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
19743 *zOut++ = 0x80 + (u8)(c & 0x3F); \
19747 #define WRITE_UTF16LE(zOut, c) { \
19748 if( c<=0xFFFF ){ \
19749 *zOut++ = (u8)(c&0x00FF); \
19750 *zOut++ = (u8)((c>>8)&0x00FF); \
19751 }else{ \
19752 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
19753 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
19754 *zOut++ = (u8)(c&0x00FF); \
19755 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
19759 #define WRITE_UTF16BE(zOut, c) { \
19760 if( c<=0xFFFF ){ \
19761 *zOut++ = (u8)((c>>8)&0x00FF); \
19762 *zOut++ = (u8)(c&0x00FF); \
19763 }else{ \
19764 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
19765 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
19766 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
19767 *zOut++ = (u8)(c&0x00FF); \
19771 #define READ_UTF16LE(zIn, TERM, c){ \
19772 c = (*zIn++); \
19773 c += ((*zIn++)<<8); \
19774 if( c>=0xD800 && c<0xE000 && TERM ){ \
19775 int c2 = (*zIn++); \
19776 c2 += ((*zIn++)<<8); \
19777 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
19781 #define READ_UTF16BE(zIn, TERM, c){ \
19782 c = ((*zIn++)<<8); \
19783 c += (*zIn++); \
19784 if( c>=0xD800 && c<0xE000 && TERM ){ \
19785 int c2 = ((*zIn++)<<8); \
19786 c2 += (*zIn++); \
19787 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
19792 ** Translate a single UTF-8 character. Return the unicode value.
19794 ** During translation, assume that the byte that zTerm points
19795 ** is a 0x00.
19797 ** Write a pointer to the next unread byte back into *pzNext.
19799 ** Notes On Invalid UTF-8:
19801 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
19802 ** be encoded as a multi-byte character. Any multi-byte character that
19803 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
19805 ** * This routine never allows a UTF16 surrogate value to be encoded.
19806 ** If a multi-byte character attempts to encode a value between
19807 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
19809 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
19810 ** byte of a character are interpreted as single-byte characters
19811 ** and rendered as themselves even though they are technically
19812 ** invalid characters.
19814 ** * This routine accepts an infinite number of different UTF8 encodings
19815 ** for unicode values 0x80 and greater. It do not change over-length
19816 ** encodings to 0xfffd as some systems recommend.
19818 #define READ_UTF8(zIn, zTerm, c) \
19819 c = *(zIn++); \
19820 if( c>=0xc0 ){ \
19821 c = sqlite3Utf8Trans1[c-0xc0]; \
19822 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
19823 c = (c<<6) + (0x3f & *(zIn++)); \
19825 if( c<0x80 \
19826 || (c&0xFFFFF800)==0xD800 \
19827 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
19829 SQLITE_PRIVATE int sqlite3Utf8Read(
19830 const unsigned char *zIn, /* First byte of UTF-8 character */
19831 const unsigned char **pzNext /* Write first byte past UTF-8 char here */
19833 unsigned int c;
19835 /* Same as READ_UTF8() above but without the zTerm parameter.
19836 ** For this routine, we assume the UTF8 string is always zero-terminated.
19838 c = *(zIn++);
19839 if( c>=0xc0 ){
19840 c = sqlite3Utf8Trans1[c-0xc0];
19841 while( (*zIn & 0xc0)==0x80 ){
19842 c = (c<<6) + (0x3f & *(zIn++));
19844 if( c<0x80
19845 || (c&0xFFFFF800)==0xD800
19846 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
19848 *pzNext = zIn;
19849 return c;
19856 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
19857 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
19859 /* #define TRANSLATE_TRACE 1 */
19861 #ifndef SQLITE_OMIT_UTF16
19863 ** This routine transforms the internal text encoding used by pMem to
19864 ** desiredEnc. It is an error if the string is already of the desired
19865 ** encoding, or if *pMem does not contain a string value.
19867 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19868 int len; /* Maximum length of output string in bytes */
19869 unsigned char *zOut; /* Output buffer */
19870 unsigned char *zIn; /* Input iterator */
19871 unsigned char *zTerm; /* End of input */
19872 unsigned char *z; /* Output iterator */
19873 unsigned int c;
19875 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19876 assert( pMem->flags&MEM_Str );
19877 assert( pMem->enc!=desiredEnc );
19878 assert( pMem->enc!=0 );
19879 assert( pMem->n>=0 );
19881 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19883 char zBuf[100];
19884 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19885 fprintf(stderr, "INPUT: %s\n", zBuf);
19887 #endif
19889 /* If the translation is between UTF-16 little and big endian, then
19890 ** all that is required is to swap the byte order. This case is handled
19891 ** differently from the others.
19893 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19894 u8 temp;
19895 int rc;
19896 rc = sqlite3VdbeMemMakeWriteable(pMem);
19897 if( rc!=SQLITE_OK ){
19898 assert( rc==SQLITE_NOMEM );
19899 return SQLITE_NOMEM;
19901 zIn = (u8*)pMem->z;
19902 zTerm = &zIn[pMem->n&~1];
19903 while( zIn<zTerm ){
19904 temp = *zIn;
19905 *zIn = *(zIn+1);
19906 zIn++;
19907 *zIn++ = temp;
19909 pMem->enc = desiredEnc;
19910 goto translate_out;
19913 /* Set len to the maximum number of bytes required in the output buffer. */
19914 if( desiredEnc==SQLITE_UTF8 ){
19915 /* When converting from UTF-16, the maximum growth results from
19916 ** translating a 2-byte character to a 4-byte UTF-8 character.
19917 ** A single byte is required for the output string
19918 ** nul-terminator.
19920 pMem->n &= ~1;
19921 len = pMem->n * 2 + 1;
19922 }else{
19923 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19924 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19925 ** character. Two bytes are required in the output buffer for the
19926 ** nul-terminator.
19928 len = pMem->n * 2 + 2;
19931 /* Set zIn to point at the start of the input buffer and zTerm to point 1
19932 ** byte past the end.
19934 ** Variable zOut is set to point at the output buffer, space obtained
19935 ** from sqlite3_malloc().
19937 zIn = (u8*)pMem->z;
19938 zTerm = &zIn[pMem->n];
19939 zOut = sqlite3DbMallocRaw(pMem->db, len);
19940 if( !zOut ){
19941 return SQLITE_NOMEM;
19943 z = zOut;
19945 if( pMem->enc==SQLITE_UTF8 ){
19946 if( desiredEnc==SQLITE_UTF16LE ){
19947 /* UTF-8 -> UTF-16 Little-endian */
19948 while( zIn<zTerm ){
19949 /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19950 READ_UTF8(zIn, zTerm, c);
19951 WRITE_UTF16LE(z, c);
19953 }else{
19954 assert( desiredEnc==SQLITE_UTF16BE );
19955 /* UTF-8 -> UTF-16 Big-endian */
19956 while( zIn<zTerm ){
19957 /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19958 READ_UTF8(zIn, zTerm, c);
19959 WRITE_UTF16BE(z, c);
19962 pMem->n = (int)(z - zOut);
19963 *z++ = 0;
19964 }else{
19965 assert( desiredEnc==SQLITE_UTF8 );
19966 if( pMem->enc==SQLITE_UTF16LE ){
19967 /* UTF-16 Little-endian -> UTF-8 */
19968 while( zIn<zTerm ){
19969 READ_UTF16LE(zIn, zIn<zTerm, c);
19970 WRITE_UTF8(z, c);
19972 }else{
19973 /* UTF-16 Big-endian -> UTF-8 */
19974 while( zIn<zTerm ){
19975 READ_UTF16BE(zIn, zIn<zTerm, c);
19976 WRITE_UTF8(z, c);
19979 pMem->n = (int)(z - zOut);
19981 *z = 0;
19982 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19984 sqlite3VdbeMemRelease(pMem);
19985 pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19986 pMem->enc = desiredEnc;
19987 pMem->flags |= (MEM_Term|MEM_Dyn);
19988 pMem->z = (char*)zOut;
19989 pMem->zMalloc = pMem->z;
19991 translate_out:
19992 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19994 char zBuf[100];
19995 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19996 fprintf(stderr, "OUTPUT: %s\n", zBuf);
19998 #endif
19999 return SQLITE_OK;
20003 ** This routine checks for a byte-order mark at the beginning of the
20004 ** UTF-16 string stored in *pMem. If one is present, it is removed and
20005 ** the encoding of the Mem adjusted. This routine does not do any
20006 ** byte-swapping, it just sets Mem.enc appropriately.
20008 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
20009 ** changed by this function.
20011 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20012 int rc = SQLITE_OK;
20013 u8 bom = 0;
20015 assert( pMem->n>=0 );
20016 if( pMem->n>1 ){
20017 u8 b1 = *(u8 *)pMem->z;
20018 u8 b2 = *(((u8 *)pMem->z) + 1);
20019 if( b1==0xFE && b2==0xFF ){
20020 bom = SQLITE_UTF16BE;
20022 if( b1==0xFF && b2==0xFE ){
20023 bom = SQLITE_UTF16LE;
20027 if( bom ){
20028 rc = sqlite3VdbeMemMakeWriteable(pMem);
20029 if( rc==SQLITE_OK ){
20030 pMem->n -= 2;
20031 memmove(pMem->z, &pMem->z[2], pMem->n);
20032 pMem->z[pMem->n] = '\0';
20033 pMem->z[pMem->n+1] = '\0';
20034 pMem->flags |= MEM_Term;
20035 pMem->enc = bom;
20038 return rc;
20040 #endif /* SQLITE_OMIT_UTF16 */
20043 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20044 ** return the number of unicode characters in pZ up to (but not including)
20045 ** the first 0x00 byte. If nByte is not less than zero, return the
20046 ** number of unicode characters in the first nByte of pZ (or up to
20047 ** the first 0x00, whichever comes first).
20049 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20050 int r = 0;
20051 const u8 *z = (const u8*)zIn;
20052 const u8 *zTerm;
20053 if( nByte>=0 ){
20054 zTerm = &z[nByte];
20055 }else{
20056 zTerm = (const u8*)(-1);
20058 assert( z<=zTerm );
20059 while( *z!=0 && z<zTerm ){
20060 SQLITE_SKIP_UTF8(z);
20061 r++;
20063 return r;
20066 /* This test function is not currently used by the automated test-suite.
20067 ** Hence it is only available in debug builds.
20069 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20071 ** Translate UTF-8 to UTF-8.
20073 ** This has the effect of making sure that the string is well-formed
20074 ** UTF-8. Miscoded characters are removed.
20076 ** The translation is done in-place and aborted if the output
20077 ** overruns the input.
20079 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20080 unsigned char *zOut = zIn;
20081 unsigned char *zStart = zIn;
20082 u32 c;
20084 while( zIn[0] && zOut<=zIn ){
20085 c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
20086 if( c!=0xfffd ){
20087 WRITE_UTF8(zOut, c);
20090 *zOut = 0;
20091 return (int)(zOut - zStart);
20093 #endif
20095 #ifndef SQLITE_OMIT_UTF16
20097 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20098 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20099 ** be freed by the calling function.
20101 ** NULL is returned if there is an allocation error.
20103 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20104 Mem m;
20105 memset(&m, 0, sizeof(m));
20106 m.db = db;
20107 sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20108 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20109 if( db->mallocFailed ){
20110 sqlite3VdbeMemRelease(&m);
20111 m.z = 0;
20113 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20114 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20115 assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20116 assert( m.z || db->mallocFailed );
20117 return m.z;
20121 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20122 ** enc. A pointer to the new string is returned, and the value of *pnOut
20123 ** is set to the length of the returned string in bytes. The call should
20124 ** arrange to call sqlite3DbFree() on the returned pointer when it is
20125 ** no longer required.
20127 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20128 ** flag set.
20130 #ifdef SQLITE_ENABLE_STAT2
20131 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20132 Mem m;
20133 memset(&m, 0, sizeof(m));
20134 m.db = db;
20135 sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20136 if( sqlite3VdbeMemTranslate(&m, enc) ){
20137 assert( db->mallocFailed );
20138 return 0;
20140 assert( m.z==m.zMalloc );
20141 *pnOut = m.n;
20142 return m.z;
20144 #endif
20147 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20148 ** Return the number of bytes in the first nChar unicode characters
20149 ** in pZ. nChar must be non-negative.
20151 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20152 int c;
20153 unsigned char const *z = zIn;
20154 int n = 0;
20156 if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20157 while( n<nChar ){
20158 READ_UTF16BE(z, 1, c);
20159 n++;
20161 }else{
20162 while( n<nChar ){
20163 READ_UTF16LE(z, 1, c);
20164 n++;
20167 return (int)(z-(unsigned char const *)zIn);
20170 #if defined(SQLITE_TEST)
20172 ** This routine is called from the TCL test function "translate_selftest".
20173 ** It checks that the primitives for serializing and deserializing
20174 ** characters in each encoding are inverses of each other.
20176 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20177 unsigned int i, t;
20178 unsigned char zBuf[20];
20179 unsigned char *z;
20180 int n;
20181 unsigned int c;
20183 for(i=0; i<0x00110000; i++){
20184 z = zBuf;
20185 WRITE_UTF8(z, i);
20186 n = (int)(z-zBuf);
20187 assert( n>0 && n<=4 );
20188 z[0] = 0;
20189 z = zBuf;
20190 c = sqlite3Utf8Read(z, (const u8**)&z);
20191 t = i;
20192 if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
20193 if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
20194 assert( c==t );
20195 assert( (z-zBuf)==n );
20197 for(i=0; i<0x00110000; i++){
20198 if( i>=0xD800 && i<0xE000 ) continue;
20199 z = zBuf;
20200 WRITE_UTF16LE(z, i);
20201 n = (int)(z-zBuf);
20202 assert( n>0 && n<=4 );
20203 z[0] = 0;
20204 z = zBuf;
20205 READ_UTF16LE(z, 1, c);
20206 assert( c==i );
20207 assert( (z-zBuf)==n );
20209 for(i=0; i<0x00110000; i++){
20210 if( i>=0xD800 && i<0xE000 ) continue;
20211 z = zBuf;
20212 WRITE_UTF16BE(z, i);
20213 n = (int)(z-zBuf);
20214 assert( n>0 && n<=4 );
20215 z[0] = 0;
20216 z = zBuf;
20217 READ_UTF16BE(z, 1, c);
20218 assert( c==i );
20219 assert( (z-zBuf)==n );
20222 #endif /* SQLITE_TEST */
20223 #endif /* SQLITE_OMIT_UTF16 */
20225 /************** End of utf.c *************************************************/
20226 /************** Begin file util.c ********************************************/
20228 ** 2001 September 15
20230 ** The author disclaims copyright to this source code. In place of
20231 ** a legal notice, here is a blessing:
20233 ** May you do good and not evil.
20234 ** May you find forgiveness for yourself and forgive others.
20235 ** May you share freely, never taking more than you give.
20237 *************************************************************************
20238 ** Utility functions used throughout sqlite.
20240 ** This file contains functions for allocating memory, comparing
20241 ** strings, and stuff like that.
20244 #ifdef SQLITE_HAVE_ISNAN
20245 # include <math.h>
20246 #endif
20249 ** Routine needed to support the testcase() macro.
20251 #ifdef SQLITE_COVERAGE_TEST
20252 SQLITE_PRIVATE void sqlite3Coverage(int x){
20253 static unsigned dummy = 0;
20254 dummy += (unsigned)x;
20256 #endif
20258 #ifndef SQLITE_OMIT_FLOATING_POINT
20260 ** Return true if the floating point value is Not a Number (NaN).
20262 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
20263 ** Otherwise, we have our own implementation that works on most systems.
20265 SQLITE_PRIVATE int sqlite3IsNaN(double x){
20266 int rc; /* The value return */
20267 #if !defined(SQLITE_HAVE_ISNAN)
20269 ** Systems that support the isnan() library function should probably
20270 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
20271 ** found that many systems do not have a working isnan() function so
20272 ** this implementation is provided as an alternative.
20274 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
20275 ** On the other hand, the use of -ffast-math comes with the following
20276 ** warning:
20278 ** This option [-ffast-math] should never be turned on by any
20279 ** -O option since it can result in incorrect output for programs
20280 ** which depend on an exact implementation of IEEE or ISO
20281 ** rules/specifications for math functions.
20283 ** Under MSVC, this NaN test may fail if compiled with a floating-
20284 ** point precision mode other than /fp:precise. From the MSDN
20285 ** documentation:
20287 ** The compiler [with /fp:precise] will properly handle comparisons
20288 ** involving NaN. For example, x != x evaluates to true if x is NaN
20289 ** ...
20291 #ifdef __FAST_MATH__
20292 # error SQLite will not work correctly with the -ffast-math option of GCC.
20293 #endif
20294 volatile double y = x;
20295 volatile double z = y;
20296 rc = (y!=z);
20297 #else /* if defined(SQLITE_HAVE_ISNAN) */
20298 rc = isnan(x);
20299 #endif /* SQLITE_HAVE_ISNAN */
20300 testcase( rc );
20301 return rc;
20303 #endif /* SQLITE_OMIT_FLOATING_POINT */
20306 ** Compute a string length that is limited to what can be stored in
20307 ** lower 30 bits of a 32-bit signed integer.
20309 ** The value returned will never be negative. Nor will it ever be greater
20310 ** than the actual length of the string. For very long strings (greater
20311 ** than 1GiB) the value returned might be less than the true string length.
20313 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
20314 const char *z2 = z;
20315 if( z==0 ) return 0;
20316 while( *z2 ){ z2++; }
20317 return 0x3fffffff & (int)(z2 - z);
20321 ** Set the most recent error code and error string for the sqlite
20322 ** handle "db". The error code is set to "err_code".
20324 ** If it is not NULL, string zFormat specifies the format of the
20325 ** error string in the style of the printf functions: The following
20326 ** format characters are allowed:
20328 ** %s Insert a string
20329 ** %z A string that should be freed after use
20330 ** %d Insert an integer
20331 ** %T Insert a token
20332 ** %S Insert the first element of a SrcList
20334 ** zFormat and any string tokens that follow it are assumed to be
20335 ** encoded in UTF-8.
20337 ** To clear the most recent error for sqlite handle "db", sqlite3Error
20338 ** should be called with err_code set to SQLITE_OK and zFormat set
20339 ** to NULL.
20341 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
20342 if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
20343 db->errCode = err_code;
20344 if( zFormat ){
20345 char *z;
20346 va_list ap;
20347 va_start(ap, zFormat);
20348 z = sqlite3VMPrintf(db, zFormat, ap);
20349 va_end(ap);
20350 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
20351 }else{
20352 sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
20358 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
20359 ** The following formatting characters are allowed:
20361 ** %s Insert a string
20362 ** %z A string that should be freed after use
20363 ** %d Insert an integer
20364 ** %T Insert a token
20365 ** %S Insert the first element of a SrcList
20367 ** This function should be used to report any error that occurs whilst
20368 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
20369 ** last thing the sqlite3_prepare() function does is copy the error
20370 ** stored by this function into the database handle using sqlite3Error().
20371 ** Function sqlite3Error() should be used during statement execution
20372 ** (sqlite3_step() etc.).
20374 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
20375 char *zMsg;
20376 va_list ap;
20377 sqlite3 *db = pParse->db;
20378 va_start(ap, zFormat);
20379 zMsg = sqlite3VMPrintf(db, zFormat, ap);
20380 va_end(ap);
20381 if( db->suppressErr ){
20382 sqlite3DbFree(db, zMsg);
20383 }else{
20384 pParse->nErr++;
20385 sqlite3DbFree(db, pParse->zErrMsg);
20386 pParse->zErrMsg = zMsg;
20387 pParse->rc = SQLITE_ERROR;
20392 ** Convert an SQL-style quoted string into a normal string by removing
20393 ** the quote characters. The conversion is done in-place. If the
20394 ** input does not begin with a quote character, then this routine
20395 ** is a no-op.
20397 ** The input string must be zero-terminated. A new zero-terminator
20398 ** is added to the dequoted string.
20400 ** The return value is -1 if no dequoting occurs or the length of the
20401 ** dequoted string, exclusive of the zero terminator, if dequoting does
20402 ** occur.
20404 ** 2002-Feb-14: This routine is extended to remove MS-Access style
20405 ** brackets from around identifers. For example: "[a-b-c]" becomes
20406 ** "a-b-c".
20408 SQLITE_PRIVATE int sqlite3Dequote(char *z){
20409 char quote;
20410 int i, j;
20411 if( z==0 ) return -1;
20412 quote = z[0];
20413 switch( quote ){
20414 case '\'': break;
20415 case '"': break;
20416 case '`': break; /* For MySQL compatibility */
20417 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
20418 default: return -1;
20420 for(i=1, j=0; ALWAYS(z[i]); i++){
20421 if( z[i]==quote ){
20422 if( z[i+1]==quote ){
20423 z[j++] = quote;
20424 i++;
20425 }else{
20426 break;
20428 }else{
20429 z[j++] = z[i];
20432 z[j] = 0;
20433 return j;
20436 /* Convenient short-hand */
20437 #define UpperToLower sqlite3UpperToLower
20440 ** Some systems have stricmp(). Others have strcasecmp(). Because
20441 ** there is no consistency, we will define our own.
20443 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20444 ** applications and extensions to compare the contents of two buffers
20445 ** containing UTF-8 strings in a case-independent fashion, using the same
20446 ** definition of case independence that SQLite uses internally when
20447 ** comparing identifiers.
20449 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20450 register unsigned char *a, *b;
20451 a = (unsigned char *)zLeft;
20452 b = (unsigned char *)zRight;
20453 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20454 return UpperToLower[*a] - UpperToLower[*b];
20456 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
20457 register unsigned char *a, *b;
20458 a = (unsigned char *)zLeft;
20459 b = (unsigned char *)zRight;
20460 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20461 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
20465 ** The string z[] is an text representation of a real number.
20466 ** Convert this string to a double and write it into *pResult.
20468 ** The string z[] is length bytes in length (bytes, not characters) and
20469 ** uses the encoding enc. The string is not necessarily zero-terminated.
20471 ** Return TRUE if the result is a valid real number (or integer) and FALSE
20472 ** if the string is empty or contains extraneous text. Valid numbers
20473 ** are in one of these formats:
20475 ** [+-]digits[E[+-]digits]
20476 ** [+-]digits.[digits][E[+-]digits]
20477 ** [+-].digits[E[+-]digits]
20479 ** Leading and trailing whitespace is ignored for the purpose of determining
20480 ** validity.
20482 ** If some prefix of the input string is a valid number, this routine
20483 ** returns FALSE but it still converts the prefix and writes the result
20484 ** into *pResult.
20486 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
20487 #ifndef SQLITE_OMIT_FLOATING_POINT
20488 int incr = (enc==SQLITE_UTF8?1:2);
20489 const char *zEnd = z + length;
20490 /* sign * significand * (10 ^ (esign * exponent)) */
20491 int sign = 1; /* sign of significand */
20492 i64 s = 0; /* significand */
20493 int d = 0; /* adjust exponent for shifting decimal point */
20494 int esign = 1; /* sign of exponent */
20495 int e = 0; /* exponent */
20496 int eValid = 1; /* True exponent is either not used or is well-formed */
20497 double result;
20498 int nDigits = 0;
20500 *pResult = 0.0; /* Default return value, in case of an error */
20502 if( enc==SQLITE_UTF16BE ) z++;
20504 /* skip leading spaces */
20505 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20506 if( z>=zEnd ) return 0;
20508 /* get sign of significand */
20509 if( *z=='-' ){
20510 sign = -1;
20511 z+=incr;
20512 }else if( *z=='+' ){
20513 z+=incr;
20516 /* skip leading zeroes */
20517 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
20519 /* copy max significant digits to significand */
20520 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20521 s = s*10 + (*z - '0');
20522 z+=incr, nDigits++;
20525 /* skip non-significant significand digits
20526 ** (increase exponent by d to shift decimal left) */
20527 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
20528 if( z>=zEnd ) goto do_atof_calc;
20530 /* if decimal point is present */
20531 if( *z=='.' ){
20532 z+=incr;
20533 /* copy digits from after decimal to significand
20534 ** (decrease exponent by d to shift decimal right) */
20535 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20536 s = s*10 + (*z - '0');
20537 z+=incr, nDigits++, d--;
20539 /* skip non-significant digits */
20540 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
20542 if( z>=zEnd ) goto do_atof_calc;
20544 /* if exponent is present */
20545 if( *z=='e' || *z=='E' ){
20546 z+=incr;
20547 eValid = 0;
20548 if( z>=zEnd ) goto do_atof_calc;
20549 /* get sign of exponent */
20550 if( *z=='-' ){
20551 esign = -1;
20552 z+=incr;
20553 }else if( *z=='+' ){
20554 z+=incr;
20556 /* copy digits to exponent */
20557 while( z<zEnd && sqlite3Isdigit(*z) ){
20558 e = e*10 + (*z - '0');
20559 z+=incr;
20560 eValid = 1;
20564 /* skip trailing spaces */
20565 if( nDigits && eValid ){
20566 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20569 do_atof_calc:
20570 /* adjust exponent by d, and update sign */
20571 e = (e*esign) + d;
20572 if( e<0 ) {
20573 esign = -1;
20574 e *= -1;
20575 } else {
20576 esign = 1;
20579 /* if 0 significand */
20580 if( !s ) {
20581 /* In the IEEE 754 standard, zero is signed.
20582 ** Add the sign if we've seen at least one digit */
20583 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
20584 } else {
20585 /* attempt to reduce exponent */
20586 if( esign>0 ){
20587 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
20588 }else{
20589 while( !(s%10) && e>0 ) e--,s/=10;
20592 /* adjust the sign of significand */
20593 s = sign<0 ? -s : s;
20595 /* if exponent, scale significand as appropriate
20596 ** and store in result. */
20597 if( e ){
20598 double scale = 1.0;
20599 /* attempt to handle extremely small/large numbers better */
20600 if( e>307 && e<342 ){
20601 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
20602 if( esign<0 ){
20603 result = s / scale;
20604 result /= 1.0e+308;
20605 }else{
20606 result = s * scale;
20607 result *= 1.0e+308;
20609 }else{
20610 /* 1.0e+22 is the largest power of 10 than can be
20611 ** represented exactly. */
20612 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
20613 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
20614 if( esign<0 ){
20615 result = s / scale;
20616 }else{
20617 result = s * scale;
20620 } else {
20621 result = (double)s;
20625 /* store the result */
20626 *pResult = result;
20628 /* return true if number and no extra non-whitespace chracters after */
20629 return z>=zEnd && nDigits>0 && eValid;
20630 #else
20631 return !sqlite3Atoi64(z, pResult, length, enc);
20632 #endif /* SQLITE_OMIT_FLOATING_POINT */
20636 ** Compare the 19-character string zNum against the text representation
20637 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
20638 ** if zNum is less than, equal to, or greater than the string.
20639 ** Note that zNum must contain exactly 19 characters.
20641 ** Unlike memcmp() this routine is guaranteed to return the difference
20642 ** in the values of the last digit if the only difference is in the
20643 ** last digit. So, for example,
20645 ** compare2pow63("9223372036854775800", 1)
20647 ** will return -8.
20649 static int compare2pow63(const char *zNum, int incr){
20650 int c = 0;
20651 int i;
20652 /* 012345678901234567 */
20653 const char *pow63 = "922337203685477580";
20654 for(i=0; c==0 && i<18; i++){
20655 c = (zNum[i*incr]-pow63[i])*10;
20657 if( c==0 ){
20658 c = zNum[18*incr] - '8';
20659 testcase( c==(-1) );
20660 testcase( c==0 );
20661 testcase( c==(+1) );
20663 return c;
20668 ** Convert zNum to a 64-bit signed integer.
20670 ** If the zNum value is representable as a 64-bit twos-complement
20671 ** integer, then write that value into *pNum and return 0.
20673 ** If zNum is exactly 9223372036854665808, return 2. This special
20674 ** case is broken out because while 9223372036854665808 cannot be a
20675 ** signed 64-bit integer, its negative -9223372036854665808 can be.
20677 ** If zNum is too big for a 64-bit integer and is not
20678 ** 9223372036854665808 then return 1.
20680 ** length is the number of bytes in the string (bytes, not characters).
20681 ** The string is not necessarily zero-terminated. The encoding is
20682 ** given by enc.
20684 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
20685 int incr = (enc==SQLITE_UTF8?1:2);
20686 u64 u = 0;
20687 int neg = 0; /* assume positive */
20688 int i;
20689 int c = 0;
20690 const char *zStart;
20691 const char *zEnd = zNum + length;
20692 if( enc==SQLITE_UTF16BE ) zNum++;
20693 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
20694 if( zNum<zEnd ){
20695 if( *zNum=='-' ){
20696 neg = 1;
20697 zNum+=incr;
20698 }else if( *zNum=='+' ){
20699 zNum+=incr;
20702 zStart = zNum;
20703 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
20704 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
20705 u = u*10 + c - '0';
20707 if( u>LARGEST_INT64 ){
20708 *pNum = SMALLEST_INT64;
20709 }else if( neg ){
20710 *pNum = -(i64)u;
20711 }else{
20712 *pNum = (i64)u;
20714 testcase( i==18 );
20715 testcase( i==19 );
20716 testcase( i==20 );
20717 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
20718 /* zNum is empty or contains non-numeric text or is longer
20719 ** than 19 digits (thus guaranteeing that it is too large) */
20720 return 1;
20721 }else if( i<19*incr ){
20722 /* Less than 19 digits, so we know that it fits in 64 bits */
20723 assert( u<=LARGEST_INT64 );
20724 return 0;
20725 }else{
20726 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
20727 c = compare2pow63(zNum, incr);
20728 if( c<0 ){
20729 /* zNum is less than 9223372036854775808 so it fits */
20730 assert( u<=LARGEST_INT64 );
20731 return 0;
20732 }else if( c>0 ){
20733 /* zNum is greater than 9223372036854775808 so it overflows */
20734 return 1;
20735 }else{
20736 /* zNum is exactly 9223372036854775808. Fits if negative. The
20737 ** special case 2 overflow if positive */
20738 assert( u-1==LARGEST_INT64 );
20739 assert( (*pNum)==SMALLEST_INT64 );
20740 return neg ? 0 : 2;
20746 ** If zNum represents an integer that will fit in 32-bits, then set
20747 ** *pValue to that integer and return true. Otherwise return false.
20749 ** Any non-numeric characters that following zNum are ignored.
20750 ** This is different from sqlite3Atoi64() which requires the
20751 ** input number to be zero-terminated.
20753 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
20754 sqlite_int64 v = 0;
20755 int i, c;
20756 int neg = 0;
20757 if( zNum[0]=='-' ){
20758 neg = 1;
20759 zNum++;
20760 }else if( zNum[0]=='+' ){
20761 zNum++;
20763 while( zNum[0]=='0' ) zNum++;
20764 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
20765 v = v*10 + c;
20768 /* The longest decimal representation of a 32 bit integer is 10 digits:
20770 ** 1234567890
20771 ** 2^31 -> 2147483648
20773 testcase( i==10 );
20774 if( i>10 ){
20775 return 0;
20777 testcase( v-neg==2147483647 );
20778 if( v-neg>2147483647 ){
20779 return 0;
20781 if( neg ){
20782 v = -v;
20784 *pValue = (int)v;
20785 return 1;
20789 ** Return a 32-bit integer value extracted from a string. If the
20790 ** string is not an integer, just return 0.
20792 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
20793 int x = 0;
20794 if( z ) sqlite3GetInt32(z, &x);
20795 return x;
20799 ** The variable-length integer encoding is as follows:
20801 ** KEY:
20802 ** A = 0xxxxxxx 7 bits of data and one flag bit
20803 ** B = 1xxxxxxx 7 bits of data and one flag bit
20804 ** C = xxxxxxxx 8 bits of data
20806 ** 7 bits - A
20807 ** 14 bits - BA
20808 ** 21 bits - BBA
20809 ** 28 bits - BBBA
20810 ** 35 bits - BBBBA
20811 ** 42 bits - BBBBBA
20812 ** 49 bits - BBBBBBA
20813 ** 56 bits - BBBBBBBA
20814 ** 64 bits - BBBBBBBBC
20818 ** Write a 64-bit variable-length integer to memory starting at p[0].
20819 ** The length of data write will be between 1 and 9 bytes. The number
20820 ** of bytes written is returned.
20822 ** A variable-length integer consists of the lower 7 bits of each byte
20823 ** for all bytes that have the 8th bit set and one byte with the 8th
20824 ** bit clear. Except, if we get to the 9th byte, it stores the full
20825 ** 8 bits and is the last byte.
20827 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
20828 int i, j, n;
20829 u8 buf[10];
20830 if( v & (((u64)0xff000000)<<32) ){
20831 p[8] = (u8)v;
20832 v >>= 8;
20833 for(i=7; i>=0; i--){
20834 p[i] = (u8)((v & 0x7f) | 0x80);
20835 v >>= 7;
20837 return 9;
20839 n = 0;
20841 buf[n++] = (u8)((v & 0x7f) | 0x80);
20842 v >>= 7;
20843 }while( v!=0 );
20844 buf[0] &= 0x7f;
20845 assert( n<=9 );
20846 for(i=0, j=n-1; j>=0; j--, i++){
20847 p[i] = buf[j];
20849 return n;
20853 ** This routine is a faster version of sqlite3PutVarint() that only
20854 ** works for 32-bit positive integers and which is optimized for
20855 ** the common case of small integers. A MACRO version, putVarint32,
20856 ** is provided which inlines the single-byte case. All code should use
20857 ** the MACRO version as this function assumes the single-byte case has
20858 ** already been handled.
20860 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20861 #ifndef putVarint32
20862 if( (v & ~0x7f)==0 ){
20863 p[0] = v;
20864 return 1;
20866 #endif
20867 if( (v & ~0x3fff)==0 ){
20868 p[0] = (u8)((v>>7) | 0x80);
20869 p[1] = (u8)(v & 0x7f);
20870 return 2;
20872 return sqlite3PutVarint(p, v);
20876 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
20877 ** are defined here rather than simply putting the constant expressions
20878 ** inline in order to work around bugs in the RVT compiler.
20880 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
20882 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
20884 #define SLOT_2_0 0x001fc07f
20885 #define SLOT_4_2_0 0xf01fc07f
20889 ** Read a 64-bit variable-length integer from memory starting at p[0].
20890 ** Return the number of bytes read. The value is stored in *v.
20892 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20893 u32 a,b,s;
20895 a = *p;
20896 /* a: p0 (unmasked) */
20897 if (!(a&0x80))
20899 *v = a;
20900 return 1;
20903 p++;
20904 b = *p;
20905 /* b: p1 (unmasked) */
20906 if (!(b&0x80))
20908 a &= 0x7f;
20909 a = a<<7;
20910 a |= b;
20911 *v = a;
20912 return 2;
20915 /* Verify that constants are precomputed correctly */
20916 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20917 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20919 p++;
20920 a = a<<14;
20921 a |= *p;
20922 /* a: p0<<14 | p2 (unmasked) */
20923 if (!(a&0x80))
20925 a &= SLOT_2_0;
20926 b &= 0x7f;
20927 b = b<<7;
20928 a |= b;
20929 *v = a;
20930 return 3;
20933 /* CSE1 from below */
20934 a &= SLOT_2_0;
20935 p++;
20936 b = b<<14;
20937 b |= *p;
20938 /* b: p1<<14 | p3 (unmasked) */
20939 if (!(b&0x80))
20941 b &= SLOT_2_0;
20942 /* moved CSE1 up */
20943 /* a &= (0x7f<<14)|(0x7f); */
20944 a = a<<7;
20945 a |= b;
20946 *v = a;
20947 return 4;
20950 /* a: p0<<14 | p2 (masked) */
20951 /* b: p1<<14 | p3 (unmasked) */
20952 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20953 /* moved CSE1 up */
20954 /* a &= (0x7f<<14)|(0x7f); */
20955 b &= SLOT_2_0;
20956 s = a;
20957 /* s: p0<<14 | p2 (masked) */
20959 p++;
20960 a = a<<14;
20961 a |= *p;
20962 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20963 if (!(a&0x80))
20965 /* we can skip these cause they were (effectively) done above in calc'ing s */
20966 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20967 /* b &= (0x7f<<14)|(0x7f); */
20968 b = b<<7;
20969 a |= b;
20970 s = s>>18;
20971 *v = ((u64)s)<<32 | a;
20972 return 5;
20975 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20976 s = s<<7;
20977 s |= b;
20978 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20980 p++;
20981 b = b<<14;
20982 b |= *p;
20983 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20984 if (!(b&0x80))
20986 /* we can skip this cause it was (effectively) done above in calc'ing s */
20987 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20988 a &= SLOT_2_0;
20989 a = a<<7;
20990 a |= b;
20991 s = s>>18;
20992 *v = ((u64)s)<<32 | a;
20993 return 6;
20996 p++;
20997 a = a<<14;
20998 a |= *p;
20999 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21000 if (!(a&0x80))
21002 a &= SLOT_4_2_0;
21003 b &= SLOT_2_0;
21004 b = b<<7;
21005 a |= b;
21006 s = s>>11;
21007 *v = ((u64)s)<<32 | a;
21008 return 7;
21011 /* CSE2 from below */
21012 a &= SLOT_2_0;
21013 p++;
21014 b = b<<14;
21015 b |= *p;
21016 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21017 if (!(b&0x80))
21019 b &= SLOT_4_2_0;
21020 /* moved CSE2 up */
21021 /* a &= (0x7f<<14)|(0x7f); */
21022 a = a<<7;
21023 a |= b;
21024 s = s>>4;
21025 *v = ((u64)s)<<32 | a;
21026 return 8;
21029 p++;
21030 a = a<<15;
21031 a |= *p;
21032 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21034 /* moved CSE2 up */
21035 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21036 b &= SLOT_2_0;
21037 b = b<<8;
21038 a |= b;
21040 s = s<<4;
21041 b = p[-4];
21042 b &= 0x7f;
21043 b = b>>3;
21044 s |= b;
21046 *v = ((u64)s)<<32 | a;
21048 return 9;
21052 ** Read a 32-bit variable-length integer from memory starting at p[0].
21053 ** Return the number of bytes read. The value is stored in *v.
21055 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21056 ** integer, then set *v to 0xffffffff.
21058 ** A MACRO version, getVarint32, is provided which inlines the
21059 ** single-byte case. All code should use the MACRO version as
21060 ** this function assumes the single-byte case has already been handled.
21062 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21063 u32 a,b;
21065 /* The 1-byte case. Overwhelmingly the most common. Handled inline
21066 ** by the getVarin32() macro */
21067 a = *p;
21068 /* a: p0 (unmasked) */
21069 #ifndef getVarint32
21070 if (!(a&0x80))
21072 /* Values between 0 and 127 */
21073 *v = a;
21074 return 1;
21076 #endif
21078 /* The 2-byte case */
21079 p++;
21080 b = *p;
21081 /* b: p1 (unmasked) */
21082 if (!(b&0x80))
21084 /* Values between 128 and 16383 */
21085 a &= 0x7f;
21086 a = a<<7;
21087 *v = a | b;
21088 return 2;
21091 /* The 3-byte case */
21092 p++;
21093 a = a<<14;
21094 a |= *p;
21095 /* a: p0<<14 | p2 (unmasked) */
21096 if (!(a&0x80))
21098 /* Values between 16384 and 2097151 */
21099 a &= (0x7f<<14)|(0x7f);
21100 b &= 0x7f;
21101 b = b<<7;
21102 *v = a | b;
21103 return 3;
21106 /* A 32-bit varint is used to store size information in btrees.
21107 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21108 ** A 3-byte varint is sufficient, for example, to record the size
21109 ** of a 1048569-byte BLOB or string.
21111 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
21112 ** rare larger cases can be handled by the slower 64-bit varint
21113 ** routine.
21115 #if 1
21117 u64 v64;
21118 u8 n;
21120 p -= 2;
21121 n = sqlite3GetVarint(p, &v64);
21122 assert( n>3 && n<=9 );
21123 if( (v64 & SQLITE_MAX_U32)!=v64 ){
21124 *v = 0xffffffff;
21125 }else{
21126 *v = (u32)v64;
21128 return n;
21131 #else
21132 /* For following code (kept for historical record only) shows an
21133 ** unrolling for the 3- and 4-byte varint cases. This code is
21134 ** slightly faster, but it is also larger and much harder to test.
21136 p++;
21137 b = b<<14;
21138 b |= *p;
21139 /* b: p1<<14 | p3 (unmasked) */
21140 if (!(b&0x80))
21142 /* Values between 2097152 and 268435455 */
21143 b &= (0x7f<<14)|(0x7f);
21144 a &= (0x7f<<14)|(0x7f);
21145 a = a<<7;
21146 *v = a | b;
21147 return 4;
21150 p++;
21151 a = a<<14;
21152 a |= *p;
21153 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21154 if (!(a&0x80))
21156 /* Values between 268435456 and 34359738367 */
21157 a &= SLOT_4_2_0;
21158 b &= SLOT_4_2_0;
21159 b = b<<7;
21160 *v = a | b;
21161 return 5;
21164 /* We can only reach this point when reading a corrupt database
21165 ** file. In that case we are not in any hurry. Use the (relatively
21166 ** slow) general-purpose sqlite3GetVarint() routine to extract the
21167 ** value. */
21169 u64 v64;
21170 u8 n;
21172 p -= 4;
21173 n = sqlite3GetVarint(p, &v64);
21174 assert( n>5 && n<=9 );
21175 *v = (u32)v64;
21176 return n;
21178 #endif
21182 ** Return the number of bytes that will be needed to store the given
21183 ** 64-bit integer.
21185 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
21186 int i = 0;
21188 i++;
21189 v >>= 7;
21190 }while( v!=0 && ALWAYS(i<9) );
21191 return i;
21196 ** Read or write a four-byte big-endian integer value.
21198 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
21199 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
21201 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
21202 p[0] = (u8)(v>>24);
21203 p[1] = (u8)(v>>16);
21204 p[2] = (u8)(v>>8);
21205 p[3] = (u8)v;
21210 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21212 ** Translate a single byte of Hex into an integer.
21213 ** This routine only works if h really is a valid hexadecimal
21214 ** character: 0..9a..fA..F
21216 static u8 hexToInt(int h){
21217 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
21218 #ifdef SQLITE_ASCII
21219 h += 9*(1&(h>>6));
21220 #endif
21221 #ifdef SQLITE_EBCDIC
21222 h += 9*(1&~(h>>4));
21223 #endif
21224 return (u8)(h & 0xf);
21226 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21228 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21230 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
21231 ** value. Return a pointer to its binary value. Space to hold the
21232 ** binary value has been obtained from malloc and must be freed by
21233 ** the calling routine.
21235 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
21236 char *zBlob;
21237 int i;
21239 zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
21240 n--;
21241 if( zBlob ){
21242 for(i=0; i<n; i+=2){
21243 zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
21245 zBlob[i/2] = 0;
21247 return zBlob;
21249 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21252 ** Log an error that is an API call on a connection pointer that should
21253 ** not have been used. The "type" of connection pointer is given as the
21254 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
21256 static void logBadConnection(const char *zType){
21257 sqlite3_log(SQLITE_MISUSE,
21258 "API call with %s database connection pointer",
21259 zType
21264 ** Check to make sure we have a valid db pointer. This test is not
21265 ** foolproof but it does provide some measure of protection against
21266 ** misuse of the interface such as passing in db pointers that are
21267 ** NULL or which have been previously closed. If this routine returns
21268 ** 1 it means that the db pointer is valid and 0 if it should not be
21269 ** dereferenced for any reason. The calling function should invoke
21270 ** SQLITE_MISUSE immediately.
21272 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
21273 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
21274 ** open properly and is not fit for general use but which can be
21275 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
21277 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
21278 u32 magic;
21279 if( db==0 ){
21280 logBadConnection("NULL");
21281 return 0;
21283 magic = db->magic;
21284 if( magic!=SQLITE_MAGIC_OPEN ){
21285 if( sqlite3SafetyCheckSickOrOk(db) ){
21286 testcase( sqlite3GlobalConfig.xLog!=0 );
21287 logBadConnection("unopened");
21289 return 0;
21290 }else{
21291 return 1;
21294 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
21295 u32 magic;
21296 magic = db->magic;
21297 if( magic!=SQLITE_MAGIC_SICK &&
21298 magic!=SQLITE_MAGIC_OPEN &&
21299 magic!=SQLITE_MAGIC_BUSY ){
21300 testcase( sqlite3GlobalConfig.xLog!=0 );
21301 logBadConnection("invalid");
21302 return 0;
21303 }else{
21304 return 1;
21309 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
21310 ** the other 64-bit signed integer at *pA and store the result in *pA.
21311 ** Return 0 on success. Or if the operation would have resulted in an
21312 ** overflow, leave *pA unchanged and return 1.
21314 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
21315 i64 iA = *pA;
21316 testcase( iA==0 ); testcase( iA==1 );
21317 testcase( iB==-1 ); testcase( iB==0 );
21318 if( iB>=0 ){
21319 testcase( iA>0 && LARGEST_INT64 - iA == iB );
21320 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
21321 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
21322 *pA += iB;
21323 }else{
21324 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
21325 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
21326 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
21327 *pA += iB;
21329 return 0;
21331 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
21332 testcase( iB==SMALLEST_INT64+1 );
21333 if( iB==SMALLEST_INT64 ){
21334 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
21335 if( (*pA)>=0 ) return 1;
21336 *pA -= iB;
21337 return 0;
21338 }else{
21339 return sqlite3AddInt64(pA, -iB);
21342 #define TWOPOWER32 (((i64)1)<<32)
21343 #define TWOPOWER31 (((i64)1)<<31)
21344 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
21345 i64 iA = *pA;
21346 i64 iA1, iA0, iB1, iB0, r;
21348 iA1 = iA/TWOPOWER32;
21349 iA0 = iA % TWOPOWER32;
21350 iB1 = iB/TWOPOWER32;
21351 iB0 = iB % TWOPOWER32;
21352 if( iA1*iB1 != 0 ) return 1;
21353 assert( iA1*iB0==0 || iA0*iB1==0 );
21354 r = iA1*iB0 + iA0*iB1;
21355 testcase( r==(-TWOPOWER31)-1 );
21356 testcase( r==(-TWOPOWER31) );
21357 testcase( r==TWOPOWER31 );
21358 testcase( r==TWOPOWER31-1 );
21359 if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
21360 r *= TWOPOWER32;
21361 if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
21362 *pA = r;
21363 return 0;
21367 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
21368 ** if the integer has a value of -2147483648, return +2147483647
21370 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
21371 if( x>=0 ) return x;
21372 if( x==(int)0x80000000 ) return 0x7fffffff;
21373 return -x;
21376 /************** End of util.c ************************************************/
21377 /************** Begin file hash.c ********************************************/
21379 ** 2001 September 22
21381 ** The author disclaims copyright to this source code. In place of
21382 ** a legal notice, here is a blessing:
21384 ** May you do good and not evil.
21385 ** May you find forgiveness for yourself and forgive others.
21386 ** May you share freely, never taking more than you give.
21388 *************************************************************************
21389 ** This is the implementation of generic hash-tables
21390 ** used in SQLite.
21393 /* Turn bulk memory into a hash table object by initializing the
21394 ** fields of the Hash structure.
21396 ** "pNew" is a pointer to the hash table that is to be initialized.
21398 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
21399 assert( pNew!=0 );
21400 pNew->first = 0;
21401 pNew->count = 0;
21402 pNew->htsize = 0;
21403 pNew->ht = 0;
21406 /* Remove all entries from a hash table. Reclaim all memory.
21407 ** Call this routine to delete a hash table or to reset a hash table
21408 ** to the empty state.
21410 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
21411 HashElem *elem; /* For looping over all elements of the table */
21413 assert( pH!=0 );
21414 elem = pH->first;
21415 pH->first = 0;
21416 sqlite3_free(pH->ht);
21417 pH->ht = 0;
21418 pH->htsize = 0;
21419 while( elem ){
21420 HashElem *next_elem = elem->next;
21421 sqlite3_free(elem);
21422 elem = next_elem;
21424 pH->count = 0;
21428 ** The hashing function.
21430 static unsigned int strHash(const char *z, int nKey){
21431 int h = 0;
21432 assert( nKey>=0 );
21433 while( nKey > 0 ){
21434 h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
21435 nKey--;
21437 return h;
21441 /* Link pNew element into the hash table pH. If pEntry!=0 then also
21442 ** insert pNew into the pEntry hash bucket.
21444 static void insertElement(
21445 Hash *pH, /* The complete hash table */
21446 struct _ht *pEntry, /* The entry into which pNew is inserted */
21447 HashElem *pNew /* The element to be inserted */
21449 HashElem *pHead; /* First element already in pEntry */
21450 if( pEntry ){
21451 pHead = pEntry->count ? pEntry->chain : 0;
21452 pEntry->count++;
21453 pEntry->chain = pNew;
21454 }else{
21455 pHead = 0;
21457 if( pHead ){
21458 pNew->next = pHead;
21459 pNew->prev = pHead->prev;
21460 if( pHead->prev ){ pHead->prev->next = pNew; }
21461 else { pH->first = pNew; }
21462 pHead->prev = pNew;
21463 }else{
21464 pNew->next = pH->first;
21465 if( pH->first ){ pH->first->prev = pNew; }
21466 pNew->prev = 0;
21467 pH->first = pNew;
21472 /* Resize the hash table so that it cantains "new_size" buckets.
21474 ** The hash table might fail to resize if sqlite3_malloc() fails or
21475 ** if the new size is the same as the prior size.
21476 ** Return TRUE if the resize occurs and false if not.
21478 static int rehash(Hash *pH, unsigned int new_size){
21479 struct _ht *new_ht; /* The new hash table */
21480 HashElem *elem, *next_elem; /* For looping over existing elements */
21482 #if SQLITE_MALLOC_SOFT_LIMIT>0
21483 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
21484 new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
21486 if( new_size==pH->htsize ) return 0;
21487 #endif
21489 /* The inability to allocates space for a larger hash table is
21490 ** a performance hit but it is not a fatal error. So mark the
21491 ** allocation as a benign.
21493 sqlite3BeginBenignMalloc();
21494 new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
21495 sqlite3EndBenignMalloc();
21497 if( new_ht==0 ) return 0;
21498 sqlite3_free(pH->ht);
21499 pH->ht = new_ht;
21500 pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
21501 memset(new_ht, 0, new_size*sizeof(struct _ht));
21502 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
21503 unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
21504 next_elem = elem->next;
21505 insertElement(pH, &new_ht[h], elem);
21507 return 1;
21510 /* This function (for internal use only) locates an element in an
21511 ** hash table that matches the given key. The hash for this key has
21512 ** already been computed and is passed as the 4th parameter.
21514 static HashElem *findElementGivenHash(
21515 const Hash *pH, /* The pH to be searched */
21516 const char *pKey, /* The key we are searching for */
21517 int nKey, /* Bytes in key (not counting zero terminator) */
21518 unsigned int h /* The hash for this key. */
21520 HashElem *elem; /* Used to loop thru the element list */
21521 int count; /* Number of elements left to test */
21523 if( pH->ht ){
21524 struct _ht *pEntry = &pH->ht[h];
21525 elem = pEntry->chain;
21526 count = pEntry->count;
21527 }else{
21528 elem = pH->first;
21529 count = pH->count;
21531 while( count-- && ALWAYS(elem) ){
21532 if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
21533 return elem;
21535 elem = elem->next;
21537 return 0;
21540 /* Remove a single entry from the hash table given a pointer to that
21541 ** element and a hash on the element's key.
21543 static void removeElementGivenHash(
21544 Hash *pH, /* The pH containing "elem" */
21545 HashElem* elem, /* The element to be removed from the pH */
21546 unsigned int h /* Hash value for the element */
21548 struct _ht *pEntry;
21549 if( elem->prev ){
21550 elem->prev->next = elem->next;
21551 }else{
21552 pH->first = elem->next;
21554 if( elem->next ){
21555 elem->next->prev = elem->prev;
21557 if( pH->ht ){
21558 pEntry = &pH->ht[h];
21559 if( pEntry->chain==elem ){
21560 pEntry->chain = elem->next;
21562 pEntry->count--;
21563 assert( pEntry->count>=0 );
21565 sqlite3_free( elem );
21566 pH->count--;
21567 if( pH->count<=0 ){
21568 assert( pH->first==0 );
21569 assert( pH->count==0 );
21570 sqlite3HashClear(pH);
21574 /* Attempt to locate an element of the hash table pH with a key
21575 ** that matches pKey,nKey. Return the data for this element if it is
21576 ** found, or NULL if there is no match.
21578 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
21579 HashElem *elem; /* The element that matches key */
21580 unsigned int h; /* A hash on key */
21582 assert( pH!=0 );
21583 assert( pKey!=0 );
21584 assert( nKey>=0 );
21585 if( pH->ht ){
21586 h = strHash(pKey, nKey) % pH->htsize;
21587 }else{
21588 h = 0;
21590 elem = findElementGivenHash(pH, pKey, nKey, h);
21591 return elem ? elem->data : 0;
21594 /* Insert an element into the hash table pH. The key is pKey,nKey
21595 ** and the data is "data".
21597 ** If no element exists with a matching key, then a new
21598 ** element is created and NULL is returned.
21600 ** If another element already exists with the same key, then the
21601 ** new data replaces the old data and the old data is returned.
21602 ** The key is not copied in this instance. If a malloc fails, then
21603 ** the new data is returned and the hash table is unchanged.
21605 ** If the "data" parameter to this function is NULL, then the
21606 ** element corresponding to "key" is removed from the hash table.
21608 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
21609 unsigned int h; /* the hash of the key modulo hash table size */
21610 HashElem *elem; /* Used to loop thru the element list */
21611 HashElem *new_elem; /* New element added to the pH */
21613 assert( pH!=0 );
21614 assert( pKey!=0 );
21615 assert( nKey>=0 );
21616 if( pH->htsize ){
21617 h = strHash(pKey, nKey) % pH->htsize;
21618 }else{
21619 h = 0;
21621 elem = findElementGivenHash(pH,pKey,nKey,h);
21622 if( elem ){
21623 void *old_data = elem->data;
21624 if( data==0 ){
21625 removeElementGivenHash(pH,elem,h);
21626 }else{
21627 elem->data = data;
21628 elem->pKey = pKey;
21629 assert(nKey==elem->nKey);
21631 return old_data;
21633 if( data==0 ) return 0;
21634 new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
21635 if( new_elem==0 ) return data;
21636 new_elem->pKey = pKey;
21637 new_elem->nKey = nKey;
21638 new_elem->data = data;
21639 pH->count++;
21640 if( pH->count>=10 && pH->count > 2*pH->htsize ){
21641 if( rehash(pH, pH->count*2) ){
21642 assert( pH->htsize>0 );
21643 h = strHash(pKey, nKey) % pH->htsize;
21646 if( pH->ht ){
21647 insertElement(pH, &pH->ht[h], new_elem);
21648 }else{
21649 insertElement(pH, 0, new_elem);
21651 return 0;
21654 /************** End of hash.c ************************************************/
21655 /************** Begin file opcodes.c *****************************************/
21656 /* Automatically generated. Do not edit */
21657 /* See the mkopcodec.awk script for details. */
21658 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
21659 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
21660 static const char *const azName[] = { "?",
21661 /* 1 */ "Goto",
21662 /* 2 */ "Gosub",
21663 /* 3 */ "Return",
21664 /* 4 */ "Yield",
21665 /* 5 */ "HaltIfNull",
21666 /* 6 */ "Halt",
21667 /* 7 */ "Integer",
21668 /* 8 */ "Int64",
21669 /* 9 */ "String",
21670 /* 10 */ "Null",
21671 /* 11 */ "Blob",
21672 /* 12 */ "Variable",
21673 /* 13 */ "Move",
21674 /* 14 */ "Copy",
21675 /* 15 */ "SCopy",
21676 /* 16 */ "ResultRow",
21677 /* 17 */ "CollSeq",
21678 /* 18 */ "Function",
21679 /* 19 */ "Not",
21680 /* 20 */ "AddImm",
21681 /* 21 */ "MustBeInt",
21682 /* 22 */ "RealAffinity",
21683 /* 23 */ "Permutation",
21684 /* 24 */ "Compare",
21685 /* 25 */ "Jump",
21686 /* 26 */ "If",
21687 /* 27 */ "IfNot",
21688 /* 28 */ "Column",
21689 /* 29 */ "Affinity",
21690 /* 30 */ "MakeRecord",
21691 /* 31 */ "Count",
21692 /* 32 */ "Savepoint",
21693 /* 33 */ "AutoCommit",
21694 /* 34 */ "Transaction",
21695 /* 35 */ "ReadCookie",
21696 /* 36 */ "SetCookie",
21697 /* 37 */ "VerifyCookie",
21698 /* 38 */ "OpenRead",
21699 /* 39 */ "OpenWrite",
21700 /* 40 */ "OpenAutoindex",
21701 /* 41 */ "OpenEphemeral",
21702 /* 42 */ "OpenPseudo",
21703 /* 43 */ "Close",
21704 /* 44 */ "SeekLt",
21705 /* 45 */ "SeekLe",
21706 /* 46 */ "SeekGe",
21707 /* 47 */ "SeekGt",
21708 /* 48 */ "Seek",
21709 /* 49 */ "NotFound",
21710 /* 50 */ "Found",
21711 /* 51 */ "IsUnique",
21712 /* 52 */ "NotExists",
21713 /* 53 */ "Sequence",
21714 /* 54 */ "NewRowid",
21715 /* 55 */ "Insert",
21716 /* 56 */ "InsertInt",
21717 /* 57 */ "Delete",
21718 /* 58 */ "ResetCount",
21719 /* 59 */ "RowKey",
21720 /* 60 */ "RowData",
21721 /* 61 */ "Rowid",
21722 /* 62 */ "NullRow",
21723 /* 63 */ "Last",
21724 /* 64 */ "Sort",
21725 /* 65 */ "Rewind",
21726 /* 66 */ "Prev",
21727 /* 67 */ "Next",
21728 /* 68 */ "Or",
21729 /* 69 */ "And",
21730 /* 70 */ "IdxInsert",
21731 /* 71 */ "IdxDelete",
21732 /* 72 */ "IdxRowid",
21733 /* 73 */ "IsNull",
21734 /* 74 */ "NotNull",
21735 /* 75 */ "Ne",
21736 /* 76 */ "Eq",
21737 /* 77 */ "Gt",
21738 /* 78 */ "Le",
21739 /* 79 */ "Lt",
21740 /* 80 */ "Ge",
21741 /* 81 */ "IdxLT",
21742 /* 82 */ "BitAnd",
21743 /* 83 */ "BitOr",
21744 /* 84 */ "ShiftLeft",
21745 /* 85 */ "ShiftRight",
21746 /* 86 */ "Add",
21747 /* 87 */ "Subtract",
21748 /* 88 */ "Multiply",
21749 /* 89 */ "Divide",
21750 /* 90 */ "Remainder",
21751 /* 91 */ "Concat",
21752 /* 92 */ "IdxGE",
21753 /* 93 */ "BitNot",
21754 /* 94 */ "String8",
21755 /* 95 */ "Destroy",
21756 /* 96 */ "Clear",
21757 /* 97 */ "CreateIndex",
21758 /* 98 */ "CreateTable",
21759 /* 99 */ "ParseSchema",
21760 /* 100 */ "LoadAnalysis",
21761 /* 101 */ "DropTable",
21762 /* 102 */ "DropIndex",
21763 /* 103 */ "DropTrigger",
21764 /* 104 */ "IntegrityCk",
21765 /* 105 */ "RowSetAdd",
21766 /* 106 */ "RowSetRead",
21767 /* 107 */ "RowSetTest",
21768 /* 108 */ "Program",
21769 /* 109 */ "Param",
21770 /* 110 */ "FkCounter",
21771 /* 111 */ "FkIfZero",
21772 /* 112 */ "MemMax",
21773 /* 113 */ "IfPos",
21774 /* 114 */ "IfNeg",
21775 /* 115 */ "IfZero",
21776 /* 116 */ "AggStep",
21777 /* 117 */ "AggFinal",
21778 /* 118 */ "Checkpoint",
21779 /* 119 */ "JournalMode",
21780 /* 120 */ "Vacuum",
21781 /* 121 */ "IncrVacuum",
21782 /* 122 */ "Expire",
21783 /* 123 */ "TableLock",
21784 /* 124 */ "VBegin",
21785 /* 125 */ "VCreate",
21786 /* 126 */ "VDestroy",
21787 /* 127 */ "VOpen",
21788 /* 128 */ "VFilter",
21789 /* 129 */ "VColumn",
21790 /* 130 */ "Real",
21791 /* 131 */ "VNext",
21792 /* 132 */ "VRename",
21793 /* 133 */ "VUpdate",
21794 /* 134 */ "Pagecount",
21795 /* 135 */ "MaxPgcnt",
21796 /* 136 */ "Trace",
21797 /* 137 */ "Noop",
21798 /* 138 */ "Explain",
21799 /* 139 */ "NotUsed_139",
21800 /* 140 */ "NotUsed_140",
21801 /* 141 */ "ToText",
21802 /* 142 */ "ToBlob",
21803 /* 143 */ "ToNumeric",
21804 /* 144 */ "ToInt",
21805 /* 145 */ "ToReal",
21807 return azName[i];
21809 #endif
21811 /************** End of opcodes.c *********************************************/
21812 /************** Begin file os_os2.c ******************************************/
21814 ** 2006 Feb 14
21816 ** The author disclaims copyright to this source code. In place of
21817 ** a legal notice, here is a blessing:
21819 ** May you do good and not evil.
21820 ** May you find forgiveness for yourself and forgive others.
21821 ** May you share freely, never taking more than you give.
21823 ******************************************************************************
21825 ** This file contains code that is specific to OS/2.
21829 #if SQLITE_OS_OS2
21832 ** A Note About Memory Allocation:
21834 ** This driver uses malloc()/free() directly rather than going through
21835 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
21836 ** are designed for use on embedded systems where memory is scarce and
21837 ** malloc failures happen frequently. OS/2 does not typically run on
21838 ** embedded systems, and when it does the developers normally have bigger
21839 ** problems to worry about than running out of memory. So there is not
21840 ** a compelling need to use the wrappers.
21842 ** But there is a good reason to not use the wrappers. If we use the
21843 ** wrappers then we will get simulated malloc() failures within this
21844 ** driver. And that causes all kinds of problems for our tests. We
21845 ** could enhance SQLite to deal with simulated malloc failures within
21846 ** the OS driver, but the code to deal with those failure would not
21847 ** be exercised on Linux (which does not need to malloc() in the driver)
21848 ** and so we would have difficulty writing coverage tests for that
21849 ** code. Better to leave the code out, we think.
21851 ** The point of this discussion is as follows: When creating a new
21852 ** OS layer for an embedded system, if you use this file as an example,
21853 ** avoid the use of malloc()/free(). Those routines work ok on OS/2
21854 ** desktops but not so well in embedded systems.
21858 ** Macros used to determine whether or not to use threads.
21860 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
21861 # define SQLITE_OS2_THREADS 1
21862 #endif
21865 ** Include code that is common to all os_*.c files
21867 /************** Include os_common.h in the middle of os_os2.c ****************/
21868 /************** Begin file os_common.h ***************************************/
21870 ** 2004 May 22
21872 ** The author disclaims copyright to this source code. In place of
21873 ** a legal notice, here is a blessing:
21875 ** May you do good and not evil.
21876 ** May you find forgiveness for yourself and forgive others.
21877 ** May you share freely, never taking more than you give.
21879 ******************************************************************************
21881 ** This file contains macros and a little bit of code that is common to
21882 ** all of the platform-specific files (os_*.c) and is #included into those
21883 ** files.
21885 ** This file should be #included by the os_*.c files only. It is not a
21886 ** general purpose header file.
21888 #ifndef _OS_COMMON_H_
21889 #define _OS_COMMON_H_
21892 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21893 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21894 ** switch. The following code should catch this problem at compile-time.
21896 #ifdef MEMORY_DEBUG
21897 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
21898 #endif
21900 #ifdef SQLITE_DEBUG
21901 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21902 #define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
21903 #else
21904 #define OSTRACE(X)
21905 #endif
21908 ** Macros for performance tracing. Normally turned off. Only works
21909 ** on i486 hardware.
21911 #ifdef SQLITE_PERFORMANCE_TRACE
21914 ** hwtime.h contains inline assembler code for implementing
21915 ** high-performance timing routines.
21917 /************** Include hwtime.h in the middle of os_common.h ****************/
21918 /************** Begin file hwtime.h ******************************************/
21920 ** 2008 May 27
21922 ** The author disclaims copyright to this source code. In place of
21923 ** a legal notice, here is a blessing:
21925 ** May you do good and not evil.
21926 ** May you find forgiveness for yourself and forgive others.
21927 ** May you share freely, never taking more than you give.
21929 ******************************************************************************
21931 ** This file contains inline asm code for retrieving "high-performance"
21932 ** counters for x86 class CPUs.
21934 #ifndef _HWTIME_H_
21935 #define _HWTIME_H_
21938 ** The following routine only works on pentium-class (or newer) processors.
21939 ** It uses the RDTSC opcode to read the cycle count value out of the
21940 ** processor and returns that value. This can be used for high-res
21941 ** profiling.
21943 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21944 (defined(i386) || defined(__i386__) || defined(_M_IX86))
21946 #if defined(__GNUC__)
21948 __inline__ sqlite_uint64 sqlite3Hwtime(void){
21949 unsigned int lo, hi;
21950 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21951 return (sqlite_uint64)hi << 32 | lo;
21954 #elif defined(_MSC_VER)
21956 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21957 __asm {
21958 rdtsc
21959 ret ; return value at EDX:EAX
21963 #endif
21965 #elif (defined(__GNUC__) && defined(__x86_64__))
21967 __inline__ sqlite_uint64 sqlite3Hwtime(void){
21968 unsigned long val;
21969 __asm__ __volatile__ ("rdtsc" : "=A" (val));
21970 return val;
21973 #elif (defined(__GNUC__) && defined(__ppc__))
21975 __inline__ sqlite_uint64 sqlite3Hwtime(void){
21976 unsigned long long retval;
21977 unsigned long junk;
21978 __asm__ __volatile__ ("\n\
21979 1: mftbu %1\n\
21980 mftb %L0\n\
21981 mftbu %0\n\
21982 cmpw %0,%1\n\
21983 bne 1b"
21984 : "=r" (retval), "=r" (junk));
21985 return retval;
21988 #else
21990 #error Need implementation of sqlite3Hwtime() for your platform.
21993 ** To compile without implementing sqlite3Hwtime() for your platform,
21994 ** you can remove the above #error and use the following
21995 ** stub function. You will lose timing support for many
21996 ** of the debugging and testing utilities, but it should at
21997 ** least compile and run.
21999 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22001 #endif
22003 #endif /* !defined(_HWTIME_H_) */
22005 /************** End of hwtime.h **********************************************/
22006 /************** Continuing where we left off in os_common.h ******************/
22008 static sqlite_uint64 g_start;
22009 static sqlite_uint64 g_elapsed;
22010 #define TIMER_START g_start=sqlite3Hwtime()
22011 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
22012 #define TIMER_ELAPSED g_elapsed
22013 #else
22014 #define TIMER_START
22015 #define TIMER_END
22016 #define TIMER_ELAPSED ((sqlite_uint64)0)
22017 #endif
22020 ** If we compile with the SQLITE_TEST macro set, then the following block
22021 ** of code will give us the ability to simulate a disk I/O error. This
22022 ** is used for testing the I/O recovery logic.
22024 #ifdef SQLITE_TEST
22025 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
22026 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
22027 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
22028 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
22029 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
22030 SQLITE_API int sqlite3_diskfull_pending = 0;
22031 SQLITE_API int sqlite3_diskfull = 0;
22032 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22033 #define SimulateIOError(CODE) \
22034 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22035 || sqlite3_io_error_pending-- == 1 ) \
22036 { local_ioerr(); CODE; }
22037 static void local_ioerr(){
22038 IOTRACE(("IOERR\n"));
22039 sqlite3_io_error_hit++;
22040 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22042 #define SimulateDiskfullError(CODE) \
22043 if( sqlite3_diskfull_pending ){ \
22044 if( sqlite3_diskfull_pending == 1 ){ \
22045 local_ioerr(); \
22046 sqlite3_diskfull = 1; \
22047 sqlite3_io_error_hit = 1; \
22048 CODE; \
22049 }else{ \
22050 sqlite3_diskfull_pending--; \
22053 #else
22054 #define SimulateIOErrorBenign(X)
22055 #define SimulateIOError(A)
22056 #define SimulateDiskfullError(A)
22057 #endif
22060 ** When testing, keep a count of the number of open files.
22062 #ifdef SQLITE_TEST
22063 SQLITE_API int sqlite3_open_file_count = 0;
22064 #define OpenCounter(X) sqlite3_open_file_count+=(X)
22065 #else
22066 #define OpenCounter(X)
22067 #endif
22069 #endif /* !defined(_OS_COMMON_H_) */
22071 /************** End of os_common.h *******************************************/
22072 /************** Continuing where we left off in os_os2.c *********************/
22074 /* Forward references */
22075 typedef struct os2File os2File; /* The file structure */
22076 typedef struct os2ShmNode os2ShmNode; /* A shared descritive memory node */
22077 typedef struct os2ShmLink os2ShmLink; /* A connection to shared-memory */
22080 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
22081 ** protability layer.
22083 struct os2File {
22084 const sqlite3_io_methods *pMethod; /* Always the first entry */
22085 HFILE h; /* Handle for accessing the file */
22086 int flags; /* Flags provided to os2Open() */
22087 int locktype; /* Type of lock currently held on this file */
22088 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
22089 char *zFullPathCp; /* Full path name of this file */
22090 os2ShmLink *pShmLink; /* Instance of shared memory on this file */
22093 #define LOCK_TIMEOUT 10L /* the default locking timeout */
22096 ** Missing from some versions of the OS/2 toolkit -
22097 ** used to allocate from high memory if possible
22099 #ifndef OBJ_ANY
22100 # define OBJ_ANY 0x00000400
22101 #endif
22103 /*****************************************************************************
22104 ** The next group of routines implement the I/O methods specified
22105 ** by the sqlite3_io_methods object.
22106 ******************************************************************************/
22109 ** Close a file.
22111 static int os2Close( sqlite3_file *id ){
22112 APIRET rc;
22113 os2File *pFile = (os2File*)id;
22115 assert( id!=0 );
22116 OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
22118 rc = DosClose( pFile->h );
22120 if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
22121 DosForceDelete( (PSZ)pFile->zFullPathCp );
22123 free( pFile->zFullPathCp );
22124 pFile->zFullPathCp = NULL;
22125 pFile->locktype = NO_LOCK;
22126 pFile->h = (HFILE)-1;
22127 pFile->flags = 0;
22129 OpenCounter( -1 );
22130 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22134 ** Read data from a file into a buffer. Return SQLITE_OK if all
22135 ** bytes were read successfully and SQLITE_IOERR if anything goes
22136 ** wrong.
22138 static int os2Read(
22139 sqlite3_file *id, /* File to read from */
22140 void *pBuf, /* Write content into this buffer */
22141 int amt, /* Number of bytes to read */
22142 sqlite3_int64 offset /* Begin reading at this offset */
22144 ULONG fileLocation = 0L;
22145 ULONG got;
22146 os2File *pFile = (os2File*)id;
22147 assert( id!=0 );
22148 SimulateIOError( return SQLITE_IOERR_READ );
22149 OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
22150 if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22151 return SQLITE_IOERR;
22153 if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
22154 return SQLITE_IOERR_READ;
22156 if( got == (ULONG)amt )
22157 return SQLITE_OK;
22158 else {
22159 /* Unread portions of the input buffer must be zero-filled */
22160 memset(&((char*)pBuf)[got], 0, amt-got);
22161 return SQLITE_IOERR_SHORT_READ;
22166 ** Write data from a buffer into a file. Return SQLITE_OK on success
22167 ** or some other error code on failure.
22169 static int os2Write(
22170 sqlite3_file *id, /* File to write into */
22171 const void *pBuf, /* The bytes to be written */
22172 int amt, /* Number of bytes to write */
22173 sqlite3_int64 offset /* Offset into the file to begin writing at */
22175 ULONG fileLocation = 0L;
22176 APIRET rc = NO_ERROR;
22177 ULONG wrote;
22178 os2File *pFile = (os2File*)id;
22179 assert( id!=0 );
22180 SimulateIOError( return SQLITE_IOERR_WRITE );
22181 SimulateDiskfullError( return SQLITE_FULL );
22182 OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
22183 if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22184 return SQLITE_IOERR;
22186 assert( amt>0 );
22187 while( amt > 0 &&
22188 ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
22189 wrote > 0
22191 amt -= wrote;
22192 pBuf = &((char*)pBuf)[wrote];
22195 return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
22199 ** Truncate an open file to a specified size
22201 static int os2Truncate( sqlite3_file *id, i64 nByte ){
22202 APIRET rc;
22203 os2File *pFile = (os2File*)id;
22204 assert( id!=0 );
22205 OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
22206 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22208 /* If the user has configured a chunk-size for this file, truncate the
22209 ** file so that it consists of an integer number of chunks (i.e. the
22210 ** actual file size after the operation may be larger than the requested
22211 ** size).
22213 if( pFile->szChunk ){
22214 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
22217 rc = DosSetFileSize( pFile->h, nByte );
22218 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
22221 #ifdef SQLITE_TEST
22223 ** Count the number of fullsyncs and normal syncs. This is used to test
22224 ** that syncs and fullsyncs are occuring at the right times.
22226 SQLITE_API int sqlite3_sync_count = 0;
22227 SQLITE_API int sqlite3_fullsync_count = 0;
22228 #endif
22231 ** Make sure all writes to a particular file are committed to disk.
22233 static int os2Sync( sqlite3_file *id, int flags ){
22234 os2File *pFile = (os2File*)id;
22235 OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
22236 #ifdef SQLITE_TEST
22237 if( flags & SQLITE_SYNC_FULL){
22238 sqlite3_fullsync_count++;
22240 sqlite3_sync_count++;
22241 #endif
22242 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22243 ** no-op
22245 #ifdef SQLITE_NO_SYNC
22246 UNUSED_PARAMETER(pFile);
22247 return SQLITE_OK;
22248 #else
22249 return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22250 #endif
22254 ** Determine the current size of a file in bytes
22256 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
22257 APIRET rc = NO_ERROR;
22258 FILESTATUS3 fsts3FileInfo;
22259 memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
22260 assert( id!=0 );
22261 SimulateIOError( return SQLITE_IOERR_FSTAT );
22262 rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
22263 if( rc == NO_ERROR ){
22264 *pSize = fsts3FileInfo.cbFile;
22265 return SQLITE_OK;
22266 }else{
22267 return SQLITE_IOERR_FSTAT;
22272 ** Acquire a reader lock.
22274 static int getReadLock( os2File *pFile ){
22275 FILELOCK LockArea,
22276 UnlockArea;
22277 APIRET res;
22278 memset(&LockArea, 0, sizeof(LockArea));
22279 memset(&UnlockArea, 0, sizeof(UnlockArea));
22280 LockArea.lOffset = SHARED_FIRST;
22281 LockArea.lRange = SHARED_SIZE;
22282 UnlockArea.lOffset = 0L;
22283 UnlockArea.lRange = 0L;
22284 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22285 OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
22286 return res;
22290 ** Undo a readlock
22292 static int unlockReadLock( os2File *id ){
22293 FILELOCK LockArea,
22294 UnlockArea;
22295 APIRET res;
22296 memset(&LockArea, 0, sizeof(LockArea));
22297 memset(&UnlockArea, 0, sizeof(UnlockArea));
22298 LockArea.lOffset = 0L;
22299 LockArea.lRange = 0L;
22300 UnlockArea.lOffset = SHARED_FIRST;
22301 UnlockArea.lRange = SHARED_SIZE;
22302 res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22303 OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
22304 return res;
22308 ** Lock the file with the lock specified by parameter locktype - one
22309 ** of the following:
22311 ** (1) SHARED_LOCK
22312 ** (2) RESERVED_LOCK
22313 ** (3) PENDING_LOCK
22314 ** (4) EXCLUSIVE_LOCK
22316 ** Sometimes when requesting one lock state, additional lock states
22317 ** are inserted in between. The locking might fail on one of the later
22318 ** transitions leaving the lock state different from what it started but
22319 ** still short of its goal. The following chart shows the allowed
22320 ** transitions and the inserted intermediate states:
22322 ** UNLOCKED -> SHARED
22323 ** SHARED -> RESERVED
22324 ** SHARED -> (PENDING) -> EXCLUSIVE
22325 ** RESERVED -> (PENDING) -> EXCLUSIVE
22326 ** PENDING -> EXCLUSIVE
22328 ** This routine will only increase a lock. The os2Unlock() routine
22329 ** erases all locks at once and returns us immediately to locking level 0.
22330 ** It is not possible to lower the locking level one step at a time. You
22331 ** must go straight to locking level 0.
22333 static int os2Lock( sqlite3_file *id, int locktype ){
22334 int rc = SQLITE_OK; /* Return code from subroutines */
22335 APIRET res = NO_ERROR; /* Result of an OS/2 lock call */
22336 int newLocktype; /* Set pFile->locktype to this value before exiting */
22337 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
22338 FILELOCK LockArea,
22339 UnlockArea;
22340 os2File *pFile = (os2File*)id;
22341 memset(&LockArea, 0, sizeof(LockArea));
22342 memset(&UnlockArea, 0, sizeof(UnlockArea));
22343 assert( pFile!=0 );
22344 OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
22346 /* If there is already a lock of this type or more restrictive on the
22347 ** os2File, do nothing. Don't use the end_lock: exit path, as
22348 ** sqlite3_mutex_enter() hasn't been called yet.
22350 if( pFile->locktype>=locktype ){
22351 OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
22352 return SQLITE_OK;
22355 /* Make sure the locking sequence is correct
22357 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22358 assert( locktype!=PENDING_LOCK );
22359 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22361 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
22362 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
22363 ** the PENDING_LOCK byte is temporary.
22365 newLocktype = pFile->locktype;
22366 if( pFile->locktype==NO_LOCK
22367 || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
22369 LockArea.lOffset = PENDING_BYTE;
22370 LockArea.lRange = 1L;
22371 UnlockArea.lOffset = 0L;
22372 UnlockArea.lRange = 0L;
22374 /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
22375 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
22376 if( res == NO_ERROR ){
22377 gotPendingLock = 1;
22378 OSTRACE(( "LOCK %d pending lock boolean set. res=%d\n", pFile->h, res ));
22382 /* Acquire a shared lock
22384 if( locktype==SHARED_LOCK && res == NO_ERROR ){
22385 assert( pFile->locktype==NO_LOCK );
22386 res = getReadLock(pFile);
22387 if( res == NO_ERROR ){
22388 newLocktype = SHARED_LOCK;
22390 OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
22393 /* Acquire a RESERVED lock
22395 if( locktype==RESERVED_LOCK && res == NO_ERROR ){
22396 assert( pFile->locktype==SHARED_LOCK );
22397 LockArea.lOffset = RESERVED_BYTE;
22398 LockArea.lRange = 1L;
22399 UnlockArea.lOffset = 0L;
22400 UnlockArea.lRange = 0L;
22401 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22402 if( res == NO_ERROR ){
22403 newLocktype = RESERVED_LOCK;
22405 OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
22408 /* Acquire a PENDING lock
22410 if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22411 newLocktype = PENDING_LOCK;
22412 gotPendingLock = 0;
22413 OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
22414 pFile->h ));
22417 /* Acquire an EXCLUSIVE lock
22419 if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22420 assert( pFile->locktype>=SHARED_LOCK );
22421 res = unlockReadLock(pFile);
22422 OSTRACE(( "unreadlock = %d\n", res ));
22423 LockArea.lOffset = SHARED_FIRST;
22424 LockArea.lRange = SHARED_SIZE;
22425 UnlockArea.lOffset = 0L;
22426 UnlockArea.lRange = 0L;
22427 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22428 if( res == NO_ERROR ){
22429 newLocktype = EXCLUSIVE_LOCK;
22430 }else{
22431 OSTRACE(( "OS/2 error-code = %d\n", res ));
22432 getReadLock(pFile);
22434 OSTRACE(( "LOCK %d acquire exclusive lock. res=%d\n", pFile->h, res ));
22437 /* If we are holding a PENDING lock that ought to be released, then
22438 ** release it now.
22440 if( gotPendingLock && locktype==SHARED_LOCK ){
22441 int r;
22442 LockArea.lOffset = 0L;
22443 LockArea.lRange = 0L;
22444 UnlockArea.lOffset = PENDING_BYTE;
22445 UnlockArea.lRange = 1L;
22446 r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22447 OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
22450 /* Update the state of the lock has held in the file descriptor then
22451 ** return the appropriate result code.
22453 if( res == NO_ERROR ){
22454 rc = SQLITE_OK;
22455 }else{
22456 OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
22457 locktype, newLocktype ));
22458 rc = SQLITE_BUSY;
22460 pFile->locktype = newLocktype;
22461 OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
22462 return rc;
22466 ** This routine checks if there is a RESERVED lock held on the specified
22467 ** file by this or any other process. If such a lock is held, return
22468 ** non-zero, otherwise zero.
22470 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
22471 int r = 0;
22472 os2File *pFile = (os2File*)id;
22473 assert( pFile!=0 );
22474 if( pFile->locktype>=RESERVED_LOCK ){
22475 r = 1;
22476 OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
22477 }else{
22478 FILELOCK LockArea,
22479 UnlockArea;
22480 APIRET rc = NO_ERROR;
22481 memset(&LockArea, 0, sizeof(LockArea));
22482 memset(&UnlockArea, 0, sizeof(UnlockArea));
22483 LockArea.lOffset = RESERVED_BYTE;
22484 LockArea.lRange = 1L;
22485 UnlockArea.lOffset = 0L;
22486 UnlockArea.lRange = 0L;
22487 rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22488 OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
22489 if( rc == NO_ERROR ){
22490 APIRET rcu = NO_ERROR; /* return code for unlocking */
22491 LockArea.lOffset = 0L;
22492 LockArea.lRange = 0L;
22493 UnlockArea.lOffset = RESERVED_BYTE;
22494 UnlockArea.lRange = 1L;
22495 rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22496 OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
22498 r = !(rc == NO_ERROR);
22499 OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
22501 *pOut = r;
22502 return SQLITE_OK;
22506 ** Lower the locking level on file descriptor id to locktype. locktype
22507 ** must be either NO_LOCK or SHARED_LOCK.
22509 ** If the locking level of the file descriptor is already at or below
22510 ** the requested locking level, this routine is a no-op.
22512 ** It is not possible for this routine to fail if the second argument
22513 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
22514 ** might return SQLITE_IOERR;
22516 static int os2Unlock( sqlite3_file *id, int locktype ){
22517 int type;
22518 os2File *pFile = (os2File*)id;
22519 APIRET rc = SQLITE_OK;
22520 APIRET res = NO_ERROR;
22521 FILELOCK LockArea,
22522 UnlockArea;
22523 memset(&LockArea, 0, sizeof(LockArea));
22524 memset(&UnlockArea, 0, sizeof(UnlockArea));
22525 assert( pFile!=0 );
22526 assert( locktype<=SHARED_LOCK );
22527 OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
22528 type = pFile->locktype;
22529 if( type>=EXCLUSIVE_LOCK ){
22530 LockArea.lOffset = 0L;
22531 LockArea.lRange = 0L;
22532 UnlockArea.lOffset = SHARED_FIRST;
22533 UnlockArea.lRange = SHARED_SIZE;
22534 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22535 OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
22536 if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
22537 /* This should never happen. We should always be able to
22538 ** reacquire the read lock */
22539 OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
22540 rc = SQLITE_IOERR_UNLOCK;
22543 if( type>=RESERVED_LOCK ){
22544 LockArea.lOffset = 0L;
22545 LockArea.lRange = 0L;
22546 UnlockArea.lOffset = RESERVED_BYTE;
22547 UnlockArea.lRange = 1L;
22548 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22549 OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
22551 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22552 res = unlockReadLock(pFile);
22553 OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
22554 pFile->h, type, locktype, res ));
22556 if( type>=PENDING_LOCK ){
22557 LockArea.lOffset = 0L;
22558 LockArea.lRange = 0L;
22559 UnlockArea.lOffset = PENDING_BYTE;
22560 UnlockArea.lRange = 1L;
22561 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22562 OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
22564 pFile->locktype = locktype;
22565 OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
22566 return rc;
22570 ** Control and query of the open file handle.
22572 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
22573 switch( op ){
22574 case SQLITE_FCNTL_LOCKSTATE: {
22575 *(int*)pArg = ((os2File*)id)->locktype;
22576 OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
22577 ((os2File*)id)->h, ((os2File*)id)->locktype ));
22578 return SQLITE_OK;
22580 case SQLITE_FCNTL_CHUNK_SIZE: {
22581 ((os2File*)id)->szChunk = *(int*)pArg;
22582 return SQLITE_OK;
22584 case SQLITE_FCNTL_SIZE_HINT: {
22585 sqlite3_int64 sz = *(sqlite3_int64*)pArg;
22586 SimulateIOErrorBenign(1);
22587 os2Truncate(id, sz);
22588 SimulateIOErrorBenign(0);
22589 return SQLITE_OK;
22591 case SQLITE_FCNTL_SYNC_OMITTED: {
22592 return SQLITE_OK;
22595 return SQLITE_NOTFOUND;
22599 ** Return the sector size in bytes of the underlying block device for
22600 ** the specified file. This is almost always 512 bytes, but may be
22601 ** larger for some devices.
22603 ** SQLite code assumes this function cannot fail. It also assumes that
22604 ** if two files are created in the same file-system directory (i.e.
22605 ** a database and its journal file) that the sector size will be the
22606 ** same for both.
22608 static int os2SectorSize(sqlite3_file *id){
22609 UNUSED_PARAMETER(id);
22610 return SQLITE_DEFAULT_SECTOR_SIZE;
22614 ** Return a vector of device characteristics.
22616 static int os2DeviceCharacteristics(sqlite3_file *id){
22617 UNUSED_PARAMETER(id);
22618 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
22623 ** Character set conversion objects used by conversion routines.
22625 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
22626 static UconvObject uclCp = NULL; /* convert between local codepage and UCS-2 */
22629 ** Helper function to initialize the conversion objects from and to UTF-8.
22631 static void initUconvObjects( void ){
22632 if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
22633 ucUtf8 = NULL;
22634 if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
22635 uclCp = NULL;
22639 ** Helper function to free the conversion objects from and to UTF-8.
22641 static void freeUconvObjects( void ){
22642 if ( ucUtf8 )
22643 UniFreeUconvObject( ucUtf8 );
22644 if ( uclCp )
22645 UniFreeUconvObject( uclCp );
22646 ucUtf8 = NULL;
22647 uclCp = NULL;
22651 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
22652 ** The two-step process: first convert the incoming UTF-8 string
22653 ** into UCS-2 and then from UCS-2 to the current codepage.
22654 ** The returned char pointer has to be freed.
22656 static char *convertUtf8PathToCp( const char *in ){
22657 UniChar tempPath[CCHMAXPATH];
22658 char *out = (char *)calloc( CCHMAXPATH, 1 );
22660 if( !out )
22661 return NULL;
22663 if( !ucUtf8 || !uclCp )
22664 initUconvObjects();
22666 /* determine string for the conversion of UTF-8 which is CP1208 */
22667 if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22668 return out; /* if conversion fails, return the empty string */
22670 /* conversion for current codepage which can be used for paths */
22671 UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
22673 return out;
22677 ** Helper function to convert filenames from local codepage to UTF-8.
22678 ** The two-step process: first convert the incoming codepage-specific
22679 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
22680 ** The returned char pointer has to be freed.
22682 ** This function is non-static to be able to use this in shell.c and
22683 ** similar applications that take command line arguments.
22685 char *convertCpPathToUtf8( const char *in ){
22686 UniChar tempPath[CCHMAXPATH];
22687 char *out = (char *)calloc( CCHMAXPATH, 1 );
22689 if( !out )
22690 return NULL;
22692 if( !ucUtf8 || !uclCp )
22693 initUconvObjects();
22695 /* conversion for current codepage which can be used for paths */
22696 if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22697 return out; /* if conversion fails, return the empty string */
22699 /* determine string for the conversion of UTF-8 which is CP1208 */
22700 UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
22702 return out;
22706 #ifndef SQLITE_OMIT_WAL
22709 ** Use main database file for interprocess locking. If un-defined
22710 ** a separate file is created for this purpose. The file will be
22711 ** used only to set file locks. There will be no data written to it.
22713 #define SQLITE_OS2_NO_WAL_LOCK_FILE
22715 #if 0
22716 static void _ERR_TRACE( const char *fmt, ... ) {
22717 va_list ap;
22718 va_start(ap, fmt);
22719 vfprintf(stderr, fmt, ap);
22720 fflush(stderr);
22722 #define ERR_TRACE(rc, msg) \
22723 if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
22724 #else
22725 #define ERR_TRACE(rc, msg)
22726 #endif
22729 ** Helper functions to obtain and relinquish the global mutex. The
22730 ** global mutex is used to protect os2ShmNodeList.
22732 ** Function os2ShmMutexHeld() is used to assert() that the global mutex
22733 ** is held when required. This function is only used as part of assert()
22734 ** statements. e.g.
22736 ** os2ShmEnterMutex()
22737 ** assert( os2ShmMutexHeld() );
22738 ** os2ShmLeaveMutex()
22740 static void os2ShmEnterMutex(void){
22741 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22743 static void os2ShmLeaveMutex(void){
22744 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22746 #ifdef SQLITE_DEBUG
22747 static int os2ShmMutexHeld(void) {
22748 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22750 int GetCurrentProcessId(void) {
22751 PPIB pib;
22752 DosGetInfoBlocks(NULL, &pib);
22753 return (int)pib->pib_ulpid;
22755 #endif
22758 ** Object used to represent a the shared memory area for a single log file.
22759 ** When multiple threads all reference the same log-summary, each thread has
22760 ** its own os2File object, but they all point to a single instance of this
22761 ** object. In other words, each log-summary is opened only once per process.
22763 ** os2ShmMutexHeld() must be true when creating or destroying
22764 ** this object or while reading or writing the following fields:
22766 ** nRef
22767 ** pNext
22769 ** The following fields are read-only after the object is created:
22771 ** szRegion
22772 ** hLockFile
22773 ** shmBaseName
22775 ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
22776 ** os2ShmMutexHeld() is true when reading or writing any other field
22777 ** in this structure.
22780 struct os2ShmNode {
22781 sqlite3_mutex *mutex; /* Mutex to access this object */
22782 os2ShmNode *pNext; /* Next in list of all os2ShmNode objects */
22784 int szRegion; /* Size of shared-memory regions */
22786 int nRegion; /* Size of array apRegion */
22787 void **apRegion; /* Array of pointers to shared-memory regions */
22789 int nRef; /* Number of os2ShmLink objects pointing to this */
22790 os2ShmLink *pFirst; /* First os2ShmLink object pointing to this */
22792 HFILE hLockFile; /* File used for inter-process memory locking */
22793 char shmBaseName[1]; /* Name of the memory object !!! must last !!! */
22798 ** Structure used internally by this VFS to record the state of an
22799 ** open shared memory connection.
22801 ** The following fields are initialized when this object is created and
22802 ** are read-only thereafter:
22804 ** os2Shm.pShmNode
22805 ** os2Shm.id
22807 ** All other fields are read/write. The os2Shm.pShmNode->mutex must be held
22808 ** while accessing any read/write fields.
22810 struct os2ShmLink {
22811 os2ShmNode *pShmNode; /* The underlying os2ShmNode object */
22812 os2ShmLink *pNext; /* Next os2Shm with the same os2ShmNode */
22813 u32 sharedMask; /* Mask of shared locks held */
22814 u32 exclMask; /* Mask of exclusive locks held */
22815 #ifdef SQLITE_DEBUG
22816 u8 id; /* Id of this connection with its os2ShmNode */
22817 #endif
22822 ** A global list of all os2ShmNode objects.
22824 ** The os2ShmMutexHeld() must be true while reading or writing this list.
22826 static os2ShmNode *os2ShmNodeList = NULL;
22829 ** Constants used for locking
22831 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
22832 #define OS2_SHM_BASE (PENDING_BYTE + 0x10000) /* first lock byte */
22833 #else
22834 #define OS2_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
22835 #endif
22837 #define OS2_SHM_DMS (OS2_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
22840 ** Apply advisory locks for all n bytes beginning at ofst.
22842 #define _SHM_UNLCK 1 /* no lock */
22843 #define _SHM_RDLCK 2 /* shared lock, no wait */
22844 #define _SHM_WRLCK 3 /* exlusive lock, no wait */
22845 #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
22846 static int os2ShmSystemLock(
22847 os2ShmNode *pNode, /* Apply locks to this open shared-memory segment */
22848 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
22849 int ofst, /* Offset to first byte to be locked/unlocked */
22850 int nByte /* Number of bytes to lock or unlock */
22852 APIRET rc;
22853 FILELOCK area;
22854 ULONG mode, timeout;
22856 /* Access to the os2ShmNode object is serialized by the caller */
22857 assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
22859 mode = 1; /* shared lock */
22860 timeout = 0; /* no wait */
22861 area.lOffset = ofst;
22862 area.lRange = nByte;
22864 switch( lockType ) {
22865 case _SHM_WRLCK_WAIT:
22866 timeout = (ULONG)-1; /* wait forever */
22867 case _SHM_WRLCK:
22868 mode = 0; /* exclusive lock */
22869 case _SHM_RDLCK:
22870 rc = DosSetFileLocks(pNode->hLockFile,
22871 NULL, &area, timeout, mode);
22872 break;
22873 /* case _SHM_UNLCK: */
22874 default:
22875 rc = DosSetFileLocks(pNode->hLockFile,
22876 &area, NULL, 0, 0);
22877 break;
22880 OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
22881 pNode->hLockFile,
22882 rc==SQLITE_OK ? "ok" : "failed",
22883 lockType==_SHM_UNLCK ? "Unlock" : "Lock",
22884 rc));
22886 ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
22888 return ( rc == 0 ) ? SQLITE_OK : SQLITE_BUSY;
22892 ** Find an os2ShmNode in global list or allocate a new one, if not found.
22894 ** This is not a VFS shared-memory method; it is a utility function called
22895 ** by VFS shared-memory methods.
22897 static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
22898 os2ShmLink *pLink;
22899 os2ShmNode *pNode;
22900 int cbShmName, rc = SQLITE_OK;
22901 char shmName[CCHMAXPATH + 30];
22902 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
22903 ULONG action;
22904 #endif
22906 /* We need some additional space at the end to append the region number */
22907 cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
22908 if( cbShmName >= CCHMAXPATH-8 )
22909 return SQLITE_IOERR_SHMOPEN;
22911 /* Replace colon in file name to form a valid shared memory name */
22912 shmName[10+1] = '!';
22914 /* Allocate link object (we free it later in case of failure) */
22915 pLink = sqlite3_malloc( sizeof(*pLink) );
22916 if( !pLink )
22917 return SQLITE_NOMEM;
22919 /* Access node list */
22920 os2ShmEnterMutex();
22922 /* Find node by it's shared memory base name */
22923 for( pNode = os2ShmNodeList;
22924 pNode && stricmp(shmName, pNode->shmBaseName) != 0;
22925 pNode = pNode->pNext ) ;
22927 /* Not found: allocate a new node */
22928 if( !pNode ) {
22929 pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
22930 if( pNode ) {
22931 memset(pNode, 0, sizeof(*pNode) );
22932 pNode->szRegion = szRegion;
22933 pNode->hLockFile = (HFILE)-1;
22934 strcpy(pNode->shmBaseName, shmName);
22936 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
22937 if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
22938 #else
22939 sprintf(shmName, "%s-lck", fd->zFullPathCp);
22940 if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL,
22941 OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
22942 OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE |
22943 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
22944 NULL) != 0 ) {
22945 #endif
22946 sqlite3_free(pNode);
22947 rc = SQLITE_IOERR;
22948 } else {
22949 pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
22950 if( !pNode->mutex ) {
22951 sqlite3_free(pNode);
22952 rc = SQLITE_NOMEM;
22955 } else {
22956 rc = SQLITE_NOMEM;
22959 if( rc == SQLITE_OK ) {
22960 pNode->pNext = os2ShmNodeList;
22961 os2ShmNodeList = pNode;
22962 } else {
22963 pNode = NULL;
22965 } else if( pNode->szRegion != szRegion ) {
22966 rc = SQLITE_IOERR_SHMSIZE;
22967 pNode = NULL;
22970 if( pNode ) {
22971 sqlite3_mutex_enter(pNode->mutex);
22973 memset(pLink, 0, sizeof(*pLink));
22975 pLink->pShmNode = pNode;
22976 pLink->pNext = pNode->pFirst;
22977 pNode->pFirst = pLink;
22978 pNode->nRef++;
22980 fd->pShmLink = pLink;
22982 sqlite3_mutex_leave(pNode->mutex);
22984 } else {
22985 /* Error occured. Free our link object. */
22986 sqlite3_free(pLink);
22989 os2ShmLeaveMutex();
22991 ERR_TRACE(rc, ("os2OpenSharedMemory: %d %s\n", rc, fd->zFullPathCp))
22993 return rc;
22997 ** Purge the os2ShmNodeList list of all entries with nRef==0.
22999 ** This is not a VFS shared-memory method; it is a utility function called
23000 ** by VFS shared-memory methods.
23002 static void os2PurgeShmNodes( int deleteFlag ) {
23003 os2ShmNode *pNode;
23004 os2ShmNode **ppNode;
23006 os2ShmEnterMutex();
23008 ppNode = &os2ShmNodeList;
23010 while( *ppNode ) {
23011 pNode = *ppNode;
23013 if( pNode->nRef == 0 ) {
23014 *ppNode = pNode->pNext;
23016 if( pNode->apRegion ) {
23017 /* Prevent other processes from resizing the shared memory */
23018 os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23020 while( pNode->nRegion-- ) {
23021 #ifdef SQLITE_DEBUG
23022 int rc =
23023 #endif
23024 DosFreeMem(pNode->apRegion[pNode->nRegion]);
23026 OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
23027 (int)GetCurrentProcessId(), pNode->nRegion,
23028 rc == 0 ? "ok" : "failed"));
23031 /* Allow other processes to resize the shared memory */
23032 os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23034 sqlite3_free(pNode->apRegion);
23037 DosClose(pNode->hLockFile);
23039 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23040 if( deleteFlag ) {
23041 char fileName[CCHMAXPATH];
23042 /* Skip "\\SHAREMEM\\" */
23043 sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
23044 /* restore colon */
23045 fileName[1] = ':';
23047 DosForceDelete(fileName);
23049 #endif
23051 sqlite3_mutex_free(pNode->mutex);
23053 sqlite3_free(pNode);
23055 } else {
23056 ppNode = &pNode->pNext;
23060 os2ShmLeaveMutex();
23064 ** This function is called to obtain a pointer to region iRegion of the
23065 ** shared-memory associated with the database file id. Shared-memory regions
23066 ** are numbered starting from zero. Each shared-memory region is szRegion
23067 ** bytes in size.
23069 ** If an error occurs, an error code is returned and *pp is set to NULL.
23071 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
23072 ** region has not been allocated (by any client, including one running in a
23073 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
23074 ** bExtend is non-zero and the requested shared-memory region has not yet
23075 ** been allocated, it is allocated by this function.
23077 ** If the shared-memory region has already been allocated or is allocated by
23078 ** this call as described above, then it is mapped into this processes
23079 ** address space (if it is not already), *pp is set to point to the mapped
23080 ** memory and SQLITE_OK returned.
23082 static int os2ShmMap(
23083 sqlite3_file *id, /* Handle open on database file */
23084 int iRegion, /* Region to retrieve */
23085 int szRegion, /* Size of regions */
23086 int bExtend, /* True to extend block if necessary */
23087 void volatile **pp /* OUT: Mapped memory */
23089 PVOID pvTemp;
23090 void **apRegion;
23091 os2ShmNode *pNode;
23092 int n, rc = SQLITE_OK;
23093 char shmName[CCHMAXPATH];
23094 os2File *pFile = (os2File*)id;
23096 *pp = NULL;
23098 if( !pFile->pShmLink )
23099 rc = os2OpenSharedMemory( pFile, szRegion );
23101 if( rc == SQLITE_OK ) {
23102 pNode = pFile->pShmLink->pShmNode ;
23104 sqlite3_mutex_enter(pNode->mutex);
23106 assert( szRegion==pNode->szRegion );
23108 /* Unmapped region ? */
23109 if( iRegion >= pNode->nRegion ) {
23110 /* Prevent other processes from resizing the shared memory */
23111 os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23113 apRegion = sqlite3_realloc(
23114 pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
23116 if( apRegion ) {
23117 pNode->apRegion = apRegion;
23119 while( pNode->nRegion <= iRegion ) {
23120 sprintf(shmName, "%s-%u",
23121 pNode->shmBaseName, pNode->nRegion);
23123 if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName,
23124 PAG_READ | PAG_WRITE) != NO_ERROR ) {
23125 if( !bExtend )
23126 break;
23128 if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23129 PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR &&
23130 DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23131 PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) {
23132 rc = SQLITE_NOMEM;
23133 break;
23137 apRegion[pNode->nRegion++] = pvTemp;
23140 /* zero out remaining entries */
23141 for( n = pNode->nRegion; n <= iRegion; n++ )
23142 pNode->apRegion[n] = NULL;
23144 /* Return this region (maybe zero) */
23145 *pp = pNode->apRegion[iRegion];
23146 } else {
23147 rc = SQLITE_NOMEM;
23150 /* Allow other processes to resize the shared memory */
23151 os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23153 } else {
23154 /* Region has been mapped previously */
23155 *pp = pNode->apRegion[iRegion];
23158 sqlite3_mutex_leave(pNode->mutex);
23161 ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n",
23162 pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
23164 return rc;
23168 ** Close a connection to shared-memory. Delete the underlying
23169 ** storage if deleteFlag is true.
23171 ** If there is no shared memory associated with the connection then this
23172 ** routine is a harmless no-op.
23174 static int os2ShmUnmap(
23175 sqlite3_file *id, /* The underlying database file */
23176 int deleteFlag /* Delete shared-memory if true */
23178 os2File *pFile = (os2File*)id;
23179 os2ShmLink *pLink = pFile->pShmLink;
23181 if( pLink ) {
23182 int nRef = -1;
23183 os2ShmLink **ppLink;
23184 os2ShmNode *pNode = pLink->pShmNode;
23186 sqlite3_mutex_enter(pNode->mutex);
23188 for( ppLink = &pNode->pFirst;
23189 *ppLink && *ppLink != pLink;
23190 ppLink = &(*ppLink)->pNext ) ;
23192 assert(*ppLink);
23194 if( *ppLink ) {
23195 *ppLink = pLink->pNext;
23196 nRef = --pNode->nRef;
23197 } else {
23198 ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n",
23199 pNode->shmBaseName))
23202 pFile->pShmLink = NULL;
23203 sqlite3_free(pLink);
23205 sqlite3_mutex_leave(pNode->mutex);
23207 if( nRef == 0 )
23208 os2PurgeShmNodes( deleteFlag );
23211 return SQLITE_OK;
23215 ** Change the lock state for a shared-memory segment.
23217 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
23218 ** different here than in posix. In xShmLock(), one can go from unlocked
23219 ** to shared and back or from unlocked to exclusive and back. But one may
23220 ** not go from shared to exclusive or from exclusive to shared.
23222 static int os2ShmLock(
23223 sqlite3_file *id, /* Database file holding the shared memory */
23224 int ofst, /* First lock to acquire or release */
23225 int n, /* Number of locks to acquire or release */
23226 int flags /* What to do with the lock */
23228 u32 mask; /* Mask of locks to take or release */
23229 int rc = SQLITE_OK; /* Result code */
23230 os2File *pFile = (os2File*)id;
23231 os2ShmLink *p = pFile->pShmLink; /* The shared memory being locked */
23232 os2ShmLink *pX; /* For looping over all siblings */
23233 os2ShmNode *pShmNode = p->pShmNode; /* Our node */
23235 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
23236 assert( n>=1 );
23237 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
23238 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
23239 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
23240 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
23241 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
23243 mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
23244 assert( n>1 || mask==(1<<ofst) );
23247 sqlite3_mutex_enter(pShmNode->mutex);
23249 if( flags & SQLITE_SHM_UNLOCK ){
23250 u32 allMask = 0; /* Mask of locks held by siblings */
23252 /* See if any siblings hold this same lock */
23253 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23254 if( pX==p ) continue;
23255 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
23256 allMask |= pX->sharedMask;
23259 /* Unlock the system-level locks */
23260 if( (mask & allMask)==0 ){
23261 rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
23262 }else{
23263 rc = SQLITE_OK;
23266 /* Undo the local locks */
23267 if( rc==SQLITE_OK ){
23268 p->exclMask &= ~mask;
23269 p->sharedMask &= ~mask;
23271 }else if( flags & SQLITE_SHM_SHARED ){
23272 u32 allShared = 0; /* Union of locks held by connections other than "p" */
23274 /* Find out which shared locks are already held by sibling connections.
23275 ** If any sibling already holds an exclusive lock, go ahead and return
23276 ** SQLITE_BUSY.
23278 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23279 if( (pX->exclMask & mask)!=0 ){
23280 rc = SQLITE_BUSY;
23281 break;
23283 allShared |= pX->sharedMask;
23286 /* Get shared locks at the system level, if necessary */
23287 if( rc==SQLITE_OK ){
23288 if( (allShared & mask)==0 ){
23289 rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
23290 }else{
23291 rc = SQLITE_OK;
23295 /* Get the local shared locks */
23296 if( rc==SQLITE_OK ){
23297 p->sharedMask |= mask;
23299 }else{
23300 /* Make sure no sibling connections hold locks that will block this
23301 ** lock. If any do, return SQLITE_BUSY right away.
23303 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23304 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
23305 rc = SQLITE_BUSY;
23306 break;
23310 /* Get the exclusive locks at the system level. Then if successful
23311 ** also mark the local connection as being locked.
23313 if( rc==SQLITE_OK ){
23314 rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
23315 if( rc==SQLITE_OK ){
23316 assert( (p->sharedMask & mask)==0 );
23317 p->exclMask |= mask;
23322 sqlite3_mutex_leave(pShmNode->mutex);
23324 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
23325 p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
23326 rc ? "failed" : "ok"));
23328 ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n",
23329 ofst, n, flags, rc))
23331 return rc;
23335 ** Implement a memory barrier or memory fence on shared memory.
23337 ** All loads and stores begun before the barrier must complete before
23338 ** any load or store begun after the barrier.
23340 static void os2ShmBarrier(
23341 sqlite3_file *id /* Database file holding the shared memory */
23343 UNUSED_PARAMETER(id);
23344 os2ShmEnterMutex();
23345 os2ShmLeaveMutex();
23348 #else
23349 # define os2ShmMap 0
23350 # define os2ShmLock 0
23351 # define os2ShmBarrier 0
23352 # define os2ShmUnmap 0
23353 #endif /* #ifndef SQLITE_OMIT_WAL */
23357 ** This vector defines all the methods that can operate on an
23358 ** sqlite3_file for os2.
23360 static const sqlite3_io_methods os2IoMethod = {
23361 2, /* iVersion */
23362 os2Close, /* xClose */
23363 os2Read, /* xRead */
23364 os2Write, /* xWrite */
23365 os2Truncate, /* xTruncate */
23366 os2Sync, /* xSync */
23367 os2FileSize, /* xFileSize */
23368 os2Lock, /* xLock */
23369 os2Unlock, /* xUnlock */
23370 os2CheckReservedLock, /* xCheckReservedLock */
23371 os2FileControl, /* xFileControl */
23372 os2SectorSize, /* xSectorSize */
23373 os2DeviceCharacteristics, /* xDeviceCharacteristics */
23374 os2ShmMap, /* xShmMap */
23375 os2ShmLock, /* xShmLock */
23376 os2ShmBarrier, /* xShmBarrier */
23377 os2ShmUnmap /* xShmUnmap */
23381 /***************************************************************************
23382 ** Here ends the I/O methods that form the sqlite3_io_methods object.
23384 ** The next block of code implements the VFS methods.
23385 ****************************************************************************/
23388 ** Create a temporary file name in zBuf. zBuf must be big enough to
23389 ** hold at pVfs->mxPathname characters.
23391 static int getTempname(int nBuf, char *zBuf ){
23392 static const char zChars[] =
23393 "abcdefghijklmnopqrstuvwxyz"
23394 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23395 "0123456789";
23396 int i, j;
23397 PSZ zTempPathCp;
23398 char zTempPath[CCHMAXPATH];
23399 ULONG ulDriveNum, ulDriveMap;
23401 /* It's odd to simulate an io-error here, but really this is just
23402 ** using the io-error infrastructure to test that SQLite handles this
23403 ** function failing.
23405 SimulateIOError( return SQLITE_IOERR );
23407 if( sqlite3_temp_directory ) {
23408 sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
23409 } else if( DosScanEnv( (PSZ)"TEMP", &zTempPathCp ) == NO_ERROR ||
23410 DosScanEnv( (PSZ)"TMP", &zTempPathCp ) == NO_ERROR ||
23411 DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
23412 char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
23413 sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
23414 free( zTempPathUTF );
23415 } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
23416 zTempPath[0] = (char)('A' + ulDriveNum - 1);
23417 zTempPath[1] = ':';
23418 zTempPath[2] = '\0';
23419 } else {
23420 zTempPath[0] = '\0';
23423 /* Strip off a trailing slashes or backslashes, otherwise we would get *
23424 * multiple (back)slashes which causes DosOpen() to fail. *
23425 * Trailing spaces are not allowed, either. */
23426 j = sqlite3Strlen30(zTempPath);
23427 while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ||
23428 zTempPath[j-1] == ' ' ) ){
23429 j--;
23431 zTempPath[j] = '\0';
23433 /* We use 20 bytes to randomize the name */
23434 sqlite3_snprintf(nBuf-22, zBuf,
23435 "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
23436 j = sqlite3Strlen30(zBuf);
23437 sqlite3_randomness( 20, &zBuf[j] );
23438 for( i = 0; i < 20; i++, j++ ){
23439 zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
23441 zBuf[j] = 0;
23443 OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
23444 return SQLITE_OK;
23449 ** Turn a relative pathname into a full pathname. Write the full
23450 ** pathname into zFull[]. zFull[] will be at least pVfs->mxPathname
23451 ** bytes in size.
23453 static int os2FullPathname(
23454 sqlite3_vfs *pVfs, /* Pointer to vfs object */
23455 const char *zRelative, /* Possibly relative input path */
23456 int nFull, /* Size of output buffer in bytes */
23457 char *zFull /* Output buffer */
23459 char *zRelativeCp = convertUtf8PathToCp( zRelative );
23460 char zFullCp[CCHMAXPATH] = "\0";
23461 char *zFullUTF;
23462 APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME,
23463 zFullCp, CCHMAXPATH );
23464 free( zRelativeCp );
23465 zFullUTF = convertCpPathToUtf8( zFullCp );
23466 sqlite3_snprintf( nFull, zFull, zFullUTF );
23467 free( zFullUTF );
23468 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23473 ** Open a file.
23475 static int os2Open(
23476 sqlite3_vfs *pVfs, /* Not used */
23477 const char *zName, /* Name of the file (UTF-8) */
23478 sqlite3_file *id, /* Write the SQLite file handle here */
23479 int flags, /* Open mode flags */
23480 int *pOutFlags /* Status return flags */
23482 HFILE h;
23483 ULONG ulOpenFlags = 0;
23484 ULONG ulOpenMode = 0;
23485 ULONG ulAction = 0;
23486 ULONG rc;
23487 os2File *pFile = (os2File*)id;
23488 const char *zUtf8Name = zName;
23489 char *zNameCp;
23490 char zTmpname[CCHMAXPATH];
23492 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
23493 int isCreate = (flags & SQLITE_OPEN_CREATE);
23494 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
23495 #ifndef NDEBUG
23496 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
23497 int isReadonly = (flags & SQLITE_OPEN_READONLY);
23498 int eType = (flags & 0xFFFFFF00);
23499 int isOpenJournal = (isCreate && (
23500 eType==SQLITE_OPEN_MASTER_JOURNAL
23501 || eType==SQLITE_OPEN_MAIN_JOURNAL
23502 || eType==SQLITE_OPEN_WAL
23504 #endif
23506 UNUSED_PARAMETER(pVfs);
23507 assert( id!=0 );
23509 /* Check the following statements are true:
23511 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
23512 ** (b) if CREATE is set, then READWRITE must also be set, and
23513 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
23514 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
23516 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
23517 assert(isCreate==0 || isReadWrite);
23518 assert(isExclusive==0 || isCreate);
23519 assert(isDelete==0 || isCreate);
23521 /* The main DB, main journal, WAL file and master journal are never
23522 ** automatically deleted. Nor are they ever temporary files. */
23523 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
23524 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
23525 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
23526 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
23528 /* Assert that the upper layer has set one of the "file-type" flags. */
23529 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
23530 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
23531 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
23532 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
23535 memset( pFile, 0, sizeof(*pFile) );
23536 pFile->h = (HFILE)-1;
23538 /* If the second argument to this function is NULL, generate a
23539 ** temporary file name to use
23541 if( !zUtf8Name ){
23542 assert(isDelete && !isOpenJournal);
23543 rc = getTempname(CCHMAXPATH, zTmpname);
23544 if( rc!=SQLITE_OK ){
23545 return rc;
23547 zUtf8Name = zTmpname;
23550 if( isReadWrite ){
23551 ulOpenMode |= OPEN_ACCESS_READWRITE;
23552 }else{
23553 ulOpenMode |= OPEN_ACCESS_READONLY;
23556 /* Open in random access mode for possibly better speed. Allow full
23557 ** sharing because file locks will provide exclusive access when needed.
23558 ** The handle should not be inherited by child processes and we don't
23559 ** want popups from the critical error handler.
23561 ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE |
23562 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
23564 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
23565 ** created. SQLite doesn't use it to indicate "exclusive access"
23566 ** as it is usually understood.
23568 if( isExclusive ){
23569 /* Creates a new file, only if it does not already exist. */
23570 /* If the file exists, it fails. */
23571 ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
23572 }else if( isCreate ){
23573 /* Open existing file, or create if it doesn't exist */
23574 ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23575 }else{
23576 /* Opens a file, only if it exists. */
23577 ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23580 zNameCp = convertUtf8PathToCp( zUtf8Name );
23581 rc = DosOpen( (PSZ)zNameCp,
23583 &ulAction,
23585 FILE_NORMAL,
23586 ulOpenFlags,
23587 ulOpenMode,
23588 (PEAOP2)NULL );
23589 free( zNameCp );
23591 if( rc != NO_ERROR ){
23592 OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
23593 rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
23595 if( isReadWrite ){
23596 return os2Open( pVfs, zName, id,
23597 ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
23598 pOutFlags );
23599 }else{
23600 return SQLITE_CANTOPEN;
23604 if( pOutFlags ){
23605 *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
23608 os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
23609 pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
23610 pFile->pMethod = &os2IoMethod;
23611 pFile->flags = flags;
23612 pFile->h = h;
23614 OpenCounter(+1);
23615 OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
23616 return SQLITE_OK;
23620 ** Delete the named file.
23622 static int os2Delete(
23623 sqlite3_vfs *pVfs, /* Not used on os2 */
23624 const char *zFilename, /* Name of file to delete */
23625 int syncDir /* Not used on os2 */
23627 APIRET rc;
23628 char *zFilenameCp;
23629 SimulateIOError( return SQLITE_IOERR_DELETE );
23630 zFilenameCp = convertUtf8PathToCp( zFilename );
23631 rc = DosDelete( (PSZ)zFilenameCp );
23632 free( zFilenameCp );
23633 OSTRACE(( "DELETE \"%s\"\n", zFilename ));
23634 return (rc == NO_ERROR ||
23635 rc == ERROR_FILE_NOT_FOUND ||
23636 rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
23640 ** Check the existance and status of a file.
23642 static int os2Access(
23643 sqlite3_vfs *pVfs, /* Not used on os2 */
23644 const char *zFilename, /* Name of file to check */
23645 int flags, /* Type of test to make on this file */
23646 int *pOut /* Write results here */
23648 APIRET rc;
23649 FILESTATUS3 fsts3ConfigInfo;
23650 char *zFilenameCp;
23652 UNUSED_PARAMETER(pVfs);
23653 SimulateIOError( return SQLITE_IOERR_ACCESS; );
23655 zFilenameCp = convertUtf8PathToCp( zFilename );
23656 rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
23657 &fsts3ConfigInfo, sizeof(FILESTATUS3) );
23658 free( zFilenameCp );
23659 OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
23660 fsts3ConfigInfo.attrFile, flags, rc ));
23662 switch( flags ){
23663 case SQLITE_ACCESS_EXISTS:
23664 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
23665 ** as if it does not exist.
23667 if( fsts3ConfigInfo.cbFile == 0 )
23668 rc = ERROR_FILE_NOT_FOUND;
23669 break;
23670 case SQLITE_ACCESS_READ:
23671 break;
23672 case SQLITE_ACCESS_READWRITE:
23673 if( fsts3ConfigInfo.attrFile & FILE_READONLY )
23674 rc = ERROR_ACCESS_DENIED;
23675 break;
23676 default:
23677 rc = ERROR_FILE_NOT_FOUND;
23678 assert( !"Invalid flags argument" );
23681 *pOut = (rc == NO_ERROR);
23682 OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
23684 return SQLITE_OK;
23688 #ifndef SQLITE_OMIT_LOAD_EXTENSION
23690 ** Interfaces for opening a shared library, finding entry points
23691 ** within the shared library, and closing the shared library.
23694 ** Interfaces for opening a shared library, finding entry points
23695 ** within the shared library, and closing the shared library.
23697 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
23698 HMODULE hmod;
23699 APIRET rc;
23700 char *zFilenameCp = convertUtf8PathToCp(zFilename);
23701 rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
23702 free(zFilenameCp);
23703 return rc != NO_ERROR ? 0 : (void*)hmod;
23706 ** A no-op since the error code is returned on the DosLoadModule call.
23707 ** os2Dlopen returns zero if DosLoadModule is not successful.
23709 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
23710 /* no-op */
23712 static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
23713 PFN pfn;
23714 APIRET rc;
23715 rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
23716 if( rc != NO_ERROR ){
23717 /* if the symbol itself was not found, search again for the same
23718 * symbol with an extra underscore, that might be needed depending
23719 * on the calling convention */
23720 char _zSymbol[256] = "_";
23721 strncat(_zSymbol, zSymbol, 254);
23722 rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
23724 return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
23726 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
23727 DosFreeModule((HMODULE)pHandle);
23729 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
23730 #define os2DlOpen 0
23731 #define os2DlError 0
23732 #define os2DlSym 0
23733 #define os2DlClose 0
23734 #endif
23738 ** Write up to nBuf bytes of randomness into zBuf.
23740 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
23741 int n = 0;
23742 #if defined(SQLITE_TEST)
23743 n = nBuf;
23744 memset(zBuf, 0, nBuf);
23745 #else
23746 int i;
23747 PPIB ppib;
23748 PTIB ptib;
23749 DATETIME dt;
23750 static unsigned c = 0;
23751 /* Ordered by variation probability */
23752 static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
23753 QSV_MAXPRMEM, QSV_MAXSHMEM,
23754 QSV_TOTAVAILMEM, QSV_TOTRESMEM };
23756 /* 8 bytes; timezone and weekday don't increase the randomness much */
23757 if( (int)sizeof(dt)-3 <= nBuf - n ){
23758 c += 0x0100;
23759 DosGetDateTime(&dt);
23760 dt.year = (USHORT)((dt.year - 1900) | c);
23761 memcpy(&zBuf[n], &dt, sizeof(dt)-3);
23762 n += sizeof(dt)-3;
23765 /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
23766 if( (int)sizeof(ULONG) <= nBuf - n ){
23767 DosGetInfoBlocks(&ptib, &ppib);
23768 *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
23769 ptib->tib_ptib2->tib2_ultid);
23770 n += sizeof(ULONG);
23773 /* Up to 6 * 4 bytes; variables depend on the system state */
23774 for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
23775 DosQuerySysInfo(svIdx[i], svIdx[i],
23776 (PULONG)&zBuf[n], sizeof(ULONG));
23777 n += sizeof(ULONG);
23779 #endif
23781 return n;
23785 ** Sleep for a little while. Return the amount of time slept.
23786 ** The argument is the number of microseconds we want to sleep.
23787 ** The return value is the number of microseconds of sleep actually
23788 ** requested from the underlying operating system, a number which
23789 ** might be greater than or equal to the argument, but not less
23790 ** than the argument.
23792 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
23793 DosSleep( (microsec/1000) );
23794 return microsec;
23798 ** The following variable, if set to a non-zero value, becomes the result
23799 ** returned from sqlite3OsCurrentTime(). This is used for testing.
23801 #ifdef SQLITE_TEST
23802 SQLITE_API int sqlite3_current_time = 0;
23803 #endif
23806 ** Find the current time (in Universal Coordinated Time). Write into *piNow
23807 ** the current time and date as a Julian Day number times 86_400_000. In
23808 ** other words, write into *piNow the number of milliseconds since the Julian
23809 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
23810 ** proleptic Gregorian calendar.
23812 ** On success, return 0. Return 1 if the time and date cannot be found.
23814 static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
23815 #ifdef SQLITE_TEST
23816 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
23817 #endif
23818 int year, month, datepart, timepart;
23820 DATETIME dt;
23821 DosGetDateTime( &dt );
23823 year = dt.year;
23824 month = dt.month;
23826 /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
23827 ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
23828 ** Calculate the Julian days
23830 datepart = (int)dt.day - 32076 +
23831 1461*(year + 4800 + (month - 14)/12)/4 +
23832 367*(month - 2 - (month - 14)/12*12)/12 -
23833 3*((year + 4900 + (month - 14)/12)/100)/4;
23835 /* Time in milliseconds, hours to noon added */
23836 timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
23837 ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
23839 *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
23841 #ifdef SQLITE_TEST
23842 if( sqlite3_current_time ){
23843 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
23845 #endif
23847 UNUSED_PARAMETER(pVfs);
23848 return 0;
23852 ** Find the current time (in Universal Coordinated Time). Write the
23853 ** current time and date as a Julian Day number into *prNow and
23854 ** return 0. Return 1 if the time and date cannot be found.
23856 static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
23857 int rc;
23858 sqlite3_int64 i;
23859 rc = os2CurrentTimeInt64(pVfs, &i);
23860 if( !rc ){
23861 *prNow = i/86400000.0;
23863 return rc;
23867 ** The idea is that this function works like a combination of
23868 ** GetLastError() and FormatMessage() on windows (or errno and
23869 ** strerror_r() on unix). After an error is returned by an OS
23870 ** function, SQLite calls this function with zBuf pointing to
23871 ** a buffer of nBuf bytes. The OS layer should populate the
23872 ** buffer with a nul-terminated UTF-8 encoded error message
23873 ** describing the last IO error to have occurred within the calling
23874 ** thread.
23876 ** If the error message is too large for the supplied buffer,
23877 ** it should be truncated. The return value of xGetLastError
23878 ** is zero if the error message fits in the buffer, or non-zero
23879 ** otherwise (if the message was truncated). If non-zero is returned,
23880 ** then it is not necessary to include the nul-terminator character
23881 ** in the output buffer.
23883 ** Not supplying an error message will have no adverse effect
23884 ** on SQLite. It is fine to have an implementation that never
23885 ** returns an error message:
23887 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23888 ** assert(zBuf[0]=='\0');
23889 ** return 0;
23890 ** }
23892 ** However if an error message is supplied, it will be incorporated
23893 ** by sqlite into the error message available to the user using
23894 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
23896 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23897 assert(zBuf[0]=='\0');
23898 return 0;
23902 ** Initialize and deinitialize the operating system interface.
23904 SQLITE_API int sqlite3_os_init(void){
23905 static sqlite3_vfs os2Vfs = {
23906 3, /* iVersion */
23907 sizeof(os2File), /* szOsFile */
23908 CCHMAXPATH, /* mxPathname */
23909 0, /* pNext */
23910 "os2", /* zName */
23911 0, /* pAppData */
23913 os2Open, /* xOpen */
23914 os2Delete, /* xDelete */
23915 os2Access, /* xAccess */
23916 os2FullPathname, /* xFullPathname */
23917 os2DlOpen, /* xDlOpen */
23918 os2DlError, /* xDlError */
23919 os2DlSym, /* xDlSym */
23920 os2DlClose, /* xDlClose */
23921 os2Randomness, /* xRandomness */
23922 os2Sleep, /* xSleep */
23923 os2CurrentTime, /* xCurrentTime */
23924 os2GetLastError, /* xGetLastError */
23925 os2CurrentTimeInt64, /* xCurrentTimeInt64 */
23926 0, /* xSetSystemCall */
23927 0, /* xGetSystemCall */
23928 0 /* xNextSystemCall */
23930 sqlite3_vfs_register(&os2Vfs, 1);
23931 initUconvObjects();
23932 /* sqlite3OSTrace = 1; */
23933 return SQLITE_OK;
23935 SQLITE_API int sqlite3_os_end(void){
23936 freeUconvObjects();
23937 return SQLITE_OK;
23940 #endif /* SQLITE_OS_OS2 */
23942 /************** End of os_os2.c **********************************************/
23943 /************** Begin file os_unix.c *****************************************/
23945 ** 2004 May 22
23947 ** The author disclaims copyright to this source code. In place of
23948 ** a legal notice, here is a blessing:
23950 ** May you do good and not evil.
23951 ** May you find forgiveness for yourself and forgive others.
23952 ** May you share freely, never taking more than you give.
23954 ******************************************************************************
23956 ** This file contains the VFS implementation for unix-like operating systems
23957 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
23959 ** There are actually several different VFS implementations in this file.
23960 ** The differences are in the way that file locking is done. The default
23961 ** implementation uses Posix Advisory Locks. Alternative implementations
23962 ** use flock(), dot-files, various proprietary locking schemas, or simply
23963 ** skip locking all together.
23965 ** This source file is organized into divisions where the logic for various
23966 ** subfunctions is contained within the appropriate division. PLEASE
23967 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
23968 ** in the correct division and should be clearly labeled.
23970 ** The layout of divisions is as follows:
23972 ** * General-purpose declarations and utility functions.
23973 ** * Unique file ID logic used by VxWorks.
23974 ** * Various locking primitive implementations (all except proxy locking):
23975 ** + for Posix Advisory Locks
23976 ** + for no-op locks
23977 ** + for dot-file locks
23978 ** + for flock() locking
23979 ** + for named semaphore locks (VxWorks only)
23980 ** + for AFP filesystem locks (MacOSX only)
23981 ** * sqlite3_file methods not associated with locking.
23982 ** * Definitions of sqlite3_io_methods objects for all locking
23983 ** methods plus "finder" functions for each locking method.
23984 ** * sqlite3_vfs method implementations.
23985 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
23986 ** * Definitions of sqlite3_vfs objects for all locking methods
23987 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
23989 #if SQLITE_OS_UNIX /* This file is used on unix only */
23992 ** There are various methods for file locking used for concurrency
23993 ** control:
23995 ** 1. POSIX locking (the default),
23996 ** 2. No locking,
23997 ** 3. Dot-file locking,
23998 ** 4. flock() locking,
23999 ** 5. AFP locking (OSX only),
24000 ** 6. Named POSIX semaphores (VXWorks only),
24001 ** 7. proxy locking. (OSX only)
24003 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24004 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24005 ** selection of the appropriate locking style based on the filesystem
24006 ** where the database is located.
24008 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24009 # if defined(__APPLE__)
24010 # define SQLITE_ENABLE_LOCKING_STYLE 1
24011 # else
24012 # define SQLITE_ENABLE_LOCKING_STYLE 0
24013 # endif
24014 #endif
24017 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
24018 ** vxworks, or 0 otherwise.
24020 #ifndef OS_VXWORKS
24021 # if defined(__RTP__) || defined(_WRS_KERNEL)
24022 # define OS_VXWORKS 1
24023 # else
24024 # define OS_VXWORKS 0
24025 # endif
24026 #endif
24029 ** These #defines should enable >2GB file support on Posix if the
24030 ** underlying operating system supports it. If the OS lacks
24031 ** large file support, these should be no-ops.
24033 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
24034 ** on the compiler command line. This is necessary if you are compiling
24035 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
24036 ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
24037 ** without this option, LFS is enable. But LFS does not exist in the kernel
24038 ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
24039 ** portability you should omit LFS.
24041 ** The previous paragraph was written in 2005. (This paragraph is written
24042 ** on 2008-11-28.) These days, all Linux kernels support large files, so
24043 ** you should probably leave LFS enabled. But some embedded platforms might
24044 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
24046 #ifndef SQLITE_DISABLE_LFS
24047 # define _LARGE_FILE 1
24048 # ifndef _FILE_OFFSET_BITS
24049 # define _FILE_OFFSET_BITS 64
24050 # endif
24051 # define _LARGEFILE_SOURCE 1
24052 #endif
24055 ** standard include files.
24057 #include <sys/types.h>
24058 #include <sys/stat.h>
24059 #include <fcntl.h>
24060 #include <unistd.h>
24061 #include <sys/time.h>
24062 #include <errno.h>
24063 #ifndef SQLITE_OMIT_WAL
24064 #include <sys/mman.h>
24065 #endif
24067 #if SQLITE_ENABLE_LOCKING_STYLE
24068 # include <sys/ioctl.h>
24069 # if OS_VXWORKS
24070 # include <semaphore.h>
24071 # include <limits.h>
24072 # else
24073 # include <sys/file.h>
24074 # include <sys/param.h>
24075 # endif
24076 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24078 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24079 # include <sys/mount.h>
24080 #endif
24083 ** Allowed values of unixFile.fsFlags
24085 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
24088 ** If we are to be thread-safe, include the pthreads header and define
24089 ** the SQLITE_UNIX_THREADS macro.
24091 #if SQLITE_THREADSAFE
24092 # define SQLITE_UNIX_THREADS 1
24093 #endif
24096 ** Default permissions when creating a new file
24098 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24099 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24100 #endif
24103 ** Default permissions when creating auto proxy dir
24105 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24106 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24107 #endif
24110 ** Maximum supported path-length.
24112 #define MAX_PATHNAME 512
24115 ** Only set the lastErrno if the error code is a real error and not
24116 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24118 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24120 /* Forward references */
24121 typedef struct unixShm unixShm; /* Connection shared memory */
24122 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
24123 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
24124 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
24127 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
24128 ** cannot be closed immediately. In these cases, instances of the following
24129 ** structure are used to store the file descriptor while waiting for an
24130 ** opportunity to either close or reuse it.
24132 struct UnixUnusedFd {
24133 int fd; /* File descriptor to close */
24134 int flags; /* Flags this file descriptor was opened with */
24135 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
24139 ** The unixFile structure is subclass of sqlite3_file specific to the unix
24140 ** VFS implementations.
24142 typedef struct unixFile unixFile;
24143 struct unixFile {
24144 sqlite3_io_methods const *pMethod; /* Always the first entry */
24145 unixInodeInfo *pInode; /* Info about locks on this inode */
24146 int h; /* The file descriptor */
24147 unsigned char eFileLock; /* The type of lock held on this fd */
24148 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
24149 int lastErrno; /* The unix errno from last I/O error */
24150 void *lockingContext; /* Locking style specific state */
24151 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
24152 const char *zPath; /* Name of the file */
24153 unixShm *pShm; /* Shared memory segment information */
24154 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
24155 #if SQLITE_ENABLE_LOCKING_STYLE
24156 int openFlags; /* The flags specified at open() */
24157 #endif
24158 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
24159 unsigned fsFlags; /* cached details from statfs() */
24160 #endif
24161 #if OS_VXWORKS
24162 int isDelete; /* Delete on close if true */
24163 struct vxworksFileId *pId; /* Unique file ID */
24164 #endif
24165 #ifndef NDEBUG
24166 /* The next group of variables are used to track whether or not the
24167 ** transaction counter in bytes 24-27 of database files are updated
24168 ** whenever any part of the database changes. An assertion fault will
24169 ** occur if a file is updated without also updating the transaction
24170 ** counter. This test is made to avoid new problems similar to the
24171 ** one described by ticket #3584.
24173 unsigned char transCntrChng; /* True if the transaction counter changed */
24174 unsigned char dbUpdate; /* True if any part of database file changed */
24175 unsigned char inNormalWrite; /* True if in a normal write operation */
24176 #endif
24177 #ifdef SQLITE_TEST
24178 /* In test mode, increase the size of this structure a bit so that
24179 ** it is larger than the struct CrashFile defined in test6.c.
24181 char aPadding[32];
24182 #endif
24186 ** Allowed values for the unixFile.ctrlFlags bitmask:
24188 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
24189 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
24190 #define UNIXFILE_DIRSYNC 0x04 /* Directory sync needed */
24193 ** Include code that is common to all os_*.c files
24195 /************** Include os_common.h in the middle of os_unix.c ***************/
24196 /************** Begin file os_common.h ***************************************/
24198 ** 2004 May 22
24200 ** The author disclaims copyright to this source code. In place of
24201 ** a legal notice, here is a blessing:
24203 ** May you do good and not evil.
24204 ** May you find forgiveness for yourself and forgive others.
24205 ** May you share freely, never taking more than you give.
24207 ******************************************************************************
24209 ** This file contains macros and a little bit of code that is common to
24210 ** all of the platform-specific files (os_*.c) and is #included into those
24211 ** files.
24213 ** This file should be #included by the os_*.c files only. It is not a
24214 ** general purpose header file.
24216 #ifndef _OS_COMMON_H_
24217 #define _OS_COMMON_H_
24220 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24221 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24222 ** switch. The following code should catch this problem at compile-time.
24224 #ifdef MEMORY_DEBUG
24225 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
24226 #endif
24228 #ifdef SQLITE_DEBUG
24229 SQLITE_PRIVATE int sqlite3OSTrace = 0;
24230 #define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
24231 #else
24232 #define OSTRACE(X)
24233 #endif
24236 ** Macros for performance tracing. Normally turned off. Only works
24237 ** on i486 hardware.
24239 #ifdef SQLITE_PERFORMANCE_TRACE
24242 ** hwtime.h contains inline assembler code for implementing
24243 ** high-performance timing routines.
24245 /************** Include hwtime.h in the middle of os_common.h ****************/
24246 /************** Begin file hwtime.h ******************************************/
24248 ** 2008 May 27
24250 ** The author disclaims copyright to this source code. In place of
24251 ** a legal notice, here is a blessing:
24253 ** May you do good and not evil.
24254 ** May you find forgiveness for yourself and forgive others.
24255 ** May you share freely, never taking more than you give.
24257 ******************************************************************************
24259 ** This file contains inline asm code for retrieving "high-performance"
24260 ** counters for x86 class CPUs.
24262 #ifndef _HWTIME_H_
24263 #define _HWTIME_H_
24266 ** The following routine only works on pentium-class (or newer) processors.
24267 ** It uses the RDTSC opcode to read the cycle count value out of the
24268 ** processor and returns that value. This can be used for high-res
24269 ** profiling.
24271 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24272 (defined(i386) || defined(__i386__) || defined(_M_IX86))
24274 #if defined(__GNUC__)
24276 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24277 unsigned int lo, hi;
24278 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24279 return (sqlite_uint64)hi << 32 | lo;
24282 #elif defined(_MSC_VER)
24284 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24285 __asm {
24286 rdtsc
24287 ret ; return value at EDX:EAX
24291 #endif
24293 #elif (defined(__GNUC__) && defined(__x86_64__))
24295 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24296 unsigned long val;
24297 __asm__ __volatile__ ("rdtsc" : "=A" (val));
24298 return val;
24301 #elif (defined(__GNUC__) && defined(__ppc__))
24303 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24304 unsigned long long retval;
24305 unsigned long junk;
24306 __asm__ __volatile__ ("\n\
24307 1: mftbu %1\n\
24308 mftb %L0\n\
24309 mftbu %0\n\
24310 cmpw %0,%1\n\
24311 bne 1b"
24312 : "=r" (retval), "=r" (junk));
24313 return retval;
24316 #else
24318 #error Need implementation of sqlite3Hwtime() for your platform.
24321 ** To compile without implementing sqlite3Hwtime() for your platform,
24322 ** you can remove the above #error and use the following
24323 ** stub function. You will lose timing support for many
24324 ** of the debugging and testing utilities, but it should at
24325 ** least compile and run.
24327 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24329 #endif
24331 #endif /* !defined(_HWTIME_H_) */
24333 /************** End of hwtime.h **********************************************/
24334 /************** Continuing where we left off in os_common.h ******************/
24336 static sqlite_uint64 g_start;
24337 static sqlite_uint64 g_elapsed;
24338 #define TIMER_START g_start=sqlite3Hwtime()
24339 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
24340 #define TIMER_ELAPSED g_elapsed
24341 #else
24342 #define TIMER_START
24343 #define TIMER_END
24344 #define TIMER_ELAPSED ((sqlite_uint64)0)
24345 #endif
24348 ** If we compile with the SQLITE_TEST macro set, then the following block
24349 ** of code will give us the ability to simulate a disk I/O error. This
24350 ** is used for testing the I/O recovery logic.
24352 #ifdef SQLITE_TEST
24353 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
24354 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
24355 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
24356 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
24357 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
24358 SQLITE_API int sqlite3_diskfull_pending = 0;
24359 SQLITE_API int sqlite3_diskfull = 0;
24360 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24361 #define SimulateIOError(CODE) \
24362 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24363 || sqlite3_io_error_pending-- == 1 ) \
24364 { local_ioerr(); CODE; }
24365 static void local_ioerr(){
24366 IOTRACE(("IOERR\n"));
24367 sqlite3_io_error_hit++;
24368 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24370 #define SimulateDiskfullError(CODE) \
24371 if( sqlite3_diskfull_pending ){ \
24372 if( sqlite3_diskfull_pending == 1 ){ \
24373 local_ioerr(); \
24374 sqlite3_diskfull = 1; \
24375 sqlite3_io_error_hit = 1; \
24376 CODE; \
24377 }else{ \
24378 sqlite3_diskfull_pending--; \
24381 #else
24382 #define SimulateIOErrorBenign(X)
24383 #define SimulateIOError(A)
24384 #define SimulateDiskfullError(A)
24385 #endif
24388 ** When testing, keep a count of the number of open files.
24390 #ifdef SQLITE_TEST
24391 SQLITE_API int sqlite3_open_file_count = 0;
24392 #define OpenCounter(X) sqlite3_open_file_count+=(X)
24393 #else
24394 #define OpenCounter(X)
24395 #endif
24397 #endif /* !defined(_OS_COMMON_H_) */
24399 /************** End of os_common.h *******************************************/
24400 /************** Continuing where we left off in os_unix.c ********************/
24403 ** Define various macros that are missing from some systems.
24405 #ifndef O_LARGEFILE
24406 # define O_LARGEFILE 0
24407 #endif
24408 #ifdef SQLITE_DISABLE_LFS
24409 # undef O_LARGEFILE
24410 # define O_LARGEFILE 0
24411 #endif
24412 #ifndef O_NOFOLLOW
24413 # define O_NOFOLLOW 0
24414 #endif
24415 #ifndef O_BINARY
24416 # define O_BINARY 0
24417 #endif
24420 ** The threadid macro resolves to the thread-id or to 0. Used for
24421 ** testing and debugging only.
24423 #if SQLITE_THREADSAFE
24424 #define threadid pthread_self()
24425 #else
24426 #define threadid 0
24427 #endif
24429 /* Forward reference */
24430 static int openDirectory(const char*, int*);
24433 ** Many system calls are accessed through pointer-to-functions so that
24434 ** they may be overridden at runtime to facilitate fault injection during
24435 ** testing and sandboxing. The following array holds the names and pointers
24436 ** to all overrideable system calls.
24438 static struct unix_syscall {
24439 const char *zName; /* Name of the sytem call */
24440 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
24441 sqlite3_syscall_ptr pDefault; /* Default value */
24442 } aSyscall[] = {
24443 { "open", (sqlite3_syscall_ptr)open, 0 },
24444 #define osOpen ((int(*)(const char*,int,...))aSyscall[0].pCurrent)
24446 { "close", (sqlite3_syscall_ptr)close, 0 },
24447 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
24449 { "access", (sqlite3_syscall_ptr)access, 0 },
24450 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
24452 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
24453 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
24455 { "stat", (sqlite3_syscall_ptr)stat, 0 },
24456 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
24459 ** The DJGPP compiler environment looks mostly like Unix, but it
24460 ** lacks the fcntl() system call. So redefine fcntl() to be something
24461 ** that always succeeds. This means that locking does not occur under
24462 ** DJGPP. But it is DOS - what did you expect?
24464 #ifdef __DJGPP__
24465 { "fstat", 0, 0 },
24466 #define osFstat(a,b,c) 0
24467 #else
24468 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
24469 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
24470 #endif
24472 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
24473 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
24475 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
24476 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
24478 { "read", (sqlite3_syscall_ptr)read, 0 },
24479 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
24481 #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
24482 { "pread", (sqlite3_syscall_ptr)pread, 0 },
24483 #else
24484 { "pread", (sqlite3_syscall_ptr)0, 0 },
24485 #endif
24486 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
24488 #if defined(USE_PREAD64)
24489 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
24490 #else
24491 { "pread64", (sqlite3_syscall_ptr)0, 0 },
24492 #endif
24493 #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
24495 { "write", (sqlite3_syscall_ptr)write, 0 },
24496 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
24498 #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
24499 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
24500 #else
24501 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
24502 #endif
24503 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
24504 aSyscall[12].pCurrent)
24506 #if defined(USE_PREAD64)
24507 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
24508 #else
24509 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
24510 #endif
24511 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
24512 aSyscall[13].pCurrent)
24514 #if SQLITE_ENABLE_LOCKING_STYLE
24515 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
24516 #else
24517 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
24518 #endif
24519 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
24521 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
24522 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
24523 #else
24524 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
24525 #endif
24526 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
24528 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
24529 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
24531 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
24532 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
24534 }; /* End of the overrideable system calls */
24537 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
24538 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
24539 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
24540 ** system call named zName.
24542 static int unixSetSystemCall(
24543 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
24544 const char *zName, /* Name of system call to override */
24545 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
24547 unsigned int i;
24548 int rc = SQLITE_NOTFOUND;
24550 UNUSED_PARAMETER(pNotUsed);
24551 if( zName==0 ){
24552 /* If no zName is given, restore all system calls to their default
24553 ** settings and return NULL
24555 rc = SQLITE_OK;
24556 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24557 if( aSyscall[i].pDefault ){
24558 aSyscall[i].pCurrent = aSyscall[i].pDefault;
24561 }else{
24562 /* If zName is specified, operate on only the one system call
24563 ** specified.
24565 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24566 if( strcmp(zName, aSyscall[i].zName)==0 ){
24567 if( aSyscall[i].pDefault==0 ){
24568 aSyscall[i].pDefault = aSyscall[i].pCurrent;
24570 rc = SQLITE_OK;
24571 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
24572 aSyscall[i].pCurrent = pNewFunc;
24573 break;
24577 return rc;
24581 ** Return the value of a system call. Return NULL if zName is not a
24582 ** recognized system call name. NULL is also returned if the system call
24583 ** is currently undefined.
24585 static sqlite3_syscall_ptr unixGetSystemCall(
24586 sqlite3_vfs *pNotUsed,
24587 const char *zName
24589 unsigned int i;
24591 UNUSED_PARAMETER(pNotUsed);
24592 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24593 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
24595 return 0;
24599 ** Return the name of the first system call after zName. If zName==NULL
24600 ** then return the name of the first system call. Return NULL if zName
24601 ** is the last system call or if zName is not the name of a valid
24602 ** system call.
24604 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
24605 int i = -1;
24607 UNUSED_PARAMETER(p);
24608 if( zName ){
24609 for(i=0; i<ArraySize(aSyscall)-1; i++){
24610 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
24613 for(i++; i<ArraySize(aSyscall); i++){
24614 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
24616 return 0;
24620 ** Retry open() calls that fail due to EINTR
24622 static int robust_open(const char *z, int f, int m){
24623 int rc;
24624 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
24625 return rc;
24629 ** Helper functions to obtain and relinquish the global mutex. The
24630 ** global mutex is used to protect the unixInodeInfo and
24631 ** vxworksFileId objects used by this file, all of which may be
24632 ** shared by multiple threads.
24634 ** Function unixMutexHeld() is used to assert() that the global mutex
24635 ** is held when required. This function is only used as part of assert()
24636 ** statements. e.g.
24638 ** unixEnterMutex()
24639 ** assert( unixMutexHeld() );
24640 ** unixEnterLeave()
24642 static void unixEnterMutex(void){
24643 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24645 static void unixLeaveMutex(void){
24646 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24648 #ifdef SQLITE_DEBUG
24649 static int unixMutexHeld(void) {
24650 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24652 #endif
24655 #ifdef SQLITE_DEBUG
24657 ** Helper function for printing out trace information from debugging
24658 ** binaries. This returns the string represetation of the supplied
24659 ** integer lock-type.
24661 static const char *azFileLock(int eFileLock){
24662 switch( eFileLock ){
24663 case NO_LOCK: return "NONE";
24664 case SHARED_LOCK: return "SHARED";
24665 case RESERVED_LOCK: return "RESERVED";
24666 case PENDING_LOCK: return "PENDING";
24667 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
24669 return "ERROR";
24671 #endif
24673 #ifdef SQLITE_LOCK_TRACE
24675 ** Print out information about all locking operations.
24677 ** This routine is used for troubleshooting locks on multithreaded
24678 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
24679 ** command-line option on the compiler. This code is normally
24680 ** turned off.
24682 static int lockTrace(int fd, int op, struct flock *p){
24683 char *zOpName, *zType;
24684 int s;
24685 int savedErrno;
24686 if( op==F_GETLK ){
24687 zOpName = "GETLK";
24688 }else if( op==F_SETLK ){
24689 zOpName = "SETLK";
24690 }else{
24691 s = osFcntl(fd, op, p);
24692 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
24693 return s;
24695 if( p->l_type==F_RDLCK ){
24696 zType = "RDLCK";
24697 }else if( p->l_type==F_WRLCK ){
24698 zType = "WRLCK";
24699 }else if( p->l_type==F_UNLCK ){
24700 zType = "UNLCK";
24701 }else{
24702 assert( 0 );
24704 assert( p->l_whence==SEEK_SET );
24705 s = osFcntl(fd, op, p);
24706 savedErrno = errno;
24707 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
24708 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
24709 (int)p->l_pid, s);
24710 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
24711 struct flock l2;
24712 l2 = *p;
24713 osFcntl(fd, F_GETLK, &l2);
24714 if( l2.l_type==F_RDLCK ){
24715 zType = "RDLCK";
24716 }else if( l2.l_type==F_WRLCK ){
24717 zType = "WRLCK";
24718 }else if( l2.l_type==F_UNLCK ){
24719 zType = "UNLCK";
24720 }else{
24721 assert( 0 );
24723 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
24724 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
24726 errno = savedErrno;
24727 return s;
24729 #undef osFcntl
24730 #define osFcntl lockTrace
24731 #endif /* SQLITE_LOCK_TRACE */
24734 ** Retry ftruncate() calls that fail due to EINTR
24736 static int robust_ftruncate(int h, sqlite3_int64 sz){
24737 int rc;
24738 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
24739 return rc;
24743 ** This routine translates a standard POSIX errno code into something
24744 ** useful to the clients of the sqlite3 functions. Specifically, it is
24745 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
24746 ** and a variety of "please close the file descriptor NOW" errors into
24747 ** SQLITE_IOERR
24749 ** Errors during initialization of locks, or file system support for locks,
24750 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
24752 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
24753 switch (posixError) {
24754 #if 0
24755 /* At one point this code was not commented out. In theory, this branch
24756 ** should never be hit, as this function should only be called after
24757 ** a locking-related function (i.e. fcntl()) has returned non-zero with
24758 ** the value of errno as the first argument. Since a system call has failed,
24759 ** errno should be non-zero.
24761 ** Despite this, if errno really is zero, we still don't want to return
24762 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
24763 ** propagated back to the caller. Commenting this branch out means errno==0
24764 ** will be handled by the "default:" case below.
24766 case 0:
24767 return SQLITE_OK;
24768 #endif
24770 case EAGAIN:
24771 case ETIMEDOUT:
24772 case EBUSY:
24773 case EINTR:
24774 case ENOLCK:
24775 /* random NFS retry error, unless during file system support
24776 * introspection, in which it actually means what it says */
24777 return SQLITE_BUSY;
24779 case EACCES:
24780 /* EACCES is like EAGAIN during locking operations, but not any other time*/
24781 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
24782 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
24783 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
24784 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
24785 return SQLITE_BUSY;
24787 /* else fall through */
24788 case EPERM:
24789 return SQLITE_PERM;
24791 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
24792 ** this module never makes such a call. And the code in SQLite itself
24793 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
24794 ** this case is also commented out. If the system does set errno to EDEADLK,
24795 ** the default SQLITE_IOERR_XXX code will be returned. */
24796 #if 0
24797 case EDEADLK:
24798 return SQLITE_IOERR_BLOCKED;
24799 #endif
24801 #if EOPNOTSUPP!=ENOTSUP
24802 case EOPNOTSUPP:
24803 /* something went terribly awry, unless during file system support
24804 * introspection, in which it actually means what it says */
24805 #endif
24806 #ifdef ENOTSUP
24807 case ENOTSUP:
24808 /* invalid fd, unless during file system support introspection, in which
24809 * it actually means what it says */
24810 #endif
24811 case EIO:
24812 case EBADF:
24813 case EINVAL:
24814 case ENOTCONN:
24815 case ENODEV:
24816 case ENXIO:
24817 case ENOENT:
24818 case ESTALE:
24819 case ENOSYS:
24820 /* these should force the client to close the file and reconnect */
24822 default:
24823 return sqliteIOErr;
24829 /******************************************************************************
24830 ****************** Begin Unique File ID Utility Used By VxWorks ***************
24832 ** On most versions of unix, we can get a unique ID for a file by concatenating
24833 ** the device number and the inode number. But this does not work on VxWorks.
24834 ** On VxWorks, a unique file id must be based on the canonical filename.
24836 ** A pointer to an instance of the following structure can be used as a
24837 ** unique file ID in VxWorks. Each instance of this structure contains
24838 ** a copy of the canonical filename. There is also a reference count.
24839 ** The structure is reclaimed when the number of pointers to it drops to
24840 ** zero.
24842 ** There are never very many files open at one time and lookups are not
24843 ** a performance-critical path, so it is sufficient to put these
24844 ** structures on a linked list.
24846 struct vxworksFileId {
24847 struct vxworksFileId *pNext; /* Next in a list of them all */
24848 int nRef; /* Number of references to this one */
24849 int nName; /* Length of the zCanonicalName[] string */
24850 char *zCanonicalName; /* Canonical filename */
24853 #if OS_VXWORKS
24855 ** All unique filenames are held on a linked list headed by this
24856 ** variable:
24858 static struct vxworksFileId *vxworksFileList = 0;
24861 ** Simplify a filename into its canonical form
24862 ** by making the following changes:
24864 ** * removing any trailing and duplicate /
24865 ** * convert /./ into just /
24866 ** * convert /A/../ where A is any simple name into just /
24868 ** Changes are made in-place. Return the new name length.
24870 ** The original filename is in z[0..n-1]. Return the number of
24871 ** characters in the simplified name.
24873 static int vxworksSimplifyName(char *z, int n){
24874 int i, j;
24875 while( n>1 && z[n-1]=='/' ){ n--; }
24876 for(i=j=0; i<n; i++){
24877 if( z[i]=='/' ){
24878 if( z[i+1]=='/' ) continue;
24879 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
24880 i += 1;
24881 continue;
24883 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
24884 while( j>0 && z[j-1]!='/' ){ j--; }
24885 if( j>0 ){ j--; }
24886 i += 2;
24887 continue;
24890 z[j++] = z[i];
24892 z[j] = 0;
24893 return j;
24897 ** Find a unique file ID for the given absolute pathname. Return
24898 ** a pointer to the vxworksFileId object. This pointer is the unique
24899 ** file ID.
24901 ** The nRef field of the vxworksFileId object is incremented before
24902 ** the object is returned. A new vxworksFileId object is created
24903 ** and added to the global list if necessary.
24905 ** If a memory allocation error occurs, return NULL.
24907 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
24908 struct vxworksFileId *pNew; /* search key and new file ID */
24909 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
24910 int n; /* Length of zAbsoluteName string */
24912 assert( zAbsoluteName[0]=='/' );
24913 n = (int)strlen(zAbsoluteName);
24914 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
24915 if( pNew==0 ) return 0;
24916 pNew->zCanonicalName = (char*)&pNew[1];
24917 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
24918 n = vxworksSimplifyName(pNew->zCanonicalName, n);
24920 /* Search for an existing entry that matching the canonical name.
24921 ** If found, increment the reference count and return a pointer to
24922 ** the existing file ID.
24924 unixEnterMutex();
24925 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
24926 if( pCandidate->nName==n
24927 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
24929 sqlite3_free(pNew);
24930 pCandidate->nRef++;
24931 unixLeaveMutex();
24932 return pCandidate;
24936 /* No match was found. We will make a new file ID */
24937 pNew->nRef = 1;
24938 pNew->nName = n;
24939 pNew->pNext = vxworksFileList;
24940 vxworksFileList = pNew;
24941 unixLeaveMutex();
24942 return pNew;
24946 ** Decrement the reference count on a vxworksFileId object. Free
24947 ** the object when the reference count reaches zero.
24949 static void vxworksReleaseFileId(struct vxworksFileId *pId){
24950 unixEnterMutex();
24951 assert( pId->nRef>0 );
24952 pId->nRef--;
24953 if( pId->nRef==0 ){
24954 struct vxworksFileId **pp;
24955 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
24956 assert( *pp==pId );
24957 *pp = pId->pNext;
24958 sqlite3_free(pId);
24960 unixLeaveMutex();
24962 #endif /* OS_VXWORKS */
24963 /*************** End of Unique File ID Utility Used By VxWorks ****************
24964 ******************************************************************************/
24967 /******************************************************************************
24968 *************************** Posix Advisory Locking ****************************
24970 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
24971 ** section 6.5.2.2 lines 483 through 490 specify that when a process
24972 ** sets or clears a lock, that operation overrides any prior locks set
24973 ** by the same process. It does not explicitly say so, but this implies
24974 ** that it overrides locks set by the same process using a different
24975 ** file descriptor. Consider this test case:
24977 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
24978 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
24980 ** Suppose ./file1 and ./file2 are really the same file (because
24981 ** one is a hard or symbolic link to the other) then if you set
24982 ** an exclusive lock on fd1, then try to get an exclusive lock
24983 ** on fd2, it works. I would have expected the second lock to
24984 ** fail since there was already a lock on the file due to fd1.
24985 ** But not so. Since both locks came from the same process, the
24986 ** second overrides the first, even though they were on different
24987 ** file descriptors opened on different file names.
24989 ** This means that we cannot use POSIX locks to synchronize file access
24990 ** among competing threads of the same process. POSIX locks will work fine
24991 ** to synchronize access for threads in separate processes, but not
24992 ** threads within the same process.
24994 ** To work around the problem, SQLite has to manage file locks internally
24995 ** on its own. Whenever a new database is opened, we have to find the
24996 ** specific inode of the database file (the inode is determined by the
24997 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
24998 ** and check for locks already existing on that inode. When locks are
24999 ** created or removed, we have to look at our own internal record of the
25000 ** locks to see if another thread has previously set a lock on that same
25001 ** inode.
25003 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
25004 ** For VxWorks, we have to use the alternative unique ID system based on
25005 ** canonical filename and implemented in the previous division.)
25007 ** The sqlite3_file structure for POSIX is no longer just an integer file
25008 ** descriptor. It is now a structure that holds the integer file
25009 ** descriptor and a pointer to a structure that describes the internal
25010 ** locks on the corresponding inode. There is one locking structure
25011 ** per inode, so if the same inode is opened twice, both unixFile structures
25012 ** point to the same locking structure. The locking structure keeps
25013 ** a reference count (so we will know when to delete it) and a "cnt"
25014 ** field that tells us its internal lock status. cnt==0 means the
25015 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
25016 ** cnt>0 means there are cnt shared locks on the file.
25018 ** Any attempt to lock or unlock a file first checks the locking
25019 ** structure. The fcntl() system call is only invoked to set a
25020 ** POSIX lock if the internal lock structure transitions between
25021 ** a locked and an unlocked state.
25023 ** But wait: there are yet more problems with POSIX advisory locks.
25025 ** If you close a file descriptor that points to a file that has locks,
25026 ** all locks on that file that are owned by the current process are
25027 ** released. To work around this problem, each unixInodeInfo object
25028 ** maintains a count of the number of pending locks on tha inode.
25029 ** When an attempt is made to close an unixFile, if there are
25030 ** other unixFile open on the same inode that are holding locks, the call
25031 ** to close() the file descriptor is deferred until all of the locks clear.
25032 ** The unixInodeInfo structure keeps a list of file descriptors that need to
25033 ** be closed and that list is walked (and cleared) when the last lock
25034 ** clears.
25036 ** Yet another problem: LinuxThreads do not play well with posix locks.
25038 ** Many older versions of linux use the LinuxThreads library which is
25039 ** not posix compliant. Under LinuxThreads, a lock created by thread
25040 ** A cannot be modified or overridden by a different thread B.
25041 ** Only thread A can modify the lock. Locking behavior is correct
25042 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
25043 ** on linux - with NPTL a lock created by thread A can override locks
25044 ** in thread B. But there is no way to know at compile-time which
25045 ** threading library is being used. So there is no way to know at
25046 ** compile-time whether or not thread A can override locks on thread B.
25047 ** One has to do a run-time check to discover the behavior of the
25048 ** current process.
25050 ** SQLite used to support LinuxThreads. But support for LinuxThreads
25051 ** was dropped beginning with version 3.7.0. SQLite will still work with
25052 ** LinuxThreads provided that (1) there is no more than one connection
25053 ** per database file in the same process and (2) database connections
25054 ** do not move across threads.
25058 ** An instance of the following structure serves as the key used
25059 ** to locate a particular unixInodeInfo object.
25061 struct unixFileId {
25062 dev_t dev; /* Device number */
25063 #if OS_VXWORKS
25064 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
25065 #else
25066 ino_t ino; /* Inode number */
25067 #endif
25071 ** An instance of the following structure is allocated for each open
25072 ** inode. Or, on LinuxThreads, there is one of these structures for
25073 ** each inode opened by each thread.
25075 ** A single inode can have multiple file descriptors, so each unixFile
25076 ** structure contains a pointer to an instance of this object and this
25077 ** object keeps a count of the number of unixFile pointing to it.
25079 struct unixInodeInfo {
25080 struct unixFileId fileId; /* The lookup key */
25081 int nShared; /* Number of SHARED locks held */
25082 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
25083 unsigned char bProcessLock; /* An exclusive process lock is held */
25084 int nRef; /* Number of pointers to this structure */
25085 unixShmNode *pShmNode; /* Shared memory associated with this inode */
25086 int nLock; /* Number of outstanding file locks */
25087 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
25088 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
25089 unixInodeInfo *pPrev; /* .... doubly linked */
25090 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
25091 unsigned long long sharedByte; /* for AFP simulated shared lock */
25092 #endif
25093 #if OS_VXWORKS
25094 sem_t *pSem; /* Named POSIX semaphore */
25095 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
25096 #endif
25100 ** A lists of all unixInodeInfo objects.
25102 static unixInodeInfo *inodeList = 0;
25106 ** This function - unixLogError_x(), is only ever called via the macro
25107 ** unixLogError().
25109 ** It is invoked after an error occurs in an OS function and errno has been
25110 ** set. It logs a message using sqlite3_log() containing the current value of
25111 ** errno and, if possible, the human-readable equivalent from strerror() or
25112 ** strerror_r().
25114 ** The first argument passed to the macro should be the error code that
25115 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
25116 ** The two subsequent arguments should be the name of the OS function that
25117 ** failed (e.g. "unlink", "open") and the the associated file-system path,
25118 ** if any.
25120 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
25121 static int unixLogErrorAtLine(
25122 int errcode, /* SQLite error code */
25123 const char *zFunc, /* Name of OS function that failed */
25124 const char *zPath, /* File path associated with error */
25125 int iLine /* Source line number where error occurred */
25127 char *zErr; /* Message from strerror() or equivalent */
25128 int iErrno = errno; /* Saved syscall error number */
25130 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25131 ** the strerror() function to obtain the human-readable error message
25132 ** equivalent to errno. Otherwise, use strerror_r().
25134 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25135 char aErr[80];
25136 memset(aErr, 0, sizeof(aErr));
25137 zErr = aErr;
25139 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25140 ** assume that the system provides the the GNU version of strerror_r() that
25141 ** returns a pointer to a buffer containing the error message. That pointer
25142 ** may point to aErr[], or it may point to some static storage somewhere.
25143 ** Otherwise, assume that the system provides the POSIX version of
25144 ** strerror_r(), which always writes an error message into aErr[].
25146 ** If the code incorrectly assumes that it is the POSIX version that is
25147 ** available, the error message will often be an empty string. Not a
25148 ** huge problem. Incorrectly concluding that the GNU version is available
25149 ** could lead to a segfault though.
25151 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
25152 zErr =
25153 # endif
25154 strerror_r(iErrno, aErr, sizeof(aErr)-1);
25156 #elif SQLITE_THREADSAFE
25157 /* This is a threadsafe build, but strerror_r() is not available. */
25158 zErr = "";
25159 #else
25160 /* Non-threadsafe build, use strerror(). */
25161 zErr = strerror(iErrno);
25162 #endif
25164 assert( errcode!=SQLITE_OK );
25165 if( zPath==0 ) zPath = "";
25166 sqlite3_log(errcode,
25167 "os_unix.c:%d: (%d) %s(%s) - %s",
25168 iLine, iErrno, zFunc, zPath, zErr
25171 return errcode;
25175 ** Close a file descriptor.
25177 ** We assume that close() almost always works, since it is only in a
25178 ** very sick application or on a very sick platform that it might fail.
25179 ** If it does fail, simply leak the file descriptor, but do log the
25180 ** error.
25182 ** Note that it is not safe to retry close() after EINTR since the
25183 ** file descriptor might have already been reused by another thread.
25184 ** So we don't even try to recover from an EINTR. Just log the error
25185 ** and move on.
25187 static void robust_close(unixFile *pFile, int h, int lineno){
25188 if( osClose(h) ){
25189 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
25190 pFile ? pFile->zPath : 0, lineno);
25195 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
25197 static void closePendingFds(unixFile *pFile){
25198 unixInodeInfo *pInode = pFile->pInode;
25199 UnixUnusedFd *p;
25200 UnixUnusedFd *pNext;
25201 for(p=pInode->pUnused; p; p=pNext){
25202 pNext = p->pNext;
25203 robust_close(pFile, p->fd, __LINE__);
25204 sqlite3_free(p);
25206 pInode->pUnused = 0;
25210 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
25212 ** The mutex entered using the unixEnterMutex() function must be held
25213 ** when this function is called.
25215 static void releaseInodeInfo(unixFile *pFile){
25216 unixInodeInfo *pInode = pFile->pInode;
25217 assert( unixMutexHeld() );
25218 if( ALWAYS(pInode) ){
25219 pInode->nRef--;
25220 if( pInode->nRef==0 ){
25221 assert( pInode->pShmNode==0 );
25222 closePendingFds(pFile);
25223 if( pInode->pPrev ){
25224 assert( pInode->pPrev->pNext==pInode );
25225 pInode->pPrev->pNext = pInode->pNext;
25226 }else{
25227 assert( inodeList==pInode );
25228 inodeList = pInode->pNext;
25230 if( pInode->pNext ){
25231 assert( pInode->pNext->pPrev==pInode );
25232 pInode->pNext->pPrev = pInode->pPrev;
25234 sqlite3_free(pInode);
25240 ** Given a file descriptor, locate the unixInodeInfo object that
25241 ** describes that file descriptor. Create a new one if necessary. The
25242 ** return value might be uninitialized if an error occurs.
25244 ** The mutex entered using the unixEnterMutex() function must be held
25245 ** when this function is called.
25247 ** Return an appropriate error code.
25249 static int findInodeInfo(
25250 unixFile *pFile, /* Unix file with file desc used in the key */
25251 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
25253 int rc; /* System call return code */
25254 int fd; /* The file descriptor for pFile */
25255 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
25256 struct stat statbuf; /* Low-level file information */
25257 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
25259 assert( unixMutexHeld() );
25261 /* Get low-level information about the file that we can used to
25262 ** create a unique name for the file.
25264 fd = pFile->h;
25265 rc = osFstat(fd, &statbuf);
25266 if( rc!=0 ){
25267 pFile->lastErrno = errno;
25268 #ifdef EOVERFLOW
25269 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
25270 #endif
25271 return SQLITE_IOERR;
25274 #ifdef __APPLE__
25275 /* On OS X on an msdos filesystem, the inode number is reported
25276 ** incorrectly for zero-size files. See ticket #3260. To work
25277 ** around this problem (we consider it a bug in OS X, not SQLite)
25278 ** we always increase the file size to 1 by writing a single byte
25279 ** prior to accessing the inode number. The one byte written is
25280 ** an ASCII 'S' character which also happens to be the first byte
25281 ** in the header of every SQLite database. In this way, if there
25282 ** is a race condition such that another thread has already populated
25283 ** the first page of the database, no damage is done.
25285 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
25286 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
25287 if( rc!=1 ){
25288 pFile->lastErrno = errno;
25289 return SQLITE_IOERR;
25291 rc = osFstat(fd, &statbuf);
25292 if( rc!=0 ){
25293 pFile->lastErrno = errno;
25294 return SQLITE_IOERR;
25297 #endif
25299 memset(&fileId, 0, sizeof(fileId));
25300 fileId.dev = statbuf.st_dev;
25301 #if OS_VXWORKS
25302 fileId.pId = pFile->pId;
25303 #else
25304 fileId.ino = statbuf.st_ino;
25305 #endif
25306 pInode = inodeList;
25307 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
25308 pInode = pInode->pNext;
25310 if( pInode==0 ){
25311 pInode = sqlite3_malloc( sizeof(*pInode) );
25312 if( pInode==0 ){
25313 return SQLITE_NOMEM;
25315 memset(pInode, 0, sizeof(*pInode));
25316 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
25317 pInode->nRef = 1;
25318 pInode->pNext = inodeList;
25319 pInode->pPrev = 0;
25320 if( inodeList ) inodeList->pPrev = pInode;
25321 inodeList = pInode;
25322 }else{
25323 pInode->nRef++;
25325 *ppInode = pInode;
25326 return SQLITE_OK;
25331 ** This routine checks if there is a RESERVED lock held on the specified
25332 ** file by this or any other process. If such a lock is held, set *pResOut
25333 ** to a non-zero value otherwise *pResOut is set to zero. The return value
25334 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25336 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
25337 int rc = SQLITE_OK;
25338 int reserved = 0;
25339 unixFile *pFile = (unixFile*)id;
25341 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25343 assert( pFile );
25344 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25346 /* Check if a thread in this process holds such a lock */
25347 if( pFile->pInode->eFileLock>SHARED_LOCK ){
25348 reserved = 1;
25351 /* Otherwise see if some other process holds it.
25353 #ifndef __DJGPP__
25354 if( !reserved && !pFile->pInode->bProcessLock ){
25355 struct flock lock;
25356 lock.l_whence = SEEK_SET;
25357 lock.l_start = RESERVED_BYTE;
25358 lock.l_len = 1;
25359 lock.l_type = F_WRLCK;
25360 if( osFcntl(pFile->h, F_GETLK, &lock) ){
25361 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
25362 pFile->lastErrno = errno;
25363 } else if( lock.l_type!=F_UNLCK ){
25364 reserved = 1;
25367 #endif
25369 unixLeaveMutex();
25370 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
25372 *pResOut = reserved;
25373 return rc;
25377 ** Attempt to set a system-lock on the file pFile. The lock is
25378 ** described by pLock.
25380 ** If the pFile was opened read/write from unix-excl, then the only lock
25381 ** ever obtained is an exclusive lock, and it is obtained exactly once
25382 ** the first time any lock is attempted. All subsequent system locking
25383 ** operations become no-ops. Locking operations still happen internally,
25384 ** in order to coordinate access between separate database connections
25385 ** within this process, but all of that is handled in memory and the
25386 ** operating system does not participate.
25388 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
25389 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
25390 ** and is read-only.
25392 ** Zero is returned if the call completes successfully, or -1 if a call
25393 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
25395 static int unixFileLock(unixFile *pFile, struct flock *pLock){
25396 int rc;
25397 unixInodeInfo *pInode = pFile->pInode;
25398 assert( unixMutexHeld() );
25399 assert( pInode!=0 );
25400 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
25401 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
25403 if( pInode->bProcessLock==0 ){
25404 struct flock lock;
25405 assert( pInode->nLock==0 );
25406 lock.l_whence = SEEK_SET;
25407 lock.l_start = SHARED_FIRST;
25408 lock.l_len = SHARED_SIZE;
25409 lock.l_type = F_WRLCK;
25410 rc = osFcntl(pFile->h, F_SETLK, &lock);
25411 if( rc<0 ) return rc;
25412 pInode->bProcessLock = 1;
25413 pInode->nLock++;
25414 }else{
25415 rc = 0;
25417 }else{
25418 rc = osFcntl(pFile->h, F_SETLK, pLock);
25420 return rc;
25424 ** Lock the file with the lock specified by parameter eFileLock - one
25425 ** of the following:
25427 ** (1) SHARED_LOCK
25428 ** (2) RESERVED_LOCK
25429 ** (3) PENDING_LOCK
25430 ** (4) EXCLUSIVE_LOCK
25432 ** Sometimes when requesting one lock state, additional lock states
25433 ** are inserted in between. The locking might fail on one of the later
25434 ** transitions leaving the lock state different from what it started but
25435 ** still short of its goal. The following chart shows the allowed
25436 ** transitions and the inserted intermediate states:
25438 ** UNLOCKED -> SHARED
25439 ** SHARED -> RESERVED
25440 ** SHARED -> (PENDING) -> EXCLUSIVE
25441 ** RESERVED -> (PENDING) -> EXCLUSIVE
25442 ** PENDING -> EXCLUSIVE
25444 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
25445 ** routine to lower a locking level.
25447 static int unixLock(sqlite3_file *id, int eFileLock){
25448 /* The following describes the implementation of the various locks and
25449 ** lock transitions in terms of the POSIX advisory shared and exclusive
25450 ** lock primitives (called read-locks and write-locks below, to avoid
25451 ** confusion with SQLite lock names). The algorithms are complicated
25452 ** slightly in order to be compatible with windows systems simultaneously
25453 ** accessing the same database file, in case that is ever required.
25455 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
25456 ** byte', each single bytes at well known offsets, and the 'shared byte
25457 ** range', a range of 510 bytes at a well known offset.
25459 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
25460 ** byte'. If this is successful, a random byte from the 'shared byte
25461 ** range' is read-locked and the lock on the 'pending byte' released.
25463 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
25464 ** A RESERVED lock is implemented by grabbing a write-lock on the
25465 ** 'reserved byte'.
25467 ** A process may only obtain a PENDING lock after it has obtained a
25468 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
25469 ** on the 'pending byte'. This ensures that no new SHARED locks can be
25470 ** obtained, but existing SHARED locks are allowed to persist. A process
25471 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
25472 ** This property is used by the algorithm for rolling back a journal file
25473 ** after a crash.
25475 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
25476 ** implemented by obtaining a write-lock on the entire 'shared byte
25477 ** range'. Since all other locks require a read-lock on one of the bytes
25478 ** within this range, this ensures that no other locks are held on the
25479 ** database.
25481 ** The reason a single byte cannot be used instead of the 'shared byte
25482 ** range' is that some versions of windows do not support read-locks. By
25483 ** locking a random byte from a range, concurrent SHARED locks may exist
25484 ** even if the locking primitive used is always a write-lock.
25486 int rc = SQLITE_OK;
25487 unixFile *pFile = (unixFile*)id;
25488 unixInodeInfo *pInode = pFile->pInode;
25489 struct flock lock;
25490 int tErrno = 0;
25492 assert( pFile );
25493 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
25494 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25495 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25497 /* If there is already a lock of this type or more restrictive on the
25498 ** unixFile, do nothing. Don't use the end_lock: exit path, as
25499 ** unixEnterMutex() hasn't been called yet.
25501 if( pFile->eFileLock>=eFileLock ){
25502 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
25503 azFileLock(eFileLock)));
25504 return SQLITE_OK;
25507 /* Make sure the locking sequence is correct.
25508 ** (1) We never move from unlocked to anything higher than shared lock.
25509 ** (2) SQLite never explicitly requests a pendig lock.
25510 ** (3) A shared lock is always held when a reserve lock is requested.
25512 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25513 assert( eFileLock!=PENDING_LOCK );
25514 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25516 /* This mutex is needed because pFile->pInode is shared across threads
25518 unixEnterMutex();
25519 pInode = pFile->pInode;
25521 /* If some thread using this PID has a lock via a different unixFile*
25522 ** handle that precludes the requested lock, return BUSY.
25524 if( (pFile->eFileLock!=pInode->eFileLock &&
25525 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25527 rc = SQLITE_BUSY;
25528 goto end_lock;
25531 /* If a SHARED lock is requested, and some thread using this PID already
25532 ** has a SHARED or RESERVED lock, then increment reference counts and
25533 ** return SQLITE_OK.
25535 if( eFileLock==SHARED_LOCK &&
25536 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25537 assert( eFileLock==SHARED_LOCK );
25538 assert( pFile->eFileLock==0 );
25539 assert( pInode->nShared>0 );
25540 pFile->eFileLock = SHARED_LOCK;
25541 pInode->nShared++;
25542 pInode->nLock++;
25543 goto end_lock;
25547 /* A PENDING lock is needed before acquiring a SHARED lock and before
25548 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
25549 ** be released.
25551 lock.l_len = 1L;
25552 lock.l_whence = SEEK_SET;
25553 if( eFileLock==SHARED_LOCK
25554 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25556 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
25557 lock.l_start = PENDING_BYTE;
25558 if( unixFileLock(pFile, &lock) ){
25559 tErrno = errno;
25560 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25561 if( rc!=SQLITE_BUSY ){
25562 pFile->lastErrno = tErrno;
25564 goto end_lock;
25569 /* If control gets to this point, then actually go ahead and make
25570 ** operating system calls for the specified lock.
25572 if( eFileLock==SHARED_LOCK ){
25573 assert( pInode->nShared==0 );
25574 assert( pInode->eFileLock==0 );
25575 assert( rc==SQLITE_OK );
25577 /* Now get the read-lock */
25578 lock.l_start = SHARED_FIRST;
25579 lock.l_len = SHARED_SIZE;
25580 if( unixFileLock(pFile, &lock) ){
25581 tErrno = errno;
25582 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25585 /* Drop the temporary PENDING lock */
25586 lock.l_start = PENDING_BYTE;
25587 lock.l_len = 1L;
25588 lock.l_type = F_UNLCK;
25589 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
25590 /* This could happen with a network mount */
25591 tErrno = errno;
25592 rc = SQLITE_IOERR_UNLOCK;
25595 if( rc ){
25596 if( rc!=SQLITE_BUSY ){
25597 pFile->lastErrno = tErrno;
25599 goto end_lock;
25600 }else{
25601 pFile->eFileLock = SHARED_LOCK;
25602 pInode->nLock++;
25603 pInode->nShared = 1;
25605 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25606 /* We are trying for an exclusive lock but another thread in this
25607 ** same process is still holding a shared lock. */
25608 rc = SQLITE_BUSY;
25609 }else{
25610 /* The request was for a RESERVED or EXCLUSIVE lock. It is
25611 ** assumed that there is a SHARED or greater lock on the file
25612 ** already.
25614 assert( 0!=pFile->eFileLock );
25615 lock.l_type = F_WRLCK;
25617 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
25618 if( eFileLock==RESERVED_LOCK ){
25619 lock.l_start = RESERVED_BYTE;
25620 lock.l_len = 1L;
25621 }else{
25622 lock.l_start = SHARED_FIRST;
25623 lock.l_len = SHARED_SIZE;
25626 if( unixFileLock(pFile, &lock) ){
25627 tErrno = errno;
25628 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25629 if( rc!=SQLITE_BUSY ){
25630 pFile->lastErrno = tErrno;
25636 #ifndef NDEBUG
25637 /* Set up the transaction-counter change checking flags when
25638 ** transitioning from a SHARED to a RESERVED lock. The change
25639 ** from SHARED to RESERVED marks the beginning of a normal
25640 ** write operation (not a hot journal rollback).
25642 if( rc==SQLITE_OK
25643 && pFile->eFileLock<=SHARED_LOCK
25644 && eFileLock==RESERVED_LOCK
25646 pFile->transCntrChng = 0;
25647 pFile->dbUpdate = 0;
25648 pFile->inNormalWrite = 1;
25650 #endif
25653 if( rc==SQLITE_OK ){
25654 pFile->eFileLock = eFileLock;
25655 pInode->eFileLock = eFileLock;
25656 }else if( eFileLock==EXCLUSIVE_LOCK ){
25657 pFile->eFileLock = PENDING_LOCK;
25658 pInode->eFileLock = PENDING_LOCK;
25661 end_lock:
25662 unixLeaveMutex();
25663 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
25664 rc==SQLITE_OK ? "ok" : "failed"));
25665 return rc;
25669 ** Add the file descriptor used by file handle pFile to the corresponding
25670 ** pUnused list.
25672 static void setPendingFd(unixFile *pFile){
25673 unixInodeInfo *pInode = pFile->pInode;
25674 UnixUnusedFd *p = pFile->pUnused;
25675 p->pNext = pInode->pUnused;
25676 pInode->pUnused = p;
25677 pFile->h = -1;
25678 pFile->pUnused = 0;
25682 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25683 ** must be either NO_LOCK or SHARED_LOCK.
25685 ** If the locking level of the file descriptor is already at or below
25686 ** the requested locking level, this routine is a no-op.
25688 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
25689 ** the byte range is divided into 2 parts and the first part is unlocked then
25690 ** set to a read lock, then the other part is simply unlocked. This works
25691 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
25692 ** remove the write lock on a region when a read lock is set.
25694 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
25695 unixFile *pFile = (unixFile*)id;
25696 unixInodeInfo *pInode;
25697 struct flock lock;
25698 int rc = SQLITE_OK;
25699 int h;
25701 assert( pFile );
25702 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
25703 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25704 getpid()));
25706 assert( eFileLock<=SHARED_LOCK );
25707 if( pFile->eFileLock<=eFileLock ){
25708 return SQLITE_OK;
25710 unixEnterMutex();
25711 h = pFile->h;
25712 pInode = pFile->pInode;
25713 assert( pInode->nShared!=0 );
25714 if( pFile->eFileLock>SHARED_LOCK ){
25715 assert( pInode->eFileLock==pFile->eFileLock );
25716 SimulateIOErrorBenign(1);
25717 SimulateIOError( h=(-1) )
25718 SimulateIOErrorBenign(0);
25720 #ifndef NDEBUG
25721 /* When reducing a lock such that other processes can start
25722 ** reading the database file again, make sure that the
25723 ** transaction counter was updated if any part of the database
25724 ** file changed. If the transaction counter is not updated,
25725 ** other connections to the same file might not realize that
25726 ** the file has changed and hence might not know to flush their
25727 ** cache. The use of a stale cache can lead to database corruption.
25729 #if 0
25730 assert( pFile->inNormalWrite==0
25731 || pFile->dbUpdate==0
25732 || pFile->transCntrChng==1 );
25733 #endif
25734 pFile->inNormalWrite = 0;
25735 #endif
25737 /* downgrading to a shared lock on NFS involves clearing the write lock
25738 ** before establishing the readlock - to avoid a race condition we downgrade
25739 ** the lock in 2 blocks, so that part of the range will be covered by a
25740 ** write lock until the rest is covered by a read lock:
25741 ** 1: [WWWWW]
25742 ** 2: [....W]
25743 ** 3: [RRRRW]
25744 ** 4: [RRRR.]
25746 if( eFileLock==SHARED_LOCK ){
25748 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
25749 (void)handleNFSUnlock;
25750 assert( handleNFSUnlock==0 );
25751 #endif
25752 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25753 if( handleNFSUnlock ){
25754 int tErrno; /* Error code from system call errors */
25755 off_t divSize = SHARED_SIZE - 1;
25757 lock.l_type = F_UNLCK;
25758 lock.l_whence = SEEK_SET;
25759 lock.l_start = SHARED_FIRST;
25760 lock.l_len = divSize;
25761 if( unixFileLock(pFile, &lock)==(-1) ){
25762 tErrno = errno;
25763 rc = SQLITE_IOERR_UNLOCK;
25764 if( IS_LOCK_ERROR(rc) ){
25765 pFile->lastErrno = tErrno;
25767 goto end_unlock;
25769 lock.l_type = F_RDLCK;
25770 lock.l_whence = SEEK_SET;
25771 lock.l_start = SHARED_FIRST;
25772 lock.l_len = divSize;
25773 if( unixFileLock(pFile, &lock)==(-1) ){
25774 tErrno = errno;
25775 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
25776 if( IS_LOCK_ERROR(rc) ){
25777 pFile->lastErrno = tErrno;
25779 goto end_unlock;
25781 lock.l_type = F_UNLCK;
25782 lock.l_whence = SEEK_SET;
25783 lock.l_start = SHARED_FIRST+divSize;
25784 lock.l_len = SHARED_SIZE-divSize;
25785 if( unixFileLock(pFile, &lock)==(-1) ){
25786 tErrno = errno;
25787 rc = SQLITE_IOERR_UNLOCK;
25788 if( IS_LOCK_ERROR(rc) ){
25789 pFile->lastErrno = tErrno;
25791 goto end_unlock;
25793 }else
25794 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25796 lock.l_type = F_RDLCK;
25797 lock.l_whence = SEEK_SET;
25798 lock.l_start = SHARED_FIRST;
25799 lock.l_len = SHARED_SIZE;
25800 if( unixFileLock(pFile, &lock) ){
25801 /* In theory, the call to unixFileLock() cannot fail because another
25802 ** process is holding an incompatible lock. If it does, this
25803 ** indicates that the other process is not following the locking
25804 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
25805 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
25806 ** an assert to fail). */
25807 rc = SQLITE_IOERR_RDLOCK;
25808 pFile->lastErrno = errno;
25809 goto end_unlock;
25813 lock.l_type = F_UNLCK;
25814 lock.l_whence = SEEK_SET;
25815 lock.l_start = PENDING_BYTE;
25816 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
25817 if( unixFileLock(pFile, &lock)==0 ){
25818 pInode->eFileLock = SHARED_LOCK;
25819 }else{
25820 rc = SQLITE_IOERR_UNLOCK;
25821 pFile->lastErrno = errno;
25822 goto end_unlock;
25825 if( eFileLock==NO_LOCK ){
25826 /* Decrement the shared lock counter. Release the lock using an
25827 ** OS call only when all threads in this same process have released
25828 ** the lock.
25830 pInode->nShared--;
25831 if( pInode->nShared==0 ){
25832 lock.l_type = F_UNLCK;
25833 lock.l_whence = SEEK_SET;
25834 lock.l_start = lock.l_len = 0L;
25835 SimulateIOErrorBenign(1);
25836 SimulateIOError( h=(-1) )
25837 SimulateIOErrorBenign(0);
25838 if( unixFileLock(pFile, &lock)==0 ){
25839 pInode->eFileLock = NO_LOCK;
25840 }else{
25841 rc = SQLITE_IOERR_UNLOCK;
25842 pFile->lastErrno = errno;
25843 pInode->eFileLock = NO_LOCK;
25844 pFile->eFileLock = NO_LOCK;
25848 /* Decrement the count of locks against this same file. When the
25849 ** count reaches zero, close any other file descriptors whose close
25850 ** was deferred because of outstanding locks.
25852 pInode->nLock--;
25853 assert( pInode->nLock>=0 );
25854 if( pInode->nLock==0 ){
25855 closePendingFds(pFile);
25859 end_unlock:
25860 unixLeaveMutex();
25861 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25862 return rc;
25866 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25867 ** must be either NO_LOCK or SHARED_LOCK.
25869 ** If the locking level of the file descriptor is already at or below
25870 ** the requested locking level, this routine is a no-op.
25872 static int unixUnlock(sqlite3_file *id, int eFileLock){
25873 return posixUnlock(id, eFileLock, 0);
25877 ** This function performs the parts of the "close file" operation
25878 ** common to all locking schemes. It closes the directory and file
25879 ** handles, if they are valid, and sets all fields of the unixFile
25880 ** structure to 0.
25882 ** It is *not* necessary to hold the mutex when this routine is called,
25883 ** even on VxWorks. A mutex will be acquired on VxWorks by the
25884 ** vxworksReleaseFileId() routine.
25886 static int closeUnixFile(sqlite3_file *id){
25887 unixFile *pFile = (unixFile*)id;
25888 if( pFile->h>=0 ){
25889 robust_close(pFile, pFile->h, __LINE__);
25890 pFile->h = -1;
25892 #if OS_VXWORKS
25893 if( pFile->pId ){
25894 if( pFile->isDelete ){
25895 osUnlink(pFile->pId->zCanonicalName);
25897 vxworksReleaseFileId(pFile->pId);
25898 pFile->pId = 0;
25900 #endif
25901 OSTRACE(("CLOSE %-3d\n", pFile->h));
25902 OpenCounter(-1);
25903 sqlite3_free(pFile->pUnused);
25904 memset(pFile, 0, sizeof(unixFile));
25905 return SQLITE_OK;
25909 ** Close a file.
25911 static int unixClose(sqlite3_file *id){
25912 int rc = SQLITE_OK;
25913 unixFile *pFile = (unixFile *)id;
25914 unixUnlock(id, NO_LOCK);
25915 unixEnterMutex();
25917 /* unixFile.pInode is always valid here. Otherwise, a different close
25918 ** routine (e.g. nolockClose()) would be called instead.
25920 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
25921 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
25922 /* If there are outstanding locks, do not actually close the file just
25923 ** yet because that would clear those locks. Instead, add the file
25924 ** descriptor to pInode->pUnused list. It will be automatically closed
25925 ** when the last lock is cleared.
25927 setPendingFd(pFile);
25929 releaseInodeInfo(pFile);
25930 rc = closeUnixFile(id);
25931 unixLeaveMutex();
25932 return rc;
25935 /************** End of the posix advisory lock implementation *****************
25936 ******************************************************************************/
25938 /******************************************************************************
25939 ****************************** No-op Locking **********************************
25941 ** Of the various locking implementations available, this is by far the
25942 ** simplest: locking is ignored. No attempt is made to lock the database
25943 ** file for reading or writing.
25945 ** This locking mode is appropriate for use on read-only databases
25946 ** (ex: databases that are burned into CD-ROM, for example.) It can
25947 ** also be used if the application employs some external mechanism to
25948 ** prevent simultaneous access of the same database by two or more
25949 ** database connections. But there is a serious risk of database
25950 ** corruption if this locking mode is used in situations where multiple
25951 ** database connections are accessing the same database file at the same
25952 ** time and one or more of those connections are writing.
25955 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
25956 UNUSED_PARAMETER(NotUsed);
25957 *pResOut = 0;
25958 return SQLITE_OK;
25960 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
25961 UNUSED_PARAMETER2(NotUsed, NotUsed2);
25962 return SQLITE_OK;
25964 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
25965 UNUSED_PARAMETER2(NotUsed, NotUsed2);
25966 return SQLITE_OK;
25970 ** Close the file.
25972 static int nolockClose(sqlite3_file *id) {
25973 return closeUnixFile(id);
25976 /******************* End of the no-op lock implementation *********************
25977 ******************************************************************************/
25979 /******************************************************************************
25980 ************************* Begin dot-file Locking ******************************
25982 ** The dotfile locking implementation uses the existance of separate lock
25983 ** files in order to control access to the database. This works on just
25984 ** about every filesystem imaginable. But there are serious downsides:
25986 ** (1) There is zero concurrency. A single reader blocks all other
25987 ** connections from reading or writing the database.
25989 ** (2) An application crash or power loss can leave stale lock files
25990 ** sitting around that need to be cleared manually.
25992 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
25993 ** other locking strategy is available.
25995 ** Dotfile locking works by creating a file in the same directory as the
25996 ** database and with the same name but with a ".lock" extension added.
25997 ** The existance of a lock file implies an EXCLUSIVE lock. All other lock
25998 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
26002 ** The file suffix added to the data base filename in order to create the
26003 ** lock file.
26005 #define DOTLOCK_SUFFIX ".lock"
26008 ** This routine checks if there is a RESERVED lock held on the specified
26009 ** file by this or any other process. If such a lock is held, set *pResOut
26010 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26011 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26013 ** In dotfile locking, either a lock exists or it does not. So in this
26014 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
26015 ** is held on the file and false if the file is unlocked.
26017 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
26018 int rc = SQLITE_OK;
26019 int reserved = 0;
26020 unixFile *pFile = (unixFile*)id;
26022 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26024 assert( pFile );
26026 /* Check if a thread in this process holds such a lock */
26027 if( pFile->eFileLock>SHARED_LOCK ){
26028 /* Either this connection or some other connection in the same process
26029 ** holds a lock on the file. No need to check further. */
26030 reserved = 1;
26031 }else{
26032 /* The lock is held if and only if the lockfile exists */
26033 const char *zLockFile = (const char*)pFile->lockingContext;
26034 reserved = osAccess(zLockFile, 0)==0;
26036 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26037 *pResOut = reserved;
26038 return rc;
26042 ** Lock the file with the lock specified by parameter eFileLock - one
26043 ** of the following:
26045 ** (1) SHARED_LOCK
26046 ** (2) RESERVED_LOCK
26047 ** (3) PENDING_LOCK
26048 ** (4) EXCLUSIVE_LOCK
26050 ** Sometimes when requesting one lock state, additional lock states
26051 ** are inserted in between. The locking might fail on one of the later
26052 ** transitions leaving the lock state different from what it started but
26053 ** still short of its goal. The following chart shows the allowed
26054 ** transitions and the inserted intermediate states:
26056 ** UNLOCKED -> SHARED
26057 ** SHARED -> RESERVED
26058 ** SHARED -> (PENDING) -> EXCLUSIVE
26059 ** RESERVED -> (PENDING) -> EXCLUSIVE
26060 ** PENDING -> EXCLUSIVE
26062 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26063 ** routine to lower a locking level.
26065 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
26066 ** But we track the other locking levels internally.
26068 static int dotlockLock(sqlite3_file *id, int eFileLock) {
26069 unixFile *pFile = (unixFile*)id;
26070 int fd;
26071 char *zLockFile = (char *)pFile->lockingContext;
26072 int rc = SQLITE_OK;
26075 /* If we have any lock, then the lock file already exists. All we have
26076 ** to do is adjust our internal record of the lock level.
26078 if( pFile->eFileLock > NO_LOCK ){
26079 pFile->eFileLock = eFileLock;
26080 #if !OS_VXWORKS
26081 /* Always update the timestamp on the old file */
26082 utimes(zLockFile, NULL);
26083 #endif
26084 return SQLITE_OK;
26087 /* grab an exclusive lock */
26088 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
26089 if( fd<0 ){
26090 /* failed to open/create the file, someone else may have stolen the lock */
26091 int tErrno = errno;
26092 if( EEXIST == tErrno ){
26093 rc = SQLITE_BUSY;
26094 } else {
26095 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26096 if( IS_LOCK_ERROR(rc) ){
26097 pFile->lastErrno = tErrno;
26100 return rc;
26102 robust_close(pFile, fd, __LINE__);
26104 /* got it, set the type and return ok */
26105 pFile->eFileLock = eFileLock;
26106 return rc;
26110 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26111 ** must be either NO_LOCK or SHARED_LOCK.
26113 ** If the locking level of the file descriptor is already at or below
26114 ** the requested locking level, this routine is a no-op.
26116 ** When the locking level reaches NO_LOCK, delete the lock file.
26118 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
26119 unixFile *pFile = (unixFile*)id;
26120 char *zLockFile = (char *)pFile->lockingContext;
26122 assert( pFile );
26123 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
26124 pFile->eFileLock, getpid()));
26125 assert( eFileLock<=SHARED_LOCK );
26127 /* no-op if possible */
26128 if( pFile->eFileLock==eFileLock ){
26129 return SQLITE_OK;
26132 /* To downgrade to shared, simply update our internal notion of the
26133 ** lock state. No need to mess with the file on disk.
26135 if( eFileLock==SHARED_LOCK ){
26136 pFile->eFileLock = SHARED_LOCK;
26137 return SQLITE_OK;
26140 /* To fully unlock the database, delete the lock file */
26141 assert( eFileLock==NO_LOCK );
26142 if( osUnlink(zLockFile) ){
26143 int rc = 0;
26144 int tErrno = errno;
26145 if( ENOENT != tErrno ){
26146 rc = SQLITE_IOERR_UNLOCK;
26148 if( IS_LOCK_ERROR(rc) ){
26149 pFile->lastErrno = tErrno;
26151 return rc;
26153 pFile->eFileLock = NO_LOCK;
26154 return SQLITE_OK;
26158 ** Close a file. Make sure the lock has been released before closing.
26160 static int dotlockClose(sqlite3_file *id) {
26161 int rc;
26162 if( id ){
26163 unixFile *pFile = (unixFile*)id;
26164 dotlockUnlock(id, NO_LOCK);
26165 sqlite3_free(pFile->lockingContext);
26167 rc = closeUnixFile(id);
26168 return rc;
26170 /****************** End of the dot-file lock implementation *******************
26171 ******************************************************************************/
26173 /******************************************************************************
26174 ************************** Begin flock Locking ********************************
26176 ** Use the flock() system call to do file locking.
26178 ** flock() locking is like dot-file locking in that the various
26179 ** fine-grain locking levels supported by SQLite are collapsed into
26180 ** a single exclusive lock. In other words, SHARED, RESERVED, and
26181 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
26182 ** still works when you do this, but concurrency is reduced since
26183 ** only a single process can be reading the database at a time.
26185 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
26186 ** compiling for VXWORKS.
26188 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26191 ** Retry flock() calls that fail with EINTR
26193 #ifdef EINTR
26194 static int robust_flock(int fd, int op){
26195 int rc;
26196 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
26197 return rc;
26199 #else
26200 # define robust_flock(a,b) flock(a,b)
26201 #endif
26205 ** This routine checks if there is a RESERVED lock held on the specified
26206 ** file by this or any other process. If such a lock is held, set *pResOut
26207 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26208 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26210 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
26211 int rc = SQLITE_OK;
26212 int reserved = 0;
26213 unixFile *pFile = (unixFile*)id;
26215 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26217 assert( pFile );
26219 /* Check if a thread in this process holds such a lock */
26220 if( pFile->eFileLock>SHARED_LOCK ){
26221 reserved = 1;
26224 /* Otherwise see if some other process holds it. */
26225 if( !reserved ){
26226 /* attempt to get the lock */
26227 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
26228 if( !lrc ){
26229 /* got the lock, unlock it */
26230 lrc = robust_flock(pFile->h, LOCK_UN);
26231 if ( lrc ) {
26232 int tErrno = errno;
26233 /* unlock failed with an error */
26234 lrc = SQLITE_IOERR_UNLOCK;
26235 if( IS_LOCK_ERROR(lrc) ){
26236 pFile->lastErrno = tErrno;
26237 rc = lrc;
26240 } else {
26241 int tErrno = errno;
26242 reserved = 1;
26243 /* someone else might have it reserved */
26244 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26245 if( IS_LOCK_ERROR(lrc) ){
26246 pFile->lastErrno = tErrno;
26247 rc = lrc;
26251 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
26253 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26254 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26255 rc = SQLITE_OK;
26256 reserved=1;
26258 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26259 *pResOut = reserved;
26260 return rc;
26264 ** Lock the file with the lock specified by parameter eFileLock - one
26265 ** of the following:
26267 ** (1) SHARED_LOCK
26268 ** (2) RESERVED_LOCK
26269 ** (3) PENDING_LOCK
26270 ** (4) EXCLUSIVE_LOCK
26272 ** Sometimes when requesting one lock state, additional lock states
26273 ** are inserted in between. The locking might fail on one of the later
26274 ** transitions leaving the lock state different from what it started but
26275 ** still short of its goal. The following chart shows the allowed
26276 ** transitions and the inserted intermediate states:
26278 ** UNLOCKED -> SHARED
26279 ** SHARED -> RESERVED
26280 ** SHARED -> (PENDING) -> EXCLUSIVE
26281 ** RESERVED -> (PENDING) -> EXCLUSIVE
26282 ** PENDING -> EXCLUSIVE
26284 ** flock() only really support EXCLUSIVE locks. We track intermediate
26285 ** lock states in the sqlite3_file structure, but all locks SHARED or
26286 ** above are really EXCLUSIVE locks and exclude all other processes from
26287 ** access the file.
26289 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26290 ** routine to lower a locking level.
26292 static int flockLock(sqlite3_file *id, int eFileLock) {
26293 int rc = SQLITE_OK;
26294 unixFile *pFile = (unixFile*)id;
26296 assert( pFile );
26298 /* if we already have a lock, it is exclusive.
26299 ** Just adjust level and punt on outta here. */
26300 if (pFile->eFileLock > NO_LOCK) {
26301 pFile->eFileLock = eFileLock;
26302 return SQLITE_OK;
26305 /* grab an exclusive lock */
26307 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
26308 int tErrno = errno;
26309 /* didn't get, must be busy */
26310 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26311 if( IS_LOCK_ERROR(rc) ){
26312 pFile->lastErrno = tErrno;
26314 } else {
26315 /* got it, set the type and return ok */
26316 pFile->eFileLock = eFileLock;
26318 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
26319 rc==SQLITE_OK ? "ok" : "failed"));
26320 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26321 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26322 rc = SQLITE_BUSY;
26324 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26325 return rc;
26330 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26331 ** must be either NO_LOCK or SHARED_LOCK.
26333 ** If the locking level of the file descriptor is already at or below
26334 ** the requested locking level, this routine is a no-op.
26336 static int flockUnlock(sqlite3_file *id, int eFileLock) {
26337 unixFile *pFile = (unixFile*)id;
26339 assert( pFile );
26340 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
26341 pFile->eFileLock, getpid()));
26342 assert( eFileLock<=SHARED_LOCK );
26344 /* no-op if possible */
26345 if( pFile->eFileLock==eFileLock ){
26346 return SQLITE_OK;
26349 /* shared can just be set because we always have an exclusive */
26350 if (eFileLock==SHARED_LOCK) {
26351 pFile->eFileLock = eFileLock;
26352 return SQLITE_OK;
26355 /* no, really, unlock. */
26356 if( robust_flock(pFile->h, LOCK_UN) ){
26357 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26358 return SQLITE_OK;
26359 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26360 return SQLITE_IOERR_UNLOCK;
26361 }else{
26362 pFile->eFileLock = NO_LOCK;
26363 return SQLITE_OK;
26368 ** Close a file.
26370 static int flockClose(sqlite3_file *id) {
26371 if( id ){
26372 flockUnlock(id, NO_LOCK);
26374 return closeUnixFile(id);
26377 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
26379 /******************* End of the flock lock implementation *********************
26380 ******************************************************************************/
26382 /******************************************************************************
26383 ************************ Begin Named Semaphore Locking ************************
26385 ** Named semaphore locking is only supported on VxWorks.
26387 ** Semaphore locking is like dot-lock and flock in that it really only
26388 ** supports EXCLUSIVE locking. Only a single process can read or write
26389 ** the database file at a time. This reduces potential concurrency, but
26390 ** makes the lock implementation much easier.
26392 #if OS_VXWORKS
26395 ** This routine checks if there is a RESERVED lock held on the specified
26396 ** file by this or any other process. If such a lock is held, set *pResOut
26397 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26398 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26400 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
26401 int rc = SQLITE_OK;
26402 int reserved = 0;
26403 unixFile *pFile = (unixFile*)id;
26405 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26407 assert( pFile );
26409 /* Check if a thread in this process holds such a lock */
26410 if( pFile->eFileLock>SHARED_LOCK ){
26411 reserved = 1;
26414 /* Otherwise see if some other process holds it. */
26415 if( !reserved ){
26416 sem_t *pSem = pFile->pInode->pSem;
26417 struct stat statBuf;
26419 if( sem_trywait(pSem)==-1 ){
26420 int tErrno = errno;
26421 if( EAGAIN != tErrno ){
26422 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
26423 pFile->lastErrno = tErrno;
26424 } else {
26425 /* someone else has the lock when we are in NO_LOCK */
26426 reserved = (pFile->eFileLock < SHARED_LOCK);
26428 }else{
26429 /* we could have it if we want it */
26430 sem_post(pSem);
26433 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
26435 *pResOut = reserved;
26436 return rc;
26440 ** Lock the file with the lock specified by parameter eFileLock - one
26441 ** of the following:
26443 ** (1) SHARED_LOCK
26444 ** (2) RESERVED_LOCK
26445 ** (3) PENDING_LOCK
26446 ** (4) EXCLUSIVE_LOCK
26448 ** Sometimes when requesting one lock state, additional lock states
26449 ** are inserted in between. The locking might fail on one of the later
26450 ** transitions leaving the lock state different from what it started but
26451 ** still short of its goal. The following chart shows the allowed
26452 ** transitions and the inserted intermediate states:
26454 ** UNLOCKED -> SHARED
26455 ** SHARED -> RESERVED
26456 ** SHARED -> (PENDING) -> EXCLUSIVE
26457 ** RESERVED -> (PENDING) -> EXCLUSIVE
26458 ** PENDING -> EXCLUSIVE
26460 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
26461 ** lock states in the sqlite3_file structure, but all locks SHARED or
26462 ** above are really EXCLUSIVE locks and exclude all other processes from
26463 ** access the file.
26465 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26466 ** routine to lower a locking level.
26468 static int semLock(sqlite3_file *id, int eFileLock) {
26469 unixFile *pFile = (unixFile*)id;
26470 int fd;
26471 sem_t *pSem = pFile->pInode->pSem;
26472 int rc = SQLITE_OK;
26474 /* if we already have a lock, it is exclusive.
26475 ** Just adjust level and punt on outta here. */
26476 if (pFile->eFileLock > NO_LOCK) {
26477 pFile->eFileLock = eFileLock;
26478 rc = SQLITE_OK;
26479 goto sem_end_lock;
26482 /* lock semaphore now but bail out when already locked. */
26483 if( sem_trywait(pSem)==-1 ){
26484 rc = SQLITE_BUSY;
26485 goto sem_end_lock;
26488 /* got it, set the type and return ok */
26489 pFile->eFileLock = eFileLock;
26491 sem_end_lock:
26492 return rc;
26496 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26497 ** must be either NO_LOCK or SHARED_LOCK.
26499 ** If the locking level of the file descriptor is already at or below
26500 ** the requested locking level, this routine is a no-op.
26502 static int semUnlock(sqlite3_file *id, int eFileLock) {
26503 unixFile *pFile = (unixFile*)id;
26504 sem_t *pSem = pFile->pInode->pSem;
26506 assert( pFile );
26507 assert( pSem );
26508 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
26509 pFile->eFileLock, getpid()));
26510 assert( eFileLock<=SHARED_LOCK );
26512 /* no-op if possible */
26513 if( pFile->eFileLock==eFileLock ){
26514 return SQLITE_OK;
26517 /* shared can just be set because we always have an exclusive */
26518 if (eFileLock==SHARED_LOCK) {
26519 pFile->eFileLock = eFileLock;
26520 return SQLITE_OK;
26523 /* no, really unlock. */
26524 if ( sem_post(pSem)==-1 ) {
26525 int rc, tErrno = errno;
26526 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
26527 if( IS_LOCK_ERROR(rc) ){
26528 pFile->lastErrno = tErrno;
26530 return rc;
26532 pFile->eFileLock = NO_LOCK;
26533 return SQLITE_OK;
26537 ** Close a file.
26539 static int semClose(sqlite3_file *id) {
26540 if( id ){
26541 unixFile *pFile = (unixFile*)id;
26542 semUnlock(id, NO_LOCK);
26543 assert( pFile );
26544 unixEnterMutex();
26545 releaseInodeInfo(pFile);
26546 unixLeaveMutex();
26547 closeUnixFile(id);
26549 return SQLITE_OK;
26552 #endif /* OS_VXWORKS */
26554 ** Named semaphore locking is only available on VxWorks.
26556 *************** End of the named semaphore lock implementation ****************
26557 ******************************************************************************/
26560 /******************************************************************************
26561 *************************** Begin AFP Locking *********************************
26563 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
26564 ** on Apple Macintosh computers - both OS9 and OSX.
26566 ** Third-party implementations of AFP are available. But this code here
26567 ** only works on OSX.
26570 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26572 ** The afpLockingContext structure contains all afp lock specific state
26574 typedef struct afpLockingContext afpLockingContext;
26575 struct afpLockingContext {
26576 int reserved;
26577 const char *dbPath; /* Name of the open file */
26580 struct ByteRangeLockPB2
26582 unsigned long long offset; /* offset to first byte to lock */
26583 unsigned long long length; /* nbr of bytes to lock */
26584 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
26585 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
26586 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
26587 int fd; /* file desc to assoc this lock with */
26590 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
26593 ** This is a utility for setting or clearing a bit-range lock on an
26594 ** AFP filesystem.
26596 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
26598 static int afpSetLock(
26599 const char *path, /* Name of the file to be locked or unlocked */
26600 unixFile *pFile, /* Open file descriptor on path */
26601 unsigned long long offset, /* First byte to be locked */
26602 unsigned long long length, /* Number of bytes to lock */
26603 int setLockFlag /* True to set lock. False to clear lock */
26605 struct ByteRangeLockPB2 pb;
26606 int err;
26608 pb.unLockFlag = setLockFlag ? 0 : 1;
26609 pb.startEndFlag = 0;
26610 pb.offset = offset;
26611 pb.length = length;
26612 pb.fd = pFile->h;
26614 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
26615 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
26616 offset, length));
26617 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
26618 if ( err==-1 ) {
26619 int rc;
26620 int tErrno = errno;
26621 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
26622 path, tErrno, strerror(tErrno)));
26623 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
26624 rc = SQLITE_BUSY;
26625 #else
26626 rc = sqliteErrorFromPosixError(tErrno,
26627 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
26628 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
26629 if( IS_LOCK_ERROR(rc) ){
26630 pFile->lastErrno = tErrno;
26632 return rc;
26633 } else {
26634 return SQLITE_OK;
26639 ** This routine checks if there is a RESERVED lock held on the specified
26640 ** file by this or any other process. If such a lock is held, set *pResOut
26641 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26642 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26644 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
26645 int rc = SQLITE_OK;
26646 int reserved = 0;
26647 unixFile *pFile = (unixFile*)id;
26649 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26651 assert( pFile );
26652 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26653 if( context->reserved ){
26654 *pResOut = 1;
26655 return SQLITE_OK;
26657 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26659 /* Check if a thread in this process holds such a lock */
26660 if( pFile->pInode->eFileLock>SHARED_LOCK ){
26661 reserved = 1;
26664 /* Otherwise see if some other process holds it.
26666 if( !reserved ){
26667 /* lock the RESERVED byte */
26668 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26669 if( SQLITE_OK==lrc ){
26670 /* if we succeeded in taking the reserved lock, unlock it to restore
26671 ** the original state */
26672 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26673 } else {
26674 /* if we failed to get the lock then someone else must have it */
26675 reserved = 1;
26677 if( IS_LOCK_ERROR(lrc) ){
26678 rc=lrc;
26682 unixLeaveMutex();
26683 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
26685 *pResOut = reserved;
26686 return rc;
26690 ** Lock the file with the lock specified by parameter eFileLock - one
26691 ** of the following:
26693 ** (1) SHARED_LOCK
26694 ** (2) RESERVED_LOCK
26695 ** (3) PENDING_LOCK
26696 ** (4) EXCLUSIVE_LOCK
26698 ** Sometimes when requesting one lock state, additional lock states
26699 ** are inserted in between. The locking might fail on one of the later
26700 ** transitions leaving the lock state different from what it started but
26701 ** still short of its goal. The following chart shows the allowed
26702 ** transitions and the inserted intermediate states:
26704 ** UNLOCKED -> SHARED
26705 ** SHARED -> RESERVED
26706 ** SHARED -> (PENDING) -> EXCLUSIVE
26707 ** RESERVED -> (PENDING) -> EXCLUSIVE
26708 ** PENDING -> EXCLUSIVE
26710 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26711 ** routine to lower a locking level.
26713 static int afpLock(sqlite3_file *id, int eFileLock){
26714 int rc = SQLITE_OK;
26715 unixFile *pFile = (unixFile*)id;
26716 unixInodeInfo *pInode = pFile->pInode;
26717 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26719 assert( pFile );
26720 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
26721 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26722 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
26724 /* If there is already a lock of this type or more restrictive on the
26725 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
26726 ** unixEnterMutex() hasn't been called yet.
26728 if( pFile->eFileLock>=eFileLock ){
26729 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
26730 azFileLock(eFileLock)));
26731 return SQLITE_OK;
26734 /* Make sure the locking sequence is correct
26735 ** (1) We never move from unlocked to anything higher than shared lock.
26736 ** (2) SQLite never explicitly requests a pendig lock.
26737 ** (3) A shared lock is always held when a reserve lock is requested.
26739 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26740 assert( eFileLock!=PENDING_LOCK );
26741 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26743 /* This mutex is needed because pFile->pInode is shared across threads
26745 unixEnterMutex();
26746 pInode = pFile->pInode;
26748 /* If some thread using this PID has a lock via a different unixFile*
26749 ** handle that precludes the requested lock, return BUSY.
26751 if( (pFile->eFileLock!=pInode->eFileLock &&
26752 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26754 rc = SQLITE_BUSY;
26755 goto afp_end_lock;
26758 /* If a SHARED lock is requested, and some thread using this PID already
26759 ** has a SHARED or RESERVED lock, then increment reference counts and
26760 ** return SQLITE_OK.
26762 if( eFileLock==SHARED_LOCK &&
26763 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26764 assert( eFileLock==SHARED_LOCK );
26765 assert( pFile->eFileLock==0 );
26766 assert( pInode->nShared>0 );
26767 pFile->eFileLock = SHARED_LOCK;
26768 pInode->nShared++;
26769 pInode->nLock++;
26770 goto afp_end_lock;
26773 /* A PENDING lock is needed before acquiring a SHARED lock and before
26774 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
26775 ** be released.
26777 if( eFileLock==SHARED_LOCK
26778 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26780 int failed;
26781 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
26782 if (failed) {
26783 rc = failed;
26784 goto afp_end_lock;
26788 /* If control gets to this point, then actually go ahead and make
26789 ** operating system calls for the specified lock.
26791 if( eFileLock==SHARED_LOCK ){
26792 int lrc1, lrc2, lrc1Errno;
26793 long lk, mask;
26795 assert( pInode->nShared==0 );
26796 assert( pInode->eFileLock==0 );
26798 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
26799 /* Now get the read-lock SHARED_LOCK */
26800 /* note that the quality of the randomness doesn't matter that much */
26801 lk = random();
26802 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
26803 lrc1 = afpSetLock(context->dbPath, pFile,
26804 SHARED_FIRST+pInode->sharedByte, 1, 1);
26805 if( IS_LOCK_ERROR(lrc1) ){
26806 lrc1Errno = pFile->lastErrno;
26808 /* Drop the temporary PENDING lock */
26809 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26811 if( IS_LOCK_ERROR(lrc1) ) {
26812 pFile->lastErrno = lrc1Errno;
26813 rc = lrc1;
26814 goto afp_end_lock;
26815 } else if( IS_LOCK_ERROR(lrc2) ){
26816 rc = lrc2;
26817 goto afp_end_lock;
26818 } else if( lrc1 != SQLITE_OK ) {
26819 rc = lrc1;
26820 } else {
26821 pFile->eFileLock = SHARED_LOCK;
26822 pInode->nLock++;
26823 pInode->nShared = 1;
26825 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26826 /* We are trying for an exclusive lock but another thread in this
26827 ** same process is still holding a shared lock. */
26828 rc = SQLITE_BUSY;
26829 }else{
26830 /* The request was for a RESERVED or EXCLUSIVE lock. It is
26831 ** assumed that there is a SHARED or greater lock on the file
26832 ** already.
26834 int failed = 0;
26835 assert( 0!=pFile->eFileLock );
26836 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
26837 /* Acquire a RESERVED lock */
26838 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26839 if( !failed ){
26840 context->reserved = 1;
26843 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
26844 /* Acquire an EXCLUSIVE lock */
26846 /* Remove the shared lock before trying the range. we'll need to
26847 ** reestablish the shared lock if we can't get the afpUnlock
26849 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
26850 pInode->sharedByte, 1, 0)) ){
26851 int failed2 = SQLITE_OK;
26852 /* now attemmpt to get the exclusive lock range */
26853 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
26854 SHARED_SIZE, 1);
26855 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
26856 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
26857 /* Can't reestablish the shared lock. Sqlite can't deal, this is
26858 ** a critical I/O error
26860 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
26861 SQLITE_IOERR_LOCK;
26862 goto afp_end_lock;
26864 }else{
26865 rc = failed;
26868 if( failed ){
26869 rc = failed;
26873 if( rc==SQLITE_OK ){
26874 pFile->eFileLock = eFileLock;
26875 pInode->eFileLock = eFileLock;
26876 }else if( eFileLock==EXCLUSIVE_LOCK ){
26877 pFile->eFileLock = PENDING_LOCK;
26878 pInode->eFileLock = PENDING_LOCK;
26881 afp_end_lock:
26882 unixLeaveMutex();
26883 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
26884 rc==SQLITE_OK ? "ok" : "failed"));
26885 return rc;
26889 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26890 ** must be either NO_LOCK or SHARED_LOCK.
26892 ** If the locking level of the file descriptor is already at or below
26893 ** the requested locking level, this routine is a no-op.
26895 static int afpUnlock(sqlite3_file *id, int eFileLock) {
26896 int rc = SQLITE_OK;
26897 unixFile *pFile = (unixFile*)id;
26898 unixInodeInfo *pInode;
26899 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26900 int skipShared = 0;
26901 #ifdef SQLITE_TEST
26902 int h = pFile->h;
26903 #endif
26905 assert( pFile );
26906 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
26907 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26908 getpid()));
26910 assert( eFileLock<=SHARED_LOCK );
26911 if( pFile->eFileLock<=eFileLock ){
26912 return SQLITE_OK;
26914 unixEnterMutex();
26915 pInode = pFile->pInode;
26916 assert( pInode->nShared!=0 );
26917 if( pFile->eFileLock>SHARED_LOCK ){
26918 assert( pInode->eFileLock==pFile->eFileLock );
26919 SimulateIOErrorBenign(1);
26920 SimulateIOError( h=(-1) )
26921 SimulateIOErrorBenign(0);
26923 #ifndef NDEBUG
26924 /* When reducing a lock such that other processes can start
26925 ** reading the database file again, make sure that the
26926 ** transaction counter was updated if any part of the database
26927 ** file changed. If the transaction counter is not updated,
26928 ** other connections to the same file might not realize that
26929 ** the file has changed and hence might not know to flush their
26930 ** cache. The use of a stale cache can lead to database corruption.
26932 assert( pFile->inNormalWrite==0
26933 || pFile->dbUpdate==0
26934 || pFile->transCntrChng==1 );
26935 pFile->inNormalWrite = 0;
26936 #endif
26938 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
26939 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
26940 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
26941 /* only re-establish the shared lock if necessary */
26942 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26943 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
26944 } else {
26945 skipShared = 1;
26948 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
26949 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26951 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
26952 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26953 if( !rc ){
26954 context->reserved = 0;
26957 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
26958 pInode->eFileLock = SHARED_LOCK;
26961 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
26963 /* Decrement the shared lock counter. Release the lock using an
26964 ** OS call only when all threads in this same process have released
26965 ** the lock.
26967 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26968 pInode->nShared--;
26969 if( pInode->nShared==0 ){
26970 SimulateIOErrorBenign(1);
26971 SimulateIOError( h=(-1) )
26972 SimulateIOErrorBenign(0);
26973 if( !skipShared ){
26974 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
26976 if( !rc ){
26977 pInode->eFileLock = NO_LOCK;
26978 pFile->eFileLock = NO_LOCK;
26981 if( rc==SQLITE_OK ){
26982 pInode->nLock--;
26983 assert( pInode->nLock>=0 );
26984 if( pInode->nLock==0 ){
26985 closePendingFds(pFile);
26990 unixLeaveMutex();
26991 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26992 return rc;
26996 ** Close a file & cleanup AFP specific locking context
26998 static int afpClose(sqlite3_file *id) {
26999 int rc = SQLITE_OK;
27000 if( id ){
27001 unixFile *pFile = (unixFile*)id;
27002 afpUnlock(id, NO_LOCK);
27003 unixEnterMutex();
27004 if( pFile->pInode && pFile->pInode->nLock ){
27005 /* If there are outstanding locks, do not actually close the file just
27006 ** yet because that would clear those locks. Instead, add the file
27007 ** descriptor to pInode->aPending. It will be automatically closed when
27008 ** the last lock is cleared.
27010 setPendingFd(pFile);
27012 releaseInodeInfo(pFile);
27013 sqlite3_free(pFile->lockingContext);
27014 rc = closeUnixFile(id);
27015 unixLeaveMutex();
27017 return rc;
27020 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27022 ** The code above is the AFP lock implementation. The code is specific
27023 ** to MacOSX and does not work on other unix platforms. No alternative
27024 ** is available. If you don't compile for a mac, then the "unix-afp"
27025 ** VFS is not available.
27027 ********************* End of the AFP lock implementation **********************
27028 ******************************************************************************/
27030 /******************************************************************************
27031 *************************** Begin NFS Locking ********************************/
27033 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27035 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27036 ** must be either NO_LOCK or SHARED_LOCK.
27038 ** If the locking level of the file descriptor is already at or below
27039 ** the requested locking level, this routine is a no-op.
27041 static int nfsUnlock(sqlite3_file *id, int eFileLock){
27042 return posixUnlock(id, eFileLock, 1);
27045 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27047 ** The code above is the NFS lock implementation. The code is specific
27048 ** to MacOSX and does not work on other unix platforms. No alternative
27049 ** is available.
27051 ********************* End of the NFS lock implementation **********************
27052 ******************************************************************************/
27054 /******************************************************************************
27055 **************** Non-locking sqlite3_file methods *****************************
27057 ** The next division contains implementations for all methods of the
27058 ** sqlite3_file object other than the locking methods. The locking
27059 ** methods were defined in divisions above (one locking method per
27060 ** division). Those methods that are common to all locking modes
27061 ** are gather together into this division.
27065 ** Seek to the offset passed as the second argument, then read cnt
27066 ** bytes into pBuf. Return the number of bytes actually read.
27068 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
27069 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
27070 ** one system to another. Since SQLite does not define USE_PREAD
27071 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
27072 ** See tickets #2741 and #2681.
27074 ** To avoid stomping the errno value on a failed read the lastErrno value
27075 ** is set before returning.
27077 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
27078 int got;
27079 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27080 i64 newOffset;
27081 #endif
27082 TIMER_START;
27083 #if defined(USE_PREAD)
27084 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27085 SimulateIOError( got = -1 );
27086 #elif defined(USE_PREAD64)
27087 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
27088 SimulateIOError( got = -1 );
27089 #else
27090 newOffset = lseek(id->h, offset, SEEK_SET);
27091 SimulateIOError( newOffset-- );
27092 if( newOffset!=offset ){
27093 if( newOffset == -1 ){
27094 ((unixFile*)id)->lastErrno = errno;
27095 }else{
27096 ((unixFile*)id)->lastErrno = 0;
27098 return -1;
27100 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27101 #endif
27102 TIMER_END;
27103 if( got<0 ){
27104 ((unixFile*)id)->lastErrno = errno;
27106 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27107 return got;
27111 ** Read data from a file into a buffer. Return SQLITE_OK if all
27112 ** bytes were read successfully and SQLITE_IOERR if anything goes
27113 ** wrong.
27115 static int unixRead(
27116 sqlite3_file *id,
27117 void *pBuf,
27118 int amt,
27119 sqlite3_int64 offset
27121 unixFile *pFile = (unixFile *)id;
27122 int got;
27123 assert( id );
27125 /* If this is a database file (not a journal, master-journal or temp
27126 ** file), the bytes in the locking range should never be read or written. */
27127 #if 0
27128 assert( pFile->pUnused==0
27129 || offset>=PENDING_BYTE+512
27130 || offset+amt<=PENDING_BYTE
27132 #endif
27134 got = seekAndRead(pFile, offset, pBuf, amt);
27135 if( got==amt ){
27136 return SQLITE_OK;
27137 }else if( got<0 ){
27138 /* lastErrno set by seekAndRead */
27139 return SQLITE_IOERR_READ;
27140 }else{
27141 pFile->lastErrno = 0; /* not a system error */
27142 /* Unread parts of the buffer must be zero-filled */
27143 memset(&((char*)pBuf)[got], 0, amt-got);
27144 return SQLITE_IOERR_SHORT_READ;
27149 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
27150 ** Return the number of bytes actually read. Update the offset.
27152 ** To avoid stomping the errno value on a failed write the lastErrno value
27153 ** is set before returning.
27155 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
27156 int got;
27157 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27158 i64 newOffset;
27159 #endif
27160 TIMER_START;
27161 #if defined(USE_PREAD)
27162 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27163 #elif defined(USE_PREAD64)
27164 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
27165 #else
27166 newOffset = lseek(id->h, offset, SEEK_SET);
27167 SimulateIOError( newOffset-- );
27168 if( newOffset!=offset ){
27169 if( newOffset == -1 ){
27170 ((unixFile*)id)->lastErrno = errno;
27171 }else{
27172 ((unixFile*)id)->lastErrno = 0;
27174 return -1;
27176 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27177 #endif
27178 TIMER_END;
27179 if( got<0 ){
27180 ((unixFile*)id)->lastErrno = errno;
27183 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27184 return got;
27189 ** Write data from a buffer into a file. Return SQLITE_OK on success
27190 ** or some other error code on failure.
27192 static int unixWrite(
27193 sqlite3_file *id,
27194 const void *pBuf,
27195 int amt,
27196 sqlite3_int64 offset
27198 unixFile *pFile = (unixFile*)id;
27199 int wrote = 0;
27200 assert( id );
27201 assert( amt>0 );
27203 /* If this is a database file (not a journal, master-journal or temp
27204 ** file), the bytes in the locking range should never be read or written. */
27205 #if 0
27206 assert( pFile->pUnused==0
27207 || offset>=PENDING_BYTE+512
27208 || offset+amt<=PENDING_BYTE
27210 #endif
27212 #ifndef NDEBUG
27213 /* If we are doing a normal write to a database file (as opposed to
27214 ** doing a hot-journal rollback or a write to some file other than a
27215 ** normal database file) then record the fact that the database
27216 ** has changed. If the transaction counter is modified, record that
27217 ** fact too.
27219 if( pFile->inNormalWrite ){
27220 pFile->dbUpdate = 1; /* The database has been modified */
27221 if( offset<=24 && offset+amt>=27 ){
27222 int rc;
27223 char oldCntr[4];
27224 SimulateIOErrorBenign(1);
27225 rc = seekAndRead(pFile, 24, oldCntr, 4);
27226 SimulateIOErrorBenign(0);
27227 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
27228 pFile->transCntrChng = 1; /* The transaction counter has changed */
27232 #endif
27234 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
27235 amt -= wrote;
27236 offset += wrote;
27237 pBuf = &((char*)pBuf)[wrote];
27239 SimulateIOError(( wrote=(-1), amt=1 ));
27240 SimulateDiskfullError(( wrote=0, amt=1 ));
27242 if( amt>0 ){
27243 if( wrote<0 ){
27244 /* lastErrno set by seekAndWrite */
27245 return SQLITE_IOERR_WRITE;
27246 }else{
27247 pFile->lastErrno = 0; /* not a system error */
27248 return SQLITE_FULL;
27252 return SQLITE_OK;
27255 #ifdef SQLITE_TEST
27257 ** Count the number of fullsyncs and normal syncs. This is used to test
27258 ** that syncs and fullsyncs are occurring at the right times.
27260 SQLITE_API int sqlite3_sync_count = 0;
27261 SQLITE_API int sqlite3_fullsync_count = 0;
27262 #endif
27265 ** We do not trust systems to provide a working fdatasync(). Some do.
27266 ** Others do no. To be safe, we will stick with the (slower) fsync().
27267 ** If you know that your system does support fdatasync() correctly,
27268 ** then simply compile with -Dfdatasync=fdatasync
27270 #if !defined(fdatasync) && !defined(__linux__)
27271 # define fdatasync fsync
27272 #endif
27275 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
27276 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
27277 ** only available on Mac OS X. But that could change.
27279 #ifdef F_FULLFSYNC
27280 # define HAVE_FULLFSYNC 1
27281 #else
27282 # define HAVE_FULLFSYNC 0
27283 #endif
27287 ** The fsync() system call does not work as advertised on many
27288 ** unix systems. The following procedure is an attempt to make
27289 ** it work better.
27291 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
27292 ** for testing when we want to run through the test suite quickly.
27293 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
27294 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
27295 ** or power failure will likely corrupt the database file.
27297 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
27298 ** The idea behind dataOnly is that it should only write the file content
27299 ** to disk, not the inode. We only set dataOnly if the file size is
27300 ** unchanged since the file size is part of the inode. However,
27301 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
27302 ** file size has changed. The only real difference between fdatasync()
27303 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
27304 ** inode if the mtime or owner or other inode attributes have changed.
27305 ** We only care about the file size, not the other file attributes, so
27306 ** as far as SQLite is concerned, an fdatasync() is always adequate.
27307 ** So, we always use fdatasync() if it is available, regardless of
27308 ** the value of the dataOnly flag.
27310 static int full_fsync(int fd, int fullSync, int dataOnly){
27311 int rc;
27313 /* The following "ifdef/elif/else/" block has the same structure as
27314 ** the one below. It is replicated here solely to avoid cluttering
27315 ** up the real code with the UNUSED_PARAMETER() macros.
27317 #ifdef SQLITE_NO_SYNC
27318 UNUSED_PARAMETER(fd);
27319 UNUSED_PARAMETER(fullSync);
27320 UNUSED_PARAMETER(dataOnly);
27321 #elif HAVE_FULLFSYNC
27322 UNUSED_PARAMETER(dataOnly);
27323 #else
27324 UNUSED_PARAMETER(fullSync);
27325 UNUSED_PARAMETER(dataOnly);
27326 #endif
27328 /* Record the number of times that we do a normal fsync() and
27329 ** FULLSYNC. This is used during testing to verify that this procedure
27330 ** gets called with the correct arguments.
27332 #ifdef SQLITE_TEST
27333 if( fullSync ) sqlite3_fullsync_count++;
27334 sqlite3_sync_count++;
27335 #endif
27337 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27338 ** no-op
27340 #ifdef SQLITE_NO_SYNC
27341 rc = SQLITE_OK;
27342 #elif HAVE_FULLFSYNC
27343 if( fullSync ){
27344 rc = osFcntl(fd, F_FULLFSYNC, 0);
27345 }else{
27346 rc = 1;
27348 /* If the FULLFSYNC failed, fall back to attempting an fsync().
27349 ** It shouldn't be possible for fullfsync to fail on the local
27350 ** file system (on OSX), so failure indicates that FULLFSYNC
27351 ** isn't supported for this file system. So, attempt an fsync
27352 ** and (for now) ignore the overhead of a superfluous fcntl call.
27353 ** It'd be better to detect fullfsync support once and avoid
27354 ** the fcntl call every time sync is called.
27356 if( rc ) rc = fsync(fd);
27358 #elif defined(__APPLE__)
27359 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
27360 ** so currently we default to the macro that redefines fdatasync to fsync
27362 rc = fsync(fd);
27363 #else
27364 rc = fdatasync(fd);
27365 #if OS_VXWORKS
27366 if( rc==-1 && errno==ENOTSUP ){
27367 rc = fsync(fd);
27369 #endif /* OS_VXWORKS */
27370 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
27372 if( OS_VXWORKS && rc!= -1 ){
27373 rc = 0;
27375 return rc;
27379 ** Open a file descriptor to the directory containing file zFilename.
27380 ** If successful, *pFd is set to the opened file descriptor and
27381 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
27382 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
27383 ** value.
27385 ** The directory file descriptor is used for only one thing - to
27386 ** fsync() a directory to make sure file creation and deletion events
27387 ** are flushed to disk. Such fsyncs are not needed on newer
27388 ** journaling filesystems, but are required on older filesystems.
27390 ** This routine can be overridden using the xSetSysCall interface.
27391 ** The ability to override this routine was added in support of the
27392 ** chromium sandbox. Opening a directory is a security risk (we are
27393 ** told) so making it overrideable allows the chromium sandbox to
27394 ** replace this routine with a harmless no-op. To make this routine
27395 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
27396 ** *pFd set to a negative number.
27398 ** If SQLITE_OK is returned, the caller is responsible for closing
27399 ** the file descriptor *pFd using close().
27401 static int openDirectory(const char *zFilename, int *pFd){
27402 int ii;
27403 int fd = -1;
27404 char zDirname[MAX_PATHNAME+1];
27406 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
27407 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
27408 if( ii>0 ){
27409 zDirname[ii] = '\0';
27410 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
27411 if( fd>=0 ){
27412 #ifdef FD_CLOEXEC
27413 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27414 #endif
27415 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
27418 *pFd = fd;
27419 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
27423 ** Make sure all writes to a particular file are committed to disk.
27425 ** If dataOnly==0 then both the file itself and its metadata (file
27426 ** size, access time, etc) are synced. If dataOnly!=0 then only the
27427 ** file data is synced.
27429 ** Under Unix, also make sure that the directory entry for the file
27430 ** has been created by fsync-ing the directory that contains the file.
27431 ** If we do not do this and we encounter a power failure, the directory
27432 ** entry for the journal might not exist after we reboot. The next
27433 ** SQLite to access the file will not know that the journal exists (because
27434 ** the directory entry for the journal was never created) and the transaction
27435 ** will not roll back - possibly leading to database corruption.
27437 static int unixSync(sqlite3_file *id, int flags){
27438 int rc;
27439 unixFile *pFile = (unixFile*)id;
27441 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
27442 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
27444 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
27445 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
27446 || (flags&0x0F)==SQLITE_SYNC_FULL
27449 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
27450 ** line is to test that doing so does not cause any problems.
27452 SimulateDiskfullError( return SQLITE_FULL );
27454 assert( pFile );
27455 OSTRACE(("SYNC %-3d\n", pFile->h));
27456 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
27457 SimulateIOError( rc=1 );
27458 if( rc ){
27459 pFile->lastErrno = errno;
27460 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
27463 /* Also fsync the directory containing the file if the DIRSYNC flag
27464 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
27465 ** are unable to fsync a directory, so ignore errors on the fsync.
27467 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
27468 int dirfd;
27469 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
27470 HAVE_FULLFSYNC, isFullsync));
27471 rc = osOpenDirectory(pFile->zPath, &dirfd);
27472 if( rc==SQLITE_OK && dirfd>=0 ){
27473 full_fsync(dirfd, 0, 0);
27474 robust_close(pFile, dirfd, __LINE__);
27475 }else if( rc==SQLITE_CANTOPEN ){
27476 rc = SQLITE_OK;
27478 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
27480 return rc;
27484 ** Truncate an open file to a specified size
27486 static int unixTruncate(sqlite3_file *id, i64 nByte){
27487 unixFile *pFile = (unixFile *)id;
27488 int rc;
27489 assert( pFile );
27490 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
27492 /* If the user has configured a chunk-size for this file, truncate the
27493 ** file so that it consists of an integer number of chunks (i.e. the
27494 ** actual file size after the operation may be larger than the requested
27495 ** size).
27497 if( pFile->szChunk ){
27498 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
27501 rc = robust_ftruncate(pFile->h, (off_t)nByte);
27502 if( rc ){
27503 pFile->lastErrno = errno;
27504 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27505 }else{
27506 #ifndef NDEBUG
27507 /* If we are doing a normal write to a database file (as opposed to
27508 ** doing a hot-journal rollback or a write to some file other than a
27509 ** normal database file) and we truncate the file to zero length,
27510 ** that effectively updates the change counter. This might happen
27511 ** when restoring a database using the backup API from a zero-length
27512 ** source.
27514 if( pFile->inNormalWrite && nByte==0 ){
27515 pFile->transCntrChng = 1;
27517 #endif
27519 return SQLITE_OK;
27524 ** Determine the current size of a file in bytes
27526 static int unixFileSize(sqlite3_file *id, i64 *pSize){
27527 int rc;
27528 struct stat buf;
27529 assert( id );
27530 rc = osFstat(((unixFile*)id)->h, &buf);
27531 SimulateIOError( rc=1 );
27532 if( rc!=0 ){
27533 ((unixFile*)id)->lastErrno = errno;
27534 return SQLITE_IOERR_FSTAT;
27536 *pSize = buf.st_size;
27538 /* When opening a zero-size database, the findInodeInfo() procedure
27539 ** writes a single byte into that file in order to work around a bug
27540 ** in the OS-X msdos filesystem. In order to avoid problems with upper
27541 ** layers, we need to report this file size as zero even though it is
27542 ** really 1. Ticket #3260.
27544 if( *pSize==1 ) *pSize = 0;
27547 return SQLITE_OK;
27550 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27552 ** Handler for proxy-locking file-control verbs. Defined below in the
27553 ** proxying locking division.
27555 static int proxyFileControl(sqlite3_file*,int,void*);
27556 #endif
27559 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
27560 ** file-control operation.
27562 ** If the user has configured a chunk-size for this file, it could be
27563 ** that the file needs to be extended at this point. Otherwise, the
27564 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
27566 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
27567 if( pFile->szChunk ){
27568 i64 nSize; /* Required file size */
27569 struct stat buf; /* Used to hold return values of fstat() */
27571 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
27573 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
27574 if( nSize>(i64)buf.st_size ){
27576 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27577 /* The code below is handling the return value of osFallocate()
27578 ** correctly. posix_fallocate() is defined to "returns zero on success,
27579 ** or an error number on failure". See the manpage for details. */
27580 int err;
27582 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
27583 }while( err==EINTR );
27584 if( err ) return SQLITE_IOERR_WRITE;
27585 #else
27586 /* If the OS does not have posix_fallocate(), fake it. First use
27587 ** ftruncate() to set the file size, then write a single byte to
27588 ** the last byte in each block within the extended region. This
27589 ** is the same technique used by glibc to implement posix_fallocate()
27590 ** on systems that do not have a real fallocate() system call.
27592 int nBlk = buf.st_blksize; /* File-system block size */
27593 i64 iWrite; /* Next offset to write to */
27595 if( robust_ftruncate(pFile->h, nSize) ){
27596 pFile->lastErrno = errno;
27597 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27599 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
27600 while( iWrite<nSize ){
27601 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
27602 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
27603 iWrite += nBlk;
27605 #endif
27609 return SQLITE_OK;
27613 ** Information and control of an open file handle.
27615 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
27616 switch( op ){
27617 case SQLITE_FCNTL_LOCKSTATE: {
27618 *(int*)pArg = ((unixFile*)id)->eFileLock;
27619 return SQLITE_OK;
27621 case SQLITE_LAST_ERRNO: {
27622 *(int*)pArg = ((unixFile*)id)->lastErrno;
27623 return SQLITE_OK;
27625 case SQLITE_FCNTL_CHUNK_SIZE: {
27626 ((unixFile*)id)->szChunk = *(int *)pArg;
27627 return SQLITE_OK;
27629 case SQLITE_FCNTL_SIZE_HINT: {
27630 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
27632 #ifndef NDEBUG
27633 /* The pager calls this method to signal that it has done
27634 ** a rollback and that the database is therefore unchanged and
27635 ** it hence it is OK for the transaction change counter to be
27636 ** unchanged.
27638 case SQLITE_FCNTL_DB_UNCHANGED: {
27639 ((unixFile*)id)->dbUpdate = 0;
27640 return SQLITE_OK;
27642 #endif
27643 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27644 case SQLITE_SET_LOCKPROXYFILE:
27645 case SQLITE_GET_LOCKPROXYFILE: {
27646 return proxyFileControl(id,op,pArg);
27648 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
27649 case SQLITE_FCNTL_SYNC_OMITTED: {
27650 return SQLITE_OK; /* A no-op */
27653 return SQLITE_NOTFOUND;
27657 ** Return the sector size in bytes of the underlying block device for
27658 ** the specified file. This is almost always 512 bytes, but may be
27659 ** larger for some devices.
27661 ** SQLite code assumes this function cannot fail. It also assumes that
27662 ** if two files are created in the same file-system directory (i.e.
27663 ** a database and its journal file) that the sector size will be the
27664 ** same for both.
27666 static int unixSectorSize(sqlite3_file *NotUsed){
27667 UNUSED_PARAMETER(NotUsed);
27668 return SQLITE_DEFAULT_SECTOR_SIZE;
27672 ** Return the device characteristics for the file. This is always 0 for unix.
27674 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
27675 UNUSED_PARAMETER(NotUsed);
27676 return 0;
27679 #ifndef SQLITE_OMIT_WAL
27683 ** Object used to represent an shared memory buffer.
27685 ** When multiple threads all reference the same wal-index, each thread
27686 ** has its own unixShm object, but they all point to a single instance
27687 ** of this unixShmNode object. In other words, each wal-index is opened
27688 ** only once per process.
27690 ** Each unixShmNode object is connected to a single unixInodeInfo object.
27691 ** We could coalesce this object into unixInodeInfo, but that would mean
27692 ** every open file that does not use shared memory (in other words, most
27693 ** open files) would have to carry around this extra information. So
27694 ** the unixInodeInfo object contains a pointer to this unixShmNode object
27695 ** and the unixShmNode object is created only when needed.
27697 ** unixMutexHeld() must be true when creating or destroying
27698 ** this object or while reading or writing the following fields:
27700 ** nRef
27702 ** The following fields are read-only after the object is created:
27704 ** fid
27705 ** zFilename
27707 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
27708 ** unixMutexHeld() is true when reading or writing any other field
27709 ** in this structure.
27711 struct unixShmNode {
27712 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
27713 sqlite3_mutex *mutex; /* Mutex to access this object */
27714 char *zFilename; /* Name of the mmapped file */
27715 int h; /* Open file descriptor */
27716 int szRegion; /* Size of shared-memory regions */
27717 int nRegion; /* Size of array apRegion */
27718 char **apRegion; /* Array of mapped shared-memory regions */
27719 int nRef; /* Number of unixShm objects pointing to this */
27720 unixShm *pFirst; /* All unixShm objects pointing to this */
27721 #ifdef SQLITE_DEBUG
27722 u8 exclMask; /* Mask of exclusive locks held */
27723 u8 sharedMask; /* Mask of shared locks held */
27724 u8 nextShmId; /* Next available unixShm.id value */
27725 #endif
27729 ** Structure used internally by this VFS to record the state of an
27730 ** open shared memory connection.
27732 ** The following fields are initialized when this object is created and
27733 ** are read-only thereafter:
27735 ** unixShm.pFile
27736 ** unixShm.id
27738 ** All other fields are read/write. The unixShm.pFile->mutex must be held
27739 ** while accessing any read/write fields.
27741 struct unixShm {
27742 unixShmNode *pShmNode; /* The underlying unixShmNode object */
27743 unixShm *pNext; /* Next unixShm with the same unixShmNode */
27744 u8 hasMutex; /* True if holding the unixShmNode mutex */
27745 u16 sharedMask; /* Mask of shared locks held */
27746 u16 exclMask; /* Mask of exclusive locks held */
27747 #ifdef SQLITE_DEBUG
27748 u8 id; /* Id of this connection within its unixShmNode */
27749 #endif
27753 ** Constants used for locking
27755 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
27756 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
27759 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
27761 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
27762 ** otherwise.
27764 static int unixShmSystemLock(
27765 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
27766 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
27767 int ofst, /* First byte of the locking range */
27768 int n /* Number of bytes to lock */
27770 struct flock f; /* The posix advisory locking structure */
27771 int rc = SQLITE_OK; /* Result code form fcntl() */
27773 /* Access to the unixShmNode object is serialized by the caller */
27774 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
27776 /* Shared locks never span more than one byte */
27777 assert( n==1 || lockType!=F_RDLCK );
27779 /* Locks are within range */
27780 assert( n>=1 && n<SQLITE_SHM_NLOCK );
27782 if( pShmNode->h>=0 ){
27783 /* Initialize the locking parameters */
27784 memset(&f, 0, sizeof(f));
27785 f.l_type = lockType;
27786 f.l_whence = SEEK_SET;
27787 f.l_start = ofst;
27788 f.l_len = n;
27790 rc = osFcntl(pShmNode->h, F_SETLK, &f);
27791 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
27794 /* Update the global lock state and do debug tracing */
27795 #ifdef SQLITE_DEBUG
27796 { u16 mask;
27797 OSTRACE(("SHM-LOCK "));
27798 mask = (1<<(ofst+n)) - (1<<ofst);
27799 if( rc==SQLITE_OK ){
27800 if( lockType==F_UNLCK ){
27801 OSTRACE(("unlock %d ok", ofst));
27802 pShmNode->exclMask &= ~mask;
27803 pShmNode->sharedMask &= ~mask;
27804 }else if( lockType==F_RDLCK ){
27805 OSTRACE(("read-lock %d ok", ofst));
27806 pShmNode->exclMask &= ~mask;
27807 pShmNode->sharedMask |= mask;
27808 }else{
27809 assert( lockType==F_WRLCK );
27810 OSTRACE(("write-lock %d ok", ofst));
27811 pShmNode->exclMask |= mask;
27812 pShmNode->sharedMask &= ~mask;
27814 }else{
27815 if( lockType==F_UNLCK ){
27816 OSTRACE(("unlock %d failed", ofst));
27817 }else if( lockType==F_RDLCK ){
27818 OSTRACE(("read-lock failed"));
27819 }else{
27820 assert( lockType==F_WRLCK );
27821 OSTRACE(("write-lock %d failed", ofst));
27824 OSTRACE((" - afterwards %03x,%03x\n",
27825 pShmNode->sharedMask, pShmNode->exclMask));
27827 #endif
27829 return rc;
27834 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
27836 ** This is not a VFS shared-memory method; it is a utility function called
27837 ** by VFS shared-memory methods.
27839 static void unixShmPurge(unixFile *pFd){
27840 unixShmNode *p = pFd->pInode->pShmNode;
27841 assert( unixMutexHeld() );
27842 if( p && p->nRef==0 ){
27843 int i;
27844 assert( p->pInode==pFd->pInode );
27845 if( p->mutex ) sqlite3_mutex_free(p->mutex);
27846 for(i=0; i<p->nRegion; i++){
27847 if( p->h>=0 ){
27848 munmap(p->apRegion[i], p->szRegion);
27849 }else{
27850 sqlite3_free(p->apRegion[i]);
27853 sqlite3_free(p->apRegion);
27854 if( p->h>=0 ){
27855 robust_close(pFd, p->h, __LINE__);
27856 p->h = -1;
27858 p->pInode->pShmNode = 0;
27859 sqlite3_free(p);
27864 ** Open a shared-memory area associated with open database file pDbFd.
27865 ** This particular implementation uses mmapped files.
27867 ** The file used to implement shared-memory is in the same directory
27868 ** as the open database file and has the same name as the open database
27869 ** file with the "-shm" suffix added. For example, if the database file
27870 ** is "/home/user1/config.db" then the file that is created and mmapped
27871 ** for shared memory will be called "/home/user1/config.db-shm".
27873 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
27874 ** some other tmpfs mount. But if a file in a different directory
27875 ** from the database file is used, then differing access permissions
27876 ** or a chroot() might cause two different processes on the same
27877 ** database to end up using different files for shared memory -
27878 ** meaning that their memory would not really be shared - resulting
27879 ** in database corruption. Nevertheless, this tmpfs file usage
27880 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
27881 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
27882 ** option results in an incompatible build of SQLite; builds of SQLite
27883 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
27884 ** same database file at the same time, database corruption will likely
27885 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
27886 ** "unsupported" and may go away in a future SQLite release.
27888 ** When opening a new shared-memory file, if no other instances of that
27889 ** file are currently open, in this process or in other processes, then
27890 ** the file must be truncated to zero length or have its header cleared.
27892 ** If the original database file (pDbFd) is using the "unix-excl" VFS
27893 ** that means that an exclusive lock is held on the database file and
27894 ** that no other processes are able to read or write the database. In
27895 ** that case, we do not really need shared memory. No shared memory
27896 ** file is created. The shared memory will be simulated with heap memory.
27898 static int unixOpenSharedMemory(unixFile *pDbFd){
27899 struct unixShm *p = 0; /* The connection to be opened */
27900 struct unixShmNode *pShmNode; /* The underlying mmapped file */
27901 int rc; /* Result code */
27902 unixInodeInfo *pInode; /* The inode of fd */
27903 char *zShmFilename; /* Name of the file used for SHM */
27904 int nShmFilename; /* Size of the SHM filename in bytes */
27906 /* Allocate space for the new unixShm object. */
27907 p = sqlite3_malloc( sizeof(*p) );
27908 if( p==0 ) return SQLITE_NOMEM;
27909 memset(p, 0, sizeof(*p));
27910 assert( pDbFd->pShm==0 );
27912 /* Check to see if a unixShmNode object already exists. Reuse an existing
27913 ** one if present. Create a new one if necessary.
27915 unixEnterMutex();
27916 pInode = pDbFd->pInode;
27917 pShmNode = pInode->pShmNode;
27918 if( pShmNode==0 ){
27919 struct stat sStat; /* fstat() info for database file */
27921 /* Call fstat() to figure out the permissions on the database file. If
27922 ** a new *-shm file is created, an attempt will be made to create it
27923 ** with the same permissions. The actual permissions the file is created
27924 ** with are subject to the current umask setting.
27926 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
27927 rc = SQLITE_IOERR_FSTAT;
27928 goto shm_open_err;
27931 #ifdef SQLITE_SHM_DIRECTORY
27932 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
27933 #else
27934 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
27935 #endif
27936 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
27937 if( pShmNode==0 ){
27938 rc = SQLITE_NOMEM;
27939 goto shm_open_err;
27941 memset(pShmNode, 0, sizeof(*pShmNode));
27942 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
27943 #ifdef SQLITE_SHM_DIRECTORY
27944 sqlite3_snprintf(nShmFilename, zShmFilename,
27945 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
27946 (u32)sStat.st_ino, (u32)sStat.st_dev);
27947 #else
27948 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
27949 #endif
27950 pShmNode->h = -1;
27951 pDbFd->pInode->pShmNode = pShmNode;
27952 pShmNode->pInode = pDbFd->pInode;
27953 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
27954 if( pShmNode->mutex==0 ){
27955 rc = SQLITE_NOMEM;
27956 goto shm_open_err;
27959 if( pInode->bProcessLock==0 ){
27960 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
27961 (sStat.st_mode & 0777));
27962 if( pShmNode->h<0 ){
27963 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
27964 goto shm_open_err;
27967 /* Check to see if another process is holding the dead-man switch.
27968 ** If not, truncate the file to zero length.
27970 rc = SQLITE_OK;
27971 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27972 if( robust_ftruncate(pShmNode->h, 0) ){
27973 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27976 if( rc==SQLITE_OK ){
27977 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27979 if( rc ) goto shm_open_err;
27983 /* Make the new connection a child of the unixShmNode */
27984 p->pShmNode = pShmNode;
27985 #ifdef SQLITE_DEBUG
27986 p->id = pShmNode->nextShmId++;
27987 #endif
27988 pShmNode->nRef++;
27989 pDbFd->pShm = p;
27990 unixLeaveMutex();
27992 /* The reference count on pShmNode has already been incremented under
27993 ** the cover of the unixEnterMutex() mutex and the pointer from the
27994 ** new (struct unixShm) object to the pShmNode has been set. All that is
27995 ** left to do is to link the new object into the linked list starting
27996 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
27997 ** mutex.
27999 sqlite3_mutex_enter(pShmNode->mutex);
28000 p->pNext = pShmNode->pFirst;
28001 pShmNode->pFirst = p;
28002 sqlite3_mutex_leave(pShmNode->mutex);
28003 return SQLITE_OK;
28005 /* Jump here on any error */
28006 shm_open_err:
28007 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
28008 sqlite3_free(p);
28009 unixLeaveMutex();
28010 return rc;
28014 ** This function is called to obtain a pointer to region iRegion of the
28015 ** shared-memory associated with the database file fd. Shared-memory regions
28016 ** are numbered starting from zero. Each shared-memory region is szRegion
28017 ** bytes in size.
28019 ** If an error occurs, an error code is returned and *pp is set to NULL.
28021 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
28022 ** region has not been allocated (by any client, including one running in a
28023 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
28024 ** bExtend is non-zero and the requested shared-memory region has not yet
28025 ** been allocated, it is allocated by this function.
28027 ** If the shared-memory region has already been allocated or is allocated by
28028 ** this call as described above, then it is mapped into this processes
28029 ** address space (if it is not already), *pp is set to point to the mapped
28030 ** memory and SQLITE_OK returned.
28032 static int unixShmMap(
28033 sqlite3_file *fd, /* Handle open on database file */
28034 int iRegion, /* Region to retrieve */
28035 int szRegion, /* Size of regions */
28036 int bExtend, /* True to extend file if necessary */
28037 void volatile **pp /* OUT: Mapped memory */
28039 unixFile *pDbFd = (unixFile*)fd;
28040 unixShm *p;
28041 unixShmNode *pShmNode;
28042 int rc = SQLITE_OK;
28044 /* If the shared-memory file has not yet been opened, open it now. */
28045 if( pDbFd->pShm==0 ){
28046 rc = unixOpenSharedMemory(pDbFd);
28047 if( rc!=SQLITE_OK ) return rc;
28050 p = pDbFd->pShm;
28051 pShmNode = p->pShmNode;
28052 sqlite3_mutex_enter(pShmNode->mutex);
28053 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
28054 assert( pShmNode->pInode==pDbFd->pInode );
28055 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28056 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28058 if( pShmNode->nRegion<=iRegion ){
28059 char **apNew; /* New apRegion[] array */
28060 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
28061 struct stat sStat; /* Used by fstat() */
28063 pShmNode->szRegion = szRegion;
28065 if( pShmNode->h>=0 ){
28066 /* The requested region is not mapped into this processes address space.
28067 ** Check to see if it has been allocated (i.e. if the wal-index file is
28068 ** large enough to contain the requested region).
28070 if( osFstat(pShmNode->h, &sStat) ){
28071 rc = SQLITE_IOERR_SHMSIZE;
28072 goto shmpage_out;
28075 if( sStat.st_size<nByte ){
28076 /* The requested memory region does not exist. If bExtend is set to
28077 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
28079 ** Alternatively, if bExtend is true, use ftruncate() to allocate
28080 ** the requested memory region.
28082 if( !bExtend ) goto shmpage_out;
28083 if( robust_ftruncate(pShmNode->h, nByte) ){
28084 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
28085 pShmNode->zFilename);
28086 goto shmpage_out;
28091 /* Map the requested memory region into this processes address space. */
28092 apNew = (char **)sqlite3_realloc(
28093 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
28095 if( !apNew ){
28096 rc = SQLITE_IOERR_NOMEM;
28097 goto shmpage_out;
28099 pShmNode->apRegion = apNew;
28100 while(pShmNode->nRegion<=iRegion){
28101 void *pMem;
28102 if( pShmNode->h>=0 ){
28103 pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
28104 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
28106 if( pMem==MAP_FAILED ){
28107 rc = SQLITE_IOERR;
28108 goto shmpage_out;
28110 }else{
28111 pMem = sqlite3_malloc(szRegion);
28112 if( pMem==0 ){
28113 rc = SQLITE_NOMEM;
28114 goto shmpage_out;
28116 memset(pMem, 0, szRegion);
28118 pShmNode->apRegion[pShmNode->nRegion] = pMem;
28119 pShmNode->nRegion++;
28123 shmpage_out:
28124 if( pShmNode->nRegion>iRegion ){
28125 *pp = pShmNode->apRegion[iRegion];
28126 }else{
28127 *pp = 0;
28129 sqlite3_mutex_leave(pShmNode->mutex);
28130 return rc;
28134 ** Change the lock state for a shared-memory segment.
28136 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
28137 ** different here than in posix. In xShmLock(), one can go from unlocked
28138 ** to shared and back or from unlocked to exclusive and back. But one may
28139 ** not go from shared to exclusive or from exclusive to shared.
28141 static int unixShmLock(
28142 sqlite3_file *fd, /* Database file holding the shared memory */
28143 int ofst, /* First lock to acquire or release */
28144 int n, /* Number of locks to acquire or release */
28145 int flags /* What to do with the lock */
28147 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
28148 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
28149 unixShm *pX; /* For looping over all siblings */
28150 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
28151 int rc = SQLITE_OK; /* Result code */
28152 u16 mask; /* Mask of locks to take or release */
28154 assert( pShmNode==pDbFd->pInode->pShmNode );
28155 assert( pShmNode->pInode==pDbFd->pInode );
28156 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
28157 assert( n>=1 );
28158 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
28159 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
28160 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
28161 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
28162 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
28163 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28164 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28166 mask = (1<<(ofst+n)) - (1<<ofst);
28167 assert( n>1 || mask==(1<<ofst) );
28168 sqlite3_mutex_enter(pShmNode->mutex);
28169 if( flags & SQLITE_SHM_UNLOCK ){
28170 u16 allMask = 0; /* Mask of locks held by siblings */
28172 /* See if any siblings hold this same lock */
28173 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28174 if( pX==p ) continue;
28175 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
28176 allMask |= pX->sharedMask;
28179 /* Unlock the system-level locks */
28180 if( (mask & allMask)==0 ){
28181 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
28182 }else{
28183 rc = SQLITE_OK;
28186 /* Undo the local locks */
28187 if( rc==SQLITE_OK ){
28188 p->exclMask &= ~mask;
28189 p->sharedMask &= ~mask;
28191 }else if( flags & SQLITE_SHM_SHARED ){
28192 u16 allShared = 0; /* Union of locks held by connections other than "p" */
28194 /* Find out which shared locks are already held by sibling connections.
28195 ** If any sibling already holds an exclusive lock, go ahead and return
28196 ** SQLITE_BUSY.
28198 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28199 if( (pX->exclMask & mask)!=0 ){
28200 rc = SQLITE_BUSY;
28201 break;
28203 allShared |= pX->sharedMask;
28206 /* Get shared locks at the system level, if necessary */
28207 if( rc==SQLITE_OK ){
28208 if( (allShared & mask)==0 ){
28209 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
28210 }else{
28211 rc = SQLITE_OK;
28215 /* Get the local shared locks */
28216 if( rc==SQLITE_OK ){
28217 p->sharedMask |= mask;
28219 }else{
28220 /* Make sure no sibling connections hold locks that will block this
28221 ** lock. If any do, return SQLITE_BUSY right away.
28223 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28224 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
28225 rc = SQLITE_BUSY;
28226 break;
28230 /* Get the exclusive locks at the system level. Then if successful
28231 ** also mark the local connection as being locked.
28233 if( rc==SQLITE_OK ){
28234 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
28235 if( rc==SQLITE_OK ){
28236 assert( (p->sharedMask & mask)==0 );
28237 p->exclMask |= mask;
28241 sqlite3_mutex_leave(pShmNode->mutex);
28242 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
28243 p->id, getpid(), p->sharedMask, p->exclMask));
28244 return rc;
28248 ** Implement a memory barrier or memory fence on shared memory.
28250 ** All loads and stores begun before the barrier must complete before
28251 ** any load or store begun after the barrier.
28253 static void unixShmBarrier(
28254 sqlite3_file *fd /* Database file holding the shared memory */
28256 UNUSED_PARAMETER(fd);
28257 unixEnterMutex();
28258 unixLeaveMutex();
28262 ** Close a connection to shared-memory. Delete the underlying
28263 ** storage if deleteFlag is true.
28265 ** If there is no shared memory associated with the connection then this
28266 ** routine is a harmless no-op.
28268 static int unixShmUnmap(
28269 sqlite3_file *fd, /* The underlying database file */
28270 int deleteFlag /* Delete shared-memory if true */
28272 unixShm *p; /* The connection to be closed */
28273 unixShmNode *pShmNode; /* The underlying shared-memory file */
28274 unixShm **pp; /* For looping over sibling connections */
28275 unixFile *pDbFd; /* The underlying database file */
28277 pDbFd = (unixFile*)fd;
28278 p = pDbFd->pShm;
28279 if( p==0 ) return SQLITE_OK;
28280 pShmNode = p->pShmNode;
28282 assert( pShmNode==pDbFd->pInode->pShmNode );
28283 assert( pShmNode->pInode==pDbFd->pInode );
28285 /* Remove connection p from the set of connections associated
28286 ** with pShmNode */
28287 sqlite3_mutex_enter(pShmNode->mutex);
28288 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
28289 *pp = p->pNext;
28291 /* Free the connection p */
28292 sqlite3_free(p);
28293 pDbFd->pShm = 0;
28294 sqlite3_mutex_leave(pShmNode->mutex);
28296 /* If pShmNode->nRef has reached 0, then close the underlying
28297 ** shared-memory file, too */
28298 unixEnterMutex();
28299 assert( pShmNode->nRef>0 );
28300 pShmNode->nRef--;
28301 if( pShmNode->nRef==0 ){
28302 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
28303 unixShmPurge(pDbFd);
28305 unixLeaveMutex();
28307 return SQLITE_OK;
28311 #else
28312 # define unixShmMap 0
28313 # define unixShmLock 0
28314 # define unixShmBarrier 0
28315 # define unixShmUnmap 0
28316 #endif /* #ifndef SQLITE_OMIT_WAL */
28319 ** Here ends the implementation of all sqlite3_file methods.
28321 ********************** End sqlite3_file Methods *******************************
28322 ******************************************************************************/
28325 ** This division contains definitions of sqlite3_io_methods objects that
28326 ** implement various file locking strategies. It also contains definitions
28327 ** of "finder" functions. A finder-function is used to locate the appropriate
28328 ** sqlite3_io_methods object for a particular database file. The pAppData
28329 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
28330 ** the correct finder-function for that VFS.
28332 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
28333 ** object. The only interesting finder-function is autolockIoFinder, which
28334 ** looks at the filesystem type and tries to guess the best locking
28335 ** strategy from that.
28337 ** For finder-funtion F, two objects are created:
28339 ** (1) The real finder-function named "FImpt()".
28341 ** (2) A constant pointer to this function named just "F".
28344 ** A pointer to the F pointer is used as the pAppData value for VFS
28345 ** objects. We have to do this instead of letting pAppData point
28346 ** directly at the finder-function since C90 rules prevent a void*
28347 ** from be cast into a function pointer.
28350 ** Each instance of this macro generates two objects:
28352 ** * A constant sqlite3_io_methods object call METHOD that has locking
28353 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
28355 ** * An I/O method finder function called FINDER that returns a pointer
28356 ** to the METHOD object in the previous bullet.
28358 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
28359 static const sqlite3_io_methods METHOD = { \
28360 VERSION, /* iVersion */ \
28361 CLOSE, /* xClose */ \
28362 unixRead, /* xRead */ \
28363 unixWrite, /* xWrite */ \
28364 unixTruncate, /* xTruncate */ \
28365 unixSync, /* xSync */ \
28366 unixFileSize, /* xFileSize */ \
28367 LOCK, /* xLock */ \
28368 UNLOCK, /* xUnlock */ \
28369 CKLOCK, /* xCheckReservedLock */ \
28370 unixFileControl, /* xFileControl */ \
28371 unixSectorSize, /* xSectorSize */ \
28372 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
28373 unixShmMap, /* xShmMap */ \
28374 unixShmLock, /* xShmLock */ \
28375 unixShmBarrier, /* xShmBarrier */ \
28376 unixShmUnmap /* xShmUnmap */ \
28377 }; \
28378 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
28379 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
28380 return &METHOD; \
28382 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
28383 = FINDER##Impl;
28386 ** Here are all of the sqlite3_io_methods objects for each of the
28387 ** locking strategies. Functions that return pointers to these methods
28388 ** are also created.
28390 IOMETHODS(
28391 posixIoFinder, /* Finder function name */
28392 posixIoMethods, /* sqlite3_io_methods object name */
28393 2, /* shared memory is enabled */
28394 unixClose, /* xClose method */
28395 unixLock, /* xLock method */
28396 unixUnlock, /* xUnlock method */
28397 unixCheckReservedLock /* xCheckReservedLock method */
28399 IOMETHODS(
28400 nolockIoFinder, /* Finder function name */
28401 nolockIoMethods, /* sqlite3_io_methods object name */
28402 1, /* shared memory is disabled */
28403 nolockClose, /* xClose method */
28404 nolockLock, /* xLock method */
28405 nolockUnlock, /* xUnlock method */
28406 nolockCheckReservedLock /* xCheckReservedLock method */
28408 IOMETHODS(
28409 dotlockIoFinder, /* Finder function name */
28410 dotlockIoMethods, /* sqlite3_io_methods object name */
28411 1, /* shared memory is disabled */
28412 dotlockClose, /* xClose method */
28413 dotlockLock, /* xLock method */
28414 dotlockUnlock, /* xUnlock method */
28415 dotlockCheckReservedLock /* xCheckReservedLock method */
28418 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28419 IOMETHODS(
28420 flockIoFinder, /* Finder function name */
28421 flockIoMethods, /* sqlite3_io_methods object name */
28422 1, /* shared memory is disabled */
28423 flockClose, /* xClose method */
28424 flockLock, /* xLock method */
28425 flockUnlock, /* xUnlock method */
28426 flockCheckReservedLock /* xCheckReservedLock method */
28428 #endif
28430 #if OS_VXWORKS
28431 IOMETHODS(
28432 semIoFinder, /* Finder function name */
28433 semIoMethods, /* sqlite3_io_methods object name */
28434 1, /* shared memory is disabled */
28435 semClose, /* xClose method */
28436 semLock, /* xLock method */
28437 semUnlock, /* xUnlock method */
28438 semCheckReservedLock /* xCheckReservedLock method */
28440 #endif
28442 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28443 IOMETHODS(
28444 afpIoFinder, /* Finder function name */
28445 afpIoMethods, /* sqlite3_io_methods object name */
28446 1, /* shared memory is disabled */
28447 afpClose, /* xClose method */
28448 afpLock, /* xLock method */
28449 afpUnlock, /* xUnlock method */
28450 afpCheckReservedLock /* xCheckReservedLock method */
28452 #endif
28455 ** The proxy locking method is a "super-method" in the sense that it
28456 ** opens secondary file descriptors for the conch and lock files and
28457 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
28458 ** secondary files. For this reason, the division that implements
28459 ** proxy locking is located much further down in the file. But we need
28460 ** to go ahead and define the sqlite3_io_methods and finder function
28461 ** for proxy locking here. So we forward declare the I/O methods.
28463 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28464 static int proxyClose(sqlite3_file*);
28465 static int proxyLock(sqlite3_file*, int);
28466 static int proxyUnlock(sqlite3_file*, int);
28467 static int proxyCheckReservedLock(sqlite3_file*, int*);
28468 IOMETHODS(
28469 proxyIoFinder, /* Finder function name */
28470 proxyIoMethods, /* sqlite3_io_methods object name */
28471 1, /* shared memory is disabled */
28472 proxyClose, /* xClose method */
28473 proxyLock, /* xLock method */
28474 proxyUnlock, /* xUnlock method */
28475 proxyCheckReservedLock /* xCheckReservedLock method */
28477 #endif
28479 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28480 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28481 IOMETHODS(
28482 nfsIoFinder, /* Finder function name */
28483 nfsIoMethods, /* sqlite3_io_methods object name */
28484 1, /* shared memory is disabled */
28485 unixClose, /* xClose method */
28486 unixLock, /* xLock method */
28487 nfsUnlock, /* xUnlock method */
28488 unixCheckReservedLock /* xCheckReservedLock method */
28490 #endif
28492 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28494 ** This "finder" function attempts to determine the best locking strategy
28495 ** for the database file "filePath". It then returns the sqlite3_io_methods
28496 ** object that implements that strategy.
28498 ** This is for MacOSX only.
28500 static const sqlite3_io_methods *autolockIoFinderImpl(
28501 const char *filePath, /* name of the database file */
28502 unixFile *pNew /* open file object for the database file */
28504 static const struct Mapping {
28505 const char *zFilesystem; /* Filesystem type name */
28506 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
28507 } aMap[] = {
28508 { "hfs", &posixIoMethods },
28509 { "ufs", &posixIoMethods },
28510 { "afpfs", &afpIoMethods },
28511 { "smbfs", &afpIoMethods },
28512 { "webdav", &nolockIoMethods },
28513 { 0, 0 }
28515 int i;
28516 struct statfs fsInfo;
28517 struct flock lockInfo;
28519 if( !filePath ){
28520 /* If filePath==NULL that means we are dealing with a transient file
28521 ** that does not need to be locked. */
28522 return &nolockIoMethods;
28524 if( statfs(filePath, &fsInfo) != -1 ){
28525 if( fsInfo.f_flags & MNT_RDONLY ){
28526 return &nolockIoMethods;
28528 for(i=0; aMap[i].zFilesystem; i++){
28529 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
28530 return aMap[i].pMethods;
28535 /* Default case. Handles, amongst others, "nfs".
28536 ** Test byte-range lock using fcntl(). If the call succeeds,
28537 ** assume that the file-system supports POSIX style locks.
28539 lockInfo.l_len = 1;
28540 lockInfo.l_start = 0;
28541 lockInfo.l_whence = SEEK_SET;
28542 lockInfo.l_type = F_RDLCK;
28543 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28544 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
28545 return &nfsIoMethods;
28546 } else {
28547 return &posixIoMethods;
28549 }else{
28550 return &dotlockIoMethods;
28553 static const sqlite3_io_methods
28554 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28556 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28558 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
28560 ** This "finder" function attempts to determine the best locking strategy
28561 ** for the database file "filePath". It then returns the sqlite3_io_methods
28562 ** object that implements that strategy.
28564 ** This is for VXWorks only.
28566 static const sqlite3_io_methods *autolockIoFinderImpl(
28567 const char *filePath, /* name of the database file */
28568 unixFile *pNew /* the open file object */
28570 struct flock lockInfo;
28572 if( !filePath ){
28573 /* If filePath==NULL that means we are dealing with a transient file
28574 ** that does not need to be locked. */
28575 return &nolockIoMethods;
28578 /* Test if fcntl() is supported and use POSIX style locks.
28579 ** Otherwise fall back to the named semaphore method.
28581 lockInfo.l_len = 1;
28582 lockInfo.l_start = 0;
28583 lockInfo.l_whence = SEEK_SET;
28584 lockInfo.l_type = F_RDLCK;
28585 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28586 return &posixIoMethods;
28587 }else{
28588 return &semIoMethods;
28591 static const sqlite3_io_methods
28592 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28594 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
28597 ** An abstract type for a pointer to a IO method finder function:
28599 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
28602 /****************************************************************************
28603 **************************** sqlite3_vfs methods ****************************
28605 ** This division contains the implementation of methods on the
28606 ** sqlite3_vfs object.
28610 ** Initializes a unixFile structure with zeros.
28612 void initUnixFile(sqlite3_file* file) {
28613 memset(file, 0, sizeof(unixFile));
28617 ** Initialize the contents of the unixFile structure pointed to by pId.
28619 int fillInUnixFile(
28620 sqlite3_vfs *pVfs, /* Pointer to vfs object */
28621 int h, /* Open file descriptor of file being opened */
28622 int syncDir, /* True to sync directory on first sync */
28623 sqlite3_file *pId, /* Write to the unixFile structure here */
28624 const char *zFilename, /* Name of the file being opened */
28625 int noLock, /* Omit locking if true */
28626 int isDelete, /* Delete on close if true */
28627 int isReadOnly /* True if the file is opened read-only */
28629 const sqlite3_io_methods *pLockingStyle;
28630 unixFile *pNew = (unixFile *)pId;
28631 int rc = SQLITE_OK;
28633 assert( pNew->pInode==NULL );
28635 /* Parameter isDelete is only used on vxworks. Express this explicitly
28636 ** here to prevent compiler warnings about unused parameters.
28638 UNUSED_PARAMETER(isDelete);
28640 /* Usually the path zFilename should not be a relative pathname. The
28641 ** exception is when opening the proxy "conch" file in builds that
28642 ** include the special Apple locking styles.
28644 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28645 assert( zFilename==0 || zFilename[0]=='/'
28646 || pVfs->pAppData==(void*)&autolockIoFinder );
28647 #else
28648 assert( zFilename==0 || zFilename[0]=='/' );
28649 #endif
28651 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
28652 pNew->h = h;
28653 pNew->zPath = zFilename;
28654 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
28655 pNew->ctrlFlags = UNIXFILE_EXCL;
28656 }else{
28657 pNew->ctrlFlags = 0;
28659 if( isReadOnly ){
28660 pNew->ctrlFlags |= UNIXFILE_RDONLY;
28662 if( syncDir ){
28663 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
28666 #if OS_VXWORKS
28667 pNew->pId = vxworksFindFileId(zFilename);
28668 if( pNew->pId==0 ){
28669 noLock = 1;
28670 rc = SQLITE_NOMEM;
28672 #endif
28674 if( noLock ){
28675 pLockingStyle = &nolockIoMethods;
28676 }else{
28677 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
28678 #if SQLITE_ENABLE_LOCKING_STYLE
28679 /* Cache zFilename in the locking context (AFP and dotlock override) for
28680 ** proxyLock activation is possible (remote proxy is based on db name)
28681 ** zFilename remains valid until file is closed, to support */
28682 pNew->lockingContext = (void*)zFilename;
28683 #endif
28686 if( pLockingStyle == &posixIoMethods
28687 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28688 || pLockingStyle == &nfsIoMethods
28689 #endif
28691 unixEnterMutex();
28692 rc = findInodeInfo(pNew, &pNew->pInode);
28693 if( rc!=SQLITE_OK ){
28694 /* If an error occured in findInodeInfo(), close the file descriptor
28695 ** immediately, before releasing the mutex. findInodeInfo() may fail
28696 ** in two scenarios:
28698 ** (a) A call to fstat() failed.
28699 ** (b) A malloc failed.
28701 ** Scenario (b) may only occur if the process is holding no other
28702 ** file descriptors open on the same file. If there were other file
28703 ** descriptors on this file, then no malloc would be required by
28704 ** findInodeInfo(). If this is the case, it is quite safe to close
28705 ** handle h - as it is guaranteed that no posix locks will be released
28706 ** by doing so.
28708 ** If scenario (a) caused the error then things are not so safe. The
28709 ** implicit assumption here is that if fstat() fails, things are in
28710 ** such bad shape that dropping a lock or two doesn't matter much.
28712 robust_close(pNew, h, __LINE__);
28713 h = -1;
28715 unixLeaveMutex();
28718 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28719 else if( pLockingStyle == &afpIoMethods ){
28720 /* AFP locking uses the file path so it needs to be included in
28721 ** the afpLockingContext.
28723 afpLockingContext *pCtx;
28724 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
28725 if( pCtx==0 ){
28726 rc = SQLITE_NOMEM;
28727 }else{
28728 /* NB: zFilename exists and remains valid until the file is closed
28729 ** according to requirement F11141. So we do not need to make a
28730 ** copy of the filename. */
28731 pCtx->dbPath = zFilename;
28732 pCtx->reserved = 0;
28733 srandomdev();
28734 unixEnterMutex();
28735 rc = findInodeInfo(pNew, &pNew->pInode);
28736 if( rc!=SQLITE_OK ){
28737 sqlite3_free(pNew->lockingContext);
28738 robust_close(pNew, h, __LINE__);
28739 h = -1;
28741 unixLeaveMutex();
28744 #endif
28746 else if( pLockingStyle == &dotlockIoMethods ){
28747 /* Dotfile locking uses the file path so it needs to be included in
28748 ** the dotlockLockingContext
28750 char *zLockFile;
28751 int nFilename;
28752 nFilename = (int)strlen(zFilename) + 6;
28753 zLockFile = (char *)sqlite3_malloc(nFilename);
28754 if( zLockFile==0 ){
28755 rc = SQLITE_NOMEM;
28756 }else{
28757 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
28759 pNew->lockingContext = zLockFile;
28762 #if OS_VXWORKS
28763 else if( pLockingStyle == &semIoMethods ){
28764 /* Named semaphore locking uses the file path so it needs to be
28765 ** included in the semLockingContext
28767 unixEnterMutex();
28768 rc = findInodeInfo(pNew, &pNew->pInode);
28769 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
28770 char *zSemName = pNew->pInode->aSemName;
28771 int n;
28772 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
28773 pNew->pId->zCanonicalName);
28774 for( n=1; zSemName[n]; n++ )
28775 if( zSemName[n]=='/' ) zSemName[n] = '_';
28776 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
28777 if( pNew->pInode->pSem == SEM_FAILED ){
28778 rc = SQLITE_NOMEM;
28779 pNew->pInode->aSemName[0] = '\0';
28782 unixLeaveMutex();
28784 #endif
28786 pNew->lastErrno = 0;
28787 #if OS_VXWORKS
28788 if( rc!=SQLITE_OK ){
28789 if( h>=0 ) robust_close(pNew, h, __LINE__);
28790 h = -1;
28791 osUnlink(zFilename);
28792 isDelete = 0;
28794 pNew->isDelete = isDelete;
28795 #endif
28796 if( rc!=SQLITE_OK ){
28797 if( h>=0 ) robust_close(pNew, h, __LINE__);
28798 }else{
28799 pNew->pMethod = pLockingStyle;
28800 OpenCounter(+1);
28802 return rc;
28806 ** Return the name of a directory in which to put temporary files.
28807 ** If no suitable temporary file directory can be found, return NULL.
28809 static const char *unixTempFileDir(void){
28810 static const char *azDirs[] = {
28813 "/var/tmp",
28814 "/usr/tmp",
28815 "/tmp",
28816 0 /* List terminator */
28818 unsigned int i;
28819 struct stat buf;
28820 const char *zDir = 0;
28822 azDirs[0] = sqlite3_temp_directory;
28823 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
28824 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
28825 if( zDir==0 ) continue;
28826 if( osStat(zDir, &buf) ) continue;
28827 if( !S_ISDIR(buf.st_mode) ) continue;
28828 if( osAccess(zDir, 07) ) continue;
28829 break;
28831 return zDir;
28835 ** Create a temporary file name in zBuf. zBuf must be allocated
28836 ** by the calling process and must be big enough to hold at least
28837 ** pVfs->mxPathname bytes.
28839 static int unixGetTempname(int nBuf, char *zBuf){
28840 static const unsigned char zChars[] =
28841 "abcdefghijklmnopqrstuvwxyz"
28842 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28843 "0123456789";
28844 unsigned int i, j;
28845 const char *zDir;
28847 /* It's odd to simulate an io-error here, but really this is just
28848 ** using the io-error infrastructure to test that SQLite handles this
28849 ** function failing.
28851 SimulateIOError( return SQLITE_IOERR );
28853 zDir = unixTempFileDir();
28854 if( zDir==0 ) zDir = ".";
28856 /* Check that the output buffer is large enough for the temporary file
28857 ** name. If it is not, return SQLITE_ERROR.
28859 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
28860 return SQLITE_ERROR;
28864 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
28865 j = (int)strlen(zBuf);
28866 sqlite3_randomness(15, &zBuf[j]);
28867 for(i=0; i<15; i++, j++){
28868 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28870 zBuf[j] = 0;
28871 }while( osAccess(zBuf,0)==0 );
28872 return SQLITE_OK;
28875 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28877 ** Routine to transform a unixFile into a proxy-locking unixFile.
28878 ** Implementation in the proxy-lock division, but used by unixOpen()
28879 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
28881 static int proxyTransformUnixFile(unixFile*, const char*);
28882 #endif
28885 ** Search for an unused file descriptor that was opened on the database
28886 ** file (not a journal or master-journal file) identified by pathname
28887 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
28888 ** argument to this function.
28890 ** Such a file descriptor may exist if a database connection was closed
28891 ** but the associated file descriptor could not be closed because some
28892 ** other file descriptor open on the same file is holding a file-lock.
28893 ** Refer to comments in the unixClose() function and the lengthy comment
28894 ** describing "Posix Advisory Locking" at the start of this file for
28895 ** further details. Also, ticket #4018.
28897 ** If a suitable file descriptor is found, then it is returned. If no
28898 ** such file descriptor is located, -1 is returned.
28900 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
28901 UnixUnusedFd *pUnused = 0;
28903 /* Do not search for an unused file descriptor on vxworks. Not because
28904 ** vxworks would not benefit from the change (it might, we're not sure),
28905 ** but because no way to test it is currently available. It is better
28906 ** not to risk breaking vxworks support for the sake of such an obscure
28907 ** feature. */
28908 #if !OS_VXWORKS
28909 struct stat sStat; /* Results of stat() call */
28911 /* A stat() call may fail for various reasons. If this happens, it is
28912 ** almost certain that an open() call on the same path will also fail.
28913 ** For this reason, if an error occurs in the stat() call here, it is
28914 ** ignored and -1 is returned. The caller will try to open a new file
28915 ** descriptor on the same path, fail, and return an error to SQLite.
28917 ** Even if a subsequent open() call does succeed, the consequences of
28918 ** not searching for a resusable file descriptor are not dire. */
28919 if( 0==osStat(zPath, &sStat) ){
28920 unixInodeInfo *pInode;
28922 unixEnterMutex();
28923 pInode = inodeList;
28924 while( pInode && (pInode->fileId.dev!=sStat.st_dev
28925 || pInode->fileId.ino!=sStat.st_ino) ){
28926 pInode = pInode->pNext;
28928 if( pInode ){
28929 UnixUnusedFd **pp;
28930 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
28931 pUnused = *pp;
28932 if( pUnused ){
28933 *pp = pUnused->pNext;
28936 unixLeaveMutex();
28938 #endif /* if !OS_VXWORKS */
28939 return pUnused;
28943 ** This function is called by unixOpen() to determine the unix permissions
28944 ** to create new files with. If no error occurs, then SQLITE_OK is returned
28945 ** and a value suitable for passing as the third argument to open(2) is
28946 ** written to *pMode. If an IO error occurs, an SQLite error code is
28947 ** returned and the value of *pMode is not modified.
28949 ** If the file being opened is a temporary file, it is always created with
28950 ** the octal permissions 0600 (read/writable by owner only). If the file
28951 ** is a database or master journal file, it is created with the permissions
28952 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
28954 ** Finally, if the file being opened is a WAL or regular journal file, then
28955 ** this function queries the file-system for the permissions on the
28956 ** corresponding database file and sets *pMode to this value. Whenever
28957 ** possible, WAL and journal files are created using the same permissions
28958 ** as the associated database file.
28960 static int findCreateFileMode(
28961 const char *zPath, /* Path of file (possibly) being created */
28962 int flags, /* Flags passed as 4th argument to xOpen() */
28963 mode_t *pMode /* OUT: Permissions to open file with */
28965 int rc = SQLITE_OK; /* Return Code */
28966 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28967 char zDb[MAX_PATHNAME+1]; /* Database file path */
28968 int nDb; /* Number of valid bytes in zDb */
28969 struct stat sStat; /* Output of stat() on database file */
28971 /* zPath is a path to a WAL or journal file. The following block derives
28972 ** the path to the associated database file from zPath. This block handles
28973 ** the following naming conventions:
28975 ** "<path to db>-journal"
28976 ** "<path to db>-wal"
28977 ** "<path to db>-journal-NNNN"
28978 ** "<path to db>-wal-NNNN"
28980 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
28981 ** used by the test_multiplex.c module.
28983 nDb = sqlite3Strlen30(zPath) - 1;
28984 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
28985 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
28986 memcpy(zDb, zPath, nDb);
28987 zDb[nDb] = '\0';
28989 if( 0==osStat(zDb, &sStat) ){
28990 *pMode = sStat.st_mode & 0777;
28991 }else{
28992 rc = SQLITE_IOERR_FSTAT;
28994 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28995 *pMode = 0600;
28996 }else{
28997 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
28999 return rc;
29003 ** Initializes a unixFile structure with zeros.
29005 void chromium_sqlite3_initialize_unix_sqlite3_file(sqlite3_file* file) {
29006 memset(file, 0, sizeof(unixFile));
29009 int chromium_sqlite3_fill_in_unix_sqlite3_file(sqlite3_vfs* vfs,
29010 int fd,
29011 int dirfd,
29012 sqlite3_file* file,
29013 const char* fileName,
29014 int noLock,
29015 int isDelete) {
29016 return fillInUnixFile(vfs, fd, dirfd, file, fileName, noLock, isDelete, 0);
29020 ** Search for an unused file descriptor that was opened on the database file.
29021 ** If a suitable file descriptor if found, then it is stored in *fd; otherwise,
29022 ** *fd is not modified.
29024 ** If a reusable file descriptor is not found, and a new UnixUnusedFd cannot
29025 ** be allocated, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK is returned.
29027 int chromium_sqlite3_get_reusable_file_handle(sqlite3_file* file,
29028 const char* fileName,
29029 int flags,
29030 int* fd) {
29031 unixFile* unixSQLite3File = (unixFile*)file;
29032 int fileType = flags & 0xFFFFFF00;
29033 if (fileType == SQLITE_OPEN_MAIN_DB) {
29034 UnixUnusedFd *unusedFd = findReusableFd(fileName, flags);
29035 if (unusedFd) {
29036 *fd = unusedFd->fd;
29037 } else {
29038 unusedFd = sqlite3_malloc(sizeof(*unusedFd));
29039 if (!unusedFd) {
29040 return SQLITE_NOMEM;
29043 unixSQLite3File->pUnused = unusedFd;
29045 return SQLITE_OK;
29049 ** Marks 'fd' as the unused file descriptor for 'pFile'.
29051 void chromium_sqlite3_update_reusable_file_handle(sqlite3_file* file,
29052 int fd,
29053 int flags) {
29054 unixFile* unixSQLite3File = (unixFile*)file;
29055 if (unixSQLite3File->pUnused) {
29056 unixSQLite3File->pUnused->fd = fd;
29057 unixSQLite3File->pUnused->flags = flags;
29062 ** Destroys pFile's field that keeps track of the unused file descriptor.
29064 void chromium_sqlite3_destroy_reusable_file_handle(sqlite3_file* file) {
29065 unixFile* unixSQLite3File = (unixFile*)file;
29066 sqlite3_free(unixSQLite3File->pUnused);
29070 ** Open the file zPath.
29072 ** Previously, the SQLite OS layer used three functions in place of this
29073 ** one:
29075 ** sqlite3OsOpenReadWrite();
29076 ** sqlite3OsOpenReadOnly();
29077 ** sqlite3OsOpenExclusive();
29079 ** These calls correspond to the following combinations of flags:
29081 ** ReadWrite() -> (READWRITE | CREATE)
29082 ** ReadOnly() -> (READONLY)
29083 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
29085 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
29086 ** true, the file was configured to be automatically deleted when the
29087 ** file handle closed. To achieve the same effect using this new
29088 ** interface, add the DELETEONCLOSE flag to those specified above for
29089 ** OpenExclusive().
29091 static int unixOpen(
29092 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
29093 const char *zPath, /* Pathname of file to be opened */
29094 sqlite3_file *pFile, /* The file descriptor to be filled in */
29095 int flags, /* Input flags to control the opening */
29096 int *pOutFlags /* Output flags returned to SQLite core */
29098 unixFile *p = (unixFile *)pFile;
29099 int fd = -1; /* File descriptor returned by open() */
29100 int openFlags = 0; /* Flags to pass to open() */
29101 int eType = flags&0xFFFFFF00; /* Type of file to open */
29102 int noLock; /* True to omit locking primitives */
29103 int rc = SQLITE_OK; /* Function Return Code */
29105 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
29106 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
29107 int isCreate = (flags & SQLITE_OPEN_CREATE);
29108 int isReadonly = (flags & SQLITE_OPEN_READONLY);
29109 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
29110 #if SQLITE_ENABLE_LOCKING_STYLE
29111 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
29112 #endif
29114 /* If creating a master or main-file journal, this function will open
29115 ** a file-descriptor on the directory too. The first time unixSync()
29116 ** is called the directory file descriptor will be fsync()ed and close()d.
29118 int syncDir = (isCreate && (
29119 eType==SQLITE_OPEN_MASTER_JOURNAL
29120 || eType==SQLITE_OPEN_MAIN_JOURNAL
29121 || eType==SQLITE_OPEN_WAL
29124 /* If argument zPath is a NULL pointer, this function is required to open
29125 ** a temporary file. Use this buffer to store the file name in.
29127 char zTmpname[MAX_PATHNAME+1];
29128 const char *zName = zPath;
29130 /* Check the following statements are true:
29132 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
29133 ** (b) if CREATE is set, then READWRITE must also be set, and
29134 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
29135 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
29137 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
29138 assert(isCreate==0 || isReadWrite);
29139 assert(isExclusive==0 || isCreate);
29140 assert(isDelete==0 || isCreate);
29142 /* The main DB, main journal, WAL file and master journal are never
29143 ** automatically deleted. Nor are they ever temporary files. */
29144 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
29145 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
29146 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
29147 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
29149 /* Assert that the upper layer has set one of the "file-type" flags. */
29150 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
29151 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
29152 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
29153 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
29156 chromium_sqlite3_initialize_unix_sqlite3_file(pFile);
29158 if( eType==SQLITE_OPEN_MAIN_DB ){
29159 rc = chromium_sqlite3_get_reusable_file_handle(pFile, zName, flags, &fd);
29160 if( rc!=SQLITE_OK ){
29161 return rc;
29163 }else if( !zName ){
29164 /* If zName is NULL, the upper layer is requesting a temp file. */
29165 assert(isDelete && !syncDir);
29166 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
29167 if( rc!=SQLITE_OK ){
29168 return rc;
29170 zName = zTmpname;
29173 /* Determine the value of the flags parameter passed to POSIX function
29174 ** open(). These must be calculated even if open() is not called, as
29175 ** they may be stored as part of the file handle and used by the
29176 ** 'conch file' locking functions later on. */
29177 if( isReadonly ) openFlags |= O_RDONLY;
29178 if( isReadWrite ) openFlags |= O_RDWR;
29179 if( isCreate ) openFlags |= O_CREAT;
29180 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
29181 openFlags |= (O_LARGEFILE|O_BINARY);
29183 if( fd<0 ){
29184 mode_t openMode; /* Permissions to create file with */
29185 rc = findCreateFileMode(zName, flags, &openMode);
29186 if( rc!=SQLITE_OK ){
29187 assert( !p->pUnused );
29188 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
29189 return rc;
29191 fd = robust_open(zName, openFlags, openMode);
29192 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
29193 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
29194 /* Failed to open the file for read/write access. Try read-only. */
29195 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
29196 openFlags &= ~(O_RDWR|O_CREAT);
29197 flags |= SQLITE_OPEN_READONLY;
29198 openFlags |= O_RDONLY;
29199 isReadonly = 1;
29200 fd = robust_open(zName, openFlags, openMode);
29202 if( fd<0 ){
29203 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
29204 goto open_finished;
29207 assert( fd>=0 );
29208 if( pOutFlags ){
29209 *pOutFlags = flags;
29212 chromium_sqlite3_update_reusable_file_handle(pFile, fd, flags);
29214 if( isDelete ){
29215 #if OS_VXWORKS
29216 zPath = zName;
29217 #else
29218 osUnlink(zName);
29219 #endif
29221 #if SQLITE_ENABLE_LOCKING_STYLE
29222 else{
29223 p->openFlags = openFlags;
29225 #endif
29227 #ifdef FD_CLOEXEC
29228 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29229 #endif
29231 noLock = eType!=SQLITE_OPEN_MAIN_DB;
29234 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29235 struct statfs fsInfo;
29236 if( fstatfs(fd, &fsInfo) == -1 ){
29237 ((unixFile*)pFile)->lastErrno = errno;
29238 robust_close(p, fd, __LINE__);
29239 return SQLITE_IOERR_ACCESS;
29241 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
29242 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
29244 #endif
29246 #if SQLITE_ENABLE_LOCKING_STYLE
29247 #if SQLITE_PREFER_PROXY_LOCKING
29248 isAutoProxy = 1;
29249 #endif
29250 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
29251 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
29252 int useProxy = 0;
29254 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
29255 ** never use proxy, NULL means use proxy for non-local files only. */
29256 if( envforce!=NULL ){
29257 useProxy = atoi(envforce)>0;
29258 }else{
29259 struct statfs fsInfo;
29260 if( statfs(zPath, &fsInfo) == -1 ){
29261 /* In theory, the close(fd) call is sub-optimal. If the file opened
29262 ** with fd is a database file, and there are other connections open
29263 ** on that file that are currently holding advisory locks on it,
29264 ** then the call to close() will cancel those locks. In practice,
29265 ** we're assuming that statfs() doesn't fail very often. At least
29266 ** not while other file descriptors opened by the same process on
29267 ** the same file are working. */
29268 p->lastErrno = errno;
29269 robust_close(p, fd, __LINE__);
29270 rc = SQLITE_IOERR_ACCESS;
29271 goto open_finished;
29273 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
29275 if( useProxy ){
29276 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
29277 isDelete, isReadonly);
29278 if( rc==SQLITE_OK ){
29279 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
29280 if( rc!=SQLITE_OK ){
29281 /* Use unixClose to clean up the resources added in fillInUnixFile
29282 ** and clear all the structure's references. Specifically,
29283 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
29285 unixClose(pFile);
29286 return rc;
29289 goto open_finished;
29292 #endif
29294 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
29295 isDelete, isReadonly);
29296 open_finished:
29297 if( rc!=SQLITE_OK ){
29298 chromium_sqlite3_destroy_reusable_file_handle(pFile);
29300 return rc;
29305 ** Delete the file at zPath. If the dirSync argument is true, fsync()
29306 ** the directory after deleting the file.
29308 static int unixDelete(
29309 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
29310 const char *zPath, /* Name of file to be deleted */
29311 int dirSync /* If true, fsync() directory after deleting file */
29313 int rc = SQLITE_OK;
29314 UNUSED_PARAMETER(NotUsed);
29315 SimulateIOError(return SQLITE_IOERR_DELETE);
29316 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
29317 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
29319 #ifndef SQLITE_DISABLE_DIRSYNC
29320 if( dirSync ){
29321 int fd;
29322 rc = osOpenDirectory(zPath, &fd);
29323 if( rc==SQLITE_OK ){
29324 #if OS_VXWORKS
29325 if( fsync(fd)==-1 )
29326 #else
29327 if( fsync(fd) )
29328 #endif
29330 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
29332 robust_close(0, fd, __LINE__);
29333 }else if( rc==SQLITE_CANTOPEN ){
29334 rc = SQLITE_OK;
29337 #endif
29338 return rc;
29342 ** Test the existance of or access permissions of file zPath. The
29343 ** test performed depends on the value of flags:
29345 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
29346 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
29347 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
29349 ** Otherwise return 0.
29351 static int unixAccess(
29352 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
29353 const char *zPath, /* Path of the file to examine */
29354 int flags, /* What do we want to learn about the zPath file? */
29355 int *pResOut /* Write result boolean here */
29357 int amode = 0;
29358 UNUSED_PARAMETER(NotUsed);
29359 SimulateIOError( return SQLITE_IOERR_ACCESS; );
29360 switch( flags ){
29361 case SQLITE_ACCESS_EXISTS:
29362 amode = F_OK;
29363 break;
29364 case SQLITE_ACCESS_READWRITE:
29365 amode = W_OK|R_OK;
29366 break;
29367 case SQLITE_ACCESS_READ:
29368 amode = R_OK;
29369 break;
29371 default:
29372 assert(!"Invalid flags argument");
29374 *pResOut = (osAccess(zPath, amode)==0);
29375 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
29376 struct stat buf;
29377 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
29378 *pResOut = 0;
29381 return SQLITE_OK;
29386 ** Turn a relative pathname into a full pathname. The relative path
29387 ** is stored as a nul-terminated string in the buffer pointed to by
29388 ** zPath.
29390 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
29391 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
29392 ** this buffer before returning.
29394 static int unixFullPathname(
29395 sqlite3_vfs *pVfs, /* Pointer to vfs object */
29396 const char *zPath, /* Possibly relative input path */
29397 int nOut, /* Size of output buffer in bytes */
29398 char *zOut /* Output buffer */
29401 /* It's odd to simulate an io-error here, but really this is just
29402 ** using the io-error infrastructure to test that SQLite handles this
29403 ** function failing. This function could fail if, for example, the
29404 ** current working directory has been unlinked.
29406 SimulateIOError( return SQLITE_ERROR );
29408 assert( pVfs->mxPathname==MAX_PATHNAME );
29409 UNUSED_PARAMETER(pVfs);
29411 zOut[nOut-1] = '\0';
29412 if( zPath[0]=='/' ){
29413 sqlite3_snprintf(nOut, zOut, "%s", zPath);
29414 }else{
29415 int nCwd;
29416 if( osGetcwd(zOut, nOut-1)==0 ){
29417 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29419 nCwd = (int)strlen(zOut);
29420 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29422 return SQLITE_OK;
29426 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29428 ** Interfaces for opening a shared library, finding entry points
29429 ** within the shared library, and closing the shared library.
29431 #include <dlfcn.h>
29432 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29433 UNUSED_PARAMETER(NotUsed);
29434 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29438 ** SQLite calls this function immediately after a call to unixDlSym() or
29439 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
29440 ** message is available, it is written to zBufOut. If no error message
29441 ** is available, zBufOut is left unmodified and SQLite uses a default
29442 ** error message.
29444 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29445 const char *zErr;
29446 UNUSED_PARAMETER(NotUsed);
29447 unixEnterMutex();
29448 zErr = dlerror();
29449 if( zErr ){
29450 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29452 unixLeaveMutex();
29454 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29456 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29457 ** cast into a pointer to a function. And yet the library dlsym() routine
29458 ** returns a void* which is really a pointer to a function. So how do we
29459 ** use dlsym() with -pedantic-errors?
29461 ** Variable x below is defined to be a pointer to a function taking
29462 ** parameters void* and const char* and returning a pointer to a function.
29463 ** We initialize x by assigning it a pointer to the dlsym() function.
29464 ** (That assignment requires a cast.) Then we call the function that
29465 ** x points to.
29467 ** This work-around is unlikely to work correctly on any system where
29468 ** you really cannot cast a function pointer into void*. But then, on the
29469 ** other hand, dlsym() will not work on such a system either, so we have
29470 ** not really lost anything.
29472 void (*(*x)(void*,const char*))(void);
29473 UNUSED_PARAMETER(NotUsed);
29474 x = (void(*(*)(void*,const char*))(void))dlsym;
29475 return (*x)(p, zSym);
29477 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29478 UNUSED_PARAMETER(NotUsed);
29479 dlclose(pHandle);
29481 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29482 #define unixDlOpen 0
29483 #define unixDlError 0
29484 #define unixDlSym 0
29485 #define unixDlClose 0
29486 #endif
29489 ** Write nBuf bytes of random data to the supplied buffer zBuf.
29491 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29492 UNUSED_PARAMETER(NotUsed);
29493 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29495 /* We have to initialize zBuf to prevent valgrind from reporting
29496 ** errors. The reports issued by valgrind are incorrect - we would
29497 ** prefer that the randomness be increased by making use of the
29498 ** uninitialized space in zBuf - but valgrind errors tend to worry
29499 ** some users. Rather than argue, it seems easier just to initialize
29500 ** the whole array and silence valgrind, even if that means less randomness
29501 ** in the random seed.
29503 ** When testing, initializing zBuf[] to zero is all we do. That means
29504 ** that we always use the same random number sequence. This makes the
29505 ** tests repeatable.
29507 memset(zBuf, 0, nBuf);
29508 #if !defined(SQLITE_TEST)
29510 int pid, fd;
29511 fd = robust_open("/dev/urandom", O_RDONLY, 0);
29512 if( fd<0 ){
29513 time_t t;
29514 time(&t);
29515 memcpy(zBuf, &t, sizeof(t));
29516 pid = getpid();
29517 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29518 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29519 nBuf = sizeof(t) + sizeof(pid);
29520 }else{
29521 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
29522 robust_close(0, fd, __LINE__);
29525 #endif
29526 return nBuf;
29531 ** Sleep for a little while. Return the amount of time slept.
29532 ** The argument is the number of microseconds we want to sleep.
29533 ** The return value is the number of microseconds of sleep actually
29534 ** requested from the underlying operating system, a number which
29535 ** might be greater than or equal to the argument, but not less
29536 ** than the argument.
29538 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29539 #if OS_VXWORKS
29540 struct timespec sp;
29542 sp.tv_sec = microseconds / 1000000;
29543 sp.tv_nsec = (microseconds % 1000000) * 1000;
29544 nanosleep(&sp, NULL);
29545 UNUSED_PARAMETER(NotUsed);
29546 return microseconds;
29547 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
29548 usleep(microseconds);
29549 UNUSED_PARAMETER(NotUsed);
29550 return microseconds;
29551 #else
29552 int seconds = (microseconds+999999)/1000000;
29553 sleep(seconds);
29554 UNUSED_PARAMETER(NotUsed);
29555 return seconds*1000000;
29556 #endif
29560 ** The following variable, if set to a non-zero value, is interpreted as
29561 ** the number of seconds since 1970 and is used to set the result of
29562 ** sqlite3OsCurrentTime() during testing.
29564 #ifdef SQLITE_TEST
29565 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
29566 #endif
29569 ** Find the current time (in Universal Coordinated Time). Write into *piNow
29570 ** the current time and date as a Julian Day number times 86_400_000. In
29571 ** other words, write into *piNow the number of milliseconds since the Julian
29572 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29573 ** proleptic Gregorian calendar.
29575 ** On success, return 0. Return 1 if the time and date cannot be found.
29577 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
29578 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29579 #if defined(NO_GETTOD)
29580 time_t t;
29581 time(&t);
29582 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
29583 #elif OS_VXWORKS
29584 struct timespec sNow;
29585 clock_gettime(CLOCK_REALTIME, &sNow);
29586 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
29587 #else
29588 struct timeval sNow;
29589 gettimeofday(&sNow, 0);
29590 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
29591 #endif
29593 #ifdef SQLITE_TEST
29594 if( sqlite3_current_time ){
29595 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29597 #endif
29598 UNUSED_PARAMETER(NotUsed);
29599 return 0;
29603 ** Find the current time (in Universal Coordinated Time). Write the
29604 ** current time and date as a Julian Day number into *prNow and
29605 ** return 0. Return 1 if the time and date cannot be found.
29607 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
29608 sqlite3_int64 i;
29609 UNUSED_PARAMETER(NotUsed);
29610 unixCurrentTimeInt64(0, &i);
29611 *prNow = i/86400000.0;
29612 return 0;
29616 ** We added the xGetLastError() method with the intention of providing
29617 ** better low-level error messages when operating-system problems come up
29618 ** during SQLite operation. But so far, none of that has been implemented
29619 ** in the core. So this routine is never called. For now, it is merely
29620 ** a place-holder.
29622 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
29623 UNUSED_PARAMETER(NotUsed);
29624 UNUSED_PARAMETER(NotUsed2);
29625 UNUSED_PARAMETER(NotUsed3);
29626 return 0;
29631 ************************ End of sqlite3_vfs methods ***************************
29632 ******************************************************************************/
29634 /******************************************************************************
29635 ************************** Begin Proxy Locking ********************************
29637 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
29638 ** other locking methods on secondary lock files. Proxy locking is a
29639 ** meta-layer over top of the primitive locking implemented above. For
29640 ** this reason, the division that implements of proxy locking is deferred
29641 ** until late in the file (here) after all of the other I/O methods have
29642 ** been defined - so that the primitive locking methods are available
29643 ** as services to help with the implementation of proxy locking.
29645 ****
29647 ** The default locking schemes in SQLite use byte-range locks on the
29648 ** database file to coordinate safe, concurrent access by multiple readers
29649 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
29650 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
29651 ** as POSIX read & write locks over fixed set of locations (via fsctl),
29652 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
29653 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
29654 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
29655 ** address in the shared range is taken for a SHARED lock, the entire
29656 ** shared range is taken for an EXCLUSIVE lock):
29658 ** PENDING_BYTE 0x40000000
29659 ** RESERVED_BYTE 0x40000001
29660 ** SHARED_RANGE 0x40000002 -> 0x40000200
29662 ** This works well on the local file system, but shows a nearly 100x
29663 ** slowdown in read performance on AFP because the AFP client disables
29664 ** the read cache when byte-range locks are present. Enabling the read
29665 ** cache exposes a cache coherency problem that is present on all OS X
29666 ** supported network file systems. NFS and AFP both observe the
29667 ** close-to-open semantics for ensuring cache coherency
29668 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
29669 ** address the requirements for concurrent database access by multiple
29670 ** readers and writers
29671 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
29673 ** To address the performance and cache coherency issues, proxy file locking
29674 ** changes the way database access is controlled by limiting access to a
29675 ** single host at a time and moving file locks off of the database file
29676 ** and onto a proxy file on the local file system.
29679 ** Using proxy locks
29680 ** -----------------
29682 ** C APIs
29684 ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
29685 ** <proxy_path> | ":auto:");
29686 ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
29689 ** SQL pragmas
29691 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
29692 ** PRAGMA [database.]lock_proxy_file
29694 ** Specifying ":auto:" means that if there is a conch file with a matching
29695 ** host ID in it, the proxy path in the conch file will be used, otherwise
29696 ** a proxy path based on the user's temp dir
29697 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
29698 ** actual proxy file name is generated from the name and path of the
29699 ** database file. For example:
29701 ** For database path "/Users/me/foo.db"
29702 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
29704 ** Once a lock proxy is configured for a database connection, it can not
29705 ** be removed, however it may be switched to a different proxy path via
29706 ** the above APIs (assuming the conch file is not being held by another
29707 ** connection or process).
29710 ** How proxy locking works
29711 ** -----------------------
29713 ** Proxy file locking relies primarily on two new supporting files:
29715 ** * conch file to limit access to the database file to a single host
29716 ** at a time
29718 ** * proxy file to act as a proxy for the advisory locks normally
29719 ** taken on the database
29721 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
29722 ** by taking an sqlite-style shared lock on the conch file, reading the
29723 ** contents and comparing the host's unique host ID (see below) and lock
29724 ** proxy path against the values stored in the conch. The conch file is
29725 ** stored in the same directory as the database file and the file name
29726 ** is patterned after the database file name as ".<databasename>-conch".
29727 ** If the conch file does not exist, or it's contents do not match the
29728 ** host ID and/or proxy path, then the lock is escalated to an exclusive
29729 ** lock and the conch file contents is updated with the host ID and proxy
29730 ** path and the lock is downgraded to a shared lock again. If the conch
29731 ** is held by another process (with a shared lock), the exclusive lock
29732 ** will fail and SQLITE_BUSY is returned.
29734 ** The proxy file - a single-byte file used for all advisory file locks
29735 ** normally taken on the database file. This allows for safe sharing
29736 ** of the database file for multiple readers and writers on the same
29737 ** host (the conch ensures that they all use the same local lock file).
29739 ** Requesting the lock proxy does not immediately take the conch, it is
29740 ** only taken when the first request to lock database file is made.
29741 ** This matches the semantics of the traditional locking behavior, where
29742 ** opening a connection to a database file does not take a lock on it.
29743 ** The shared lock and an open file descriptor are maintained until
29744 ** the connection to the database is closed.
29746 ** The proxy file and the lock file are never deleted so they only need
29747 ** to be created the first time they are used.
29749 ** Configuration options
29750 ** ---------------------
29752 ** SQLITE_PREFER_PROXY_LOCKING
29754 ** Database files accessed on non-local file systems are
29755 ** automatically configured for proxy locking, lock files are
29756 ** named automatically using the same logic as
29757 ** PRAGMA lock_proxy_file=":auto:"
29759 ** SQLITE_PROXY_DEBUG
29761 ** Enables the logging of error messages during host id file
29762 ** retrieval and creation
29764 ** LOCKPROXYDIR
29766 ** Overrides the default directory used for lock proxy files that
29767 ** are named automatically via the ":auto:" setting
29769 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29771 ** Permissions to use when creating a directory for storing the
29772 ** lock proxy files, only used when LOCKPROXYDIR is not set.
29775 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
29776 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
29777 ** force proxy locking to be used for every database file opened, and 0
29778 ** will force automatic proxy locking to be disabled for all database
29779 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
29780 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
29784 ** Proxy locking is only available on MacOSX
29786 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29789 ** The proxyLockingContext has the path and file structures for the remote
29790 ** and local proxy files in it
29792 typedef struct proxyLockingContext proxyLockingContext;
29793 struct proxyLockingContext {
29794 unixFile *conchFile; /* Open conch file */
29795 char *conchFilePath; /* Name of the conch file */
29796 unixFile *lockProxy; /* Open proxy lock file */
29797 char *lockProxyPath; /* Name of the proxy lock file */
29798 char *dbPath; /* Name of the open file */
29799 int conchHeld; /* 1 if the conch is held, -1 if lockless */
29800 void *oldLockingContext; /* Original lockingcontext to restore on close */
29801 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
29805 ** The proxy lock file path for the database at dbPath is written into lPath,
29806 ** which must point to valid, writable memory large enough for a maxLen length
29807 ** file path.
29809 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
29810 int len;
29811 int dbLen;
29812 int i;
29814 #ifdef LOCKPROXYDIR
29815 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
29816 #else
29817 # ifdef _CS_DARWIN_USER_TEMP_DIR
29819 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
29820 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
29821 lPath, errno, getpid()));
29822 return SQLITE_IOERR_LOCK;
29824 len = strlcat(lPath, "sqliteplocks", maxLen);
29826 # else
29827 len = strlcpy(lPath, "/tmp/", maxLen);
29828 # endif
29829 #endif
29831 if( lPath[len-1]!='/' ){
29832 len = strlcat(lPath, "/", maxLen);
29835 /* transform the db path to a unique cache name */
29836 dbLen = (int)strlen(dbPath);
29837 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
29838 char c = dbPath[i];
29839 lPath[i+len] = (c=='/')?'_':c;
29841 lPath[i+len]='\0';
29842 strlcat(lPath, ":auto:", maxLen);
29843 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
29844 return SQLITE_OK;
29848 ** Creates the lock file and any missing directories in lockPath
29850 static int proxyCreateLockPath(const char *lockPath){
29851 int i, len;
29852 char buf[MAXPATHLEN];
29853 int start = 0;
29855 assert(lockPath!=NULL);
29856 /* try to create all the intermediate directories */
29857 len = (int)strlen(lockPath);
29858 buf[0] = lockPath[0];
29859 for( i=1; i<len; i++ ){
29860 if( lockPath[i] == '/' && (i - start > 0) ){
29861 /* only mkdir if leaf dir != "." or "/" or ".." */
29862 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
29863 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
29864 buf[i]='\0';
29865 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
29866 int err=errno;
29867 if( err!=EEXIST ) {
29868 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
29869 "'%s' proxy lock path=%s pid=%d\n",
29870 buf, strerror(err), lockPath, getpid()));
29871 return err;
29875 start=i+1;
29877 buf[i] = lockPath[i];
29879 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
29880 return 0;
29884 ** Create a new VFS file descriptor (stored in memory obtained from
29885 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
29887 ** The caller is responsible not only for closing the file descriptor
29888 ** but also for freeing the memory associated with the file descriptor.
29890 static int proxyCreateUnixFile(
29891 const char *path, /* path for the new unixFile */
29892 unixFile **ppFile, /* unixFile created and returned by ref */
29893 int islockfile /* if non zero missing dirs will be created */
29895 int fd = -1;
29896 unixFile *pNew;
29897 int rc = SQLITE_OK;
29898 int openFlags = O_RDWR | O_CREAT;
29899 sqlite3_vfs dummyVfs;
29900 int terrno = 0;
29901 UnixUnusedFd *pUnused = NULL;
29903 /* 1. first try to open/create the file
29904 ** 2. if that fails, and this is a lock file (not-conch), try creating
29905 ** the parent directories and then try again.
29906 ** 3. if that fails, try to open the file read-only
29907 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
29909 pUnused = findReusableFd(path, openFlags);
29910 if( pUnused ){
29911 fd = pUnused->fd;
29912 }else{
29913 pUnused = sqlite3_malloc(sizeof(*pUnused));
29914 if( !pUnused ){
29915 return SQLITE_NOMEM;
29918 if( fd<0 ){
29919 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29920 terrno = errno;
29921 if( fd<0 && errno==ENOENT && islockfile ){
29922 if( proxyCreateLockPath(path) == SQLITE_OK ){
29923 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29927 if( fd<0 ){
29928 openFlags = O_RDONLY;
29929 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29930 terrno = errno;
29932 if( fd<0 ){
29933 if( islockfile ){
29934 return SQLITE_BUSY;
29936 switch (terrno) {
29937 case EACCES:
29938 return SQLITE_PERM;
29939 case EIO:
29940 return SQLITE_IOERR_LOCK; /* even though it is the conch */
29941 default:
29942 return SQLITE_CANTOPEN_BKPT;
29946 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
29947 if( pNew==NULL ){
29948 rc = SQLITE_NOMEM;
29949 goto end_create_proxy;
29951 memset(pNew, 0, sizeof(unixFile));
29952 pNew->openFlags = openFlags;
29953 memset(&dummyVfs, 0, sizeof(dummyVfs));
29954 dummyVfs.pAppData = (void*)&autolockIoFinder;
29955 dummyVfs.zName = "dummy";
29956 pUnused->fd = fd;
29957 pUnused->flags = openFlags;
29958 pNew->pUnused = pUnused;
29960 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
29961 if( rc==SQLITE_OK ){
29962 *ppFile = pNew;
29963 return SQLITE_OK;
29965 end_create_proxy:
29966 robust_close(pNew, fd, __LINE__);
29967 sqlite3_free(pNew);
29968 sqlite3_free(pUnused);
29969 return rc;
29972 #ifdef SQLITE_TEST
29973 /* simulate multiple hosts by creating unique hostid file paths */
29974 SQLITE_API int sqlite3_hostid_num = 0;
29975 #endif
29977 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
29979 /* Not always defined in the headers as it ought to be */
29980 extern int gethostuuid(uuid_t id, const struct timespec *wait);
29982 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
29983 ** bytes of writable memory.
29985 static int proxyGetHostID(unsigned char *pHostID, int *pError){
29986 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
29987 memset(pHostID, 0, PROXY_HOSTIDLEN);
29988 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
29989 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
29991 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
29992 if( gethostuuid(pHostID, &timeout) ){
29993 int err = errno;
29994 if( pError ){
29995 *pError = err;
29997 return SQLITE_IOERR;
30000 #endif
30001 #ifdef SQLITE_TEST
30002 /* simulate multiple hosts by creating unique hostid file paths */
30003 if( sqlite3_hostid_num != 0){
30004 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
30006 #endif
30008 return SQLITE_OK;
30011 /* The conch file contains the header, host id and lock file path
30013 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
30014 #define PROXY_HEADERLEN 1 /* conch file header length */
30015 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
30016 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
30019 ** Takes an open conch file, copies the contents to a new path and then moves
30020 ** it back. The newly created file's file descriptor is assigned to the
30021 ** conch file structure and finally the original conch file descriptor is
30022 ** closed. Returns zero if successful.
30024 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
30025 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30026 unixFile *conchFile = pCtx->conchFile;
30027 char tPath[MAXPATHLEN];
30028 char buf[PROXY_MAXCONCHLEN];
30029 char *cPath = pCtx->conchFilePath;
30030 size_t readLen = 0;
30031 size_t pathLen = 0;
30032 char errmsg[64] = "";
30033 int fd = -1;
30034 int rc = -1;
30035 UNUSED_PARAMETER(myHostID);
30037 /* create a new path by replace the trailing '-conch' with '-break' */
30038 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
30039 if( pathLen>MAXPATHLEN || pathLen<6 ||
30040 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
30041 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
30042 goto end_breaklock;
30044 /* read the conch content */
30045 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
30046 if( readLen<PROXY_PATHINDEX ){
30047 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
30048 goto end_breaklock;
30050 /* write it out to the temporary break file */
30051 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
30052 SQLITE_DEFAULT_FILE_PERMISSIONS);
30053 if( fd<0 ){
30054 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
30055 goto end_breaklock;
30057 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
30058 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
30059 goto end_breaklock;
30061 if( rename(tPath, cPath) ){
30062 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
30063 goto end_breaklock;
30065 rc = 0;
30066 fprintf(stderr, "broke stale lock on %s\n", cPath);
30067 robust_close(pFile, conchFile->h, __LINE__);
30068 conchFile->h = fd;
30069 conchFile->openFlags = O_RDWR | O_CREAT;
30071 end_breaklock:
30072 if( rc ){
30073 if( fd>=0 ){
30074 osUnlink(tPath);
30075 robust_close(pFile, fd, __LINE__);
30077 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
30079 return rc;
30082 /* Take the requested lock on the conch file and break a stale lock if the
30083 ** host id matches.
30085 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
30086 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30087 unixFile *conchFile = pCtx->conchFile;
30088 int rc = SQLITE_OK;
30089 int nTries = 0;
30090 struct timespec conchModTime;
30092 do {
30093 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30094 nTries ++;
30095 if( rc==SQLITE_BUSY ){
30096 /* If the lock failed (busy):
30097 * 1st try: get the mod time of the conch, wait 0.5s and try again.
30098 * 2nd try: fail if the mod time changed or host id is different, wait
30099 * 10 sec and try again
30100 * 3rd try: break the lock unless the mod time has changed.
30102 struct stat buf;
30103 if( osFstat(conchFile->h, &buf) ){
30104 pFile->lastErrno = errno;
30105 return SQLITE_IOERR_LOCK;
30108 if( nTries==1 ){
30109 conchModTime = buf.st_mtimespec;
30110 usleep(500000); /* wait 0.5 sec and try the lock again*/
30111 continue;
30114 assert( nTries>1 );
30115 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
30116 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
30117 return SQLITE_BUSY;
30120 if( nTries==2 ){
30121 char tBuf[PROXY_MAXCONCHLEN];
30122 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
30123 if( len<0 ){
30124 pFile->lastErrno = errno;
30125 return SQLITE_IOERR_LOCK;
30127 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
30128 /* don't break the lock if the host id doesn't match */
30129 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
30130 return SQLITE_BUSY;
30132 }else{
30133 /* don't break the lock on short read or a version mismatch */
30134 return SQLITE_BUSY;
30136 usleep(10000000); /* wait 10 sec and try the lock again */
30137 continue;
30140 assert( nTries==3 );
30141 if( 0==proxyBreakConchLock(pFile, myHostID) ){
30142 rc = SQLITE_OK;
30143 if( lockType==EXCLUSIVE_LOCK ){
30144 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
30146 if( !rc ){
30147 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30151 } while( rc==SQLITE_BUSY && nTries<3 );
30153 return rc;
30156 /* Takes the conch by taking a shared lock and read the contents conch, if
30157 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
30158 ** lockPath means that the lockPath in the conch file will be used if the
30159 ** host IDs match, or a new lock path will be generated automatically
30160 ** and written to the conch file.
30162 static int proxyTakeConch(unixFile *pFile){
30163 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30165 if( pCtx->conchHeld!=0 ){
30166 return SQLITE_OK;
30167 }else{
30168 unixFile *conchFile = pCtx->conchFile;
30169 uuid_t myHostID;
30170 int pError = 0;
30171 char readBuf[PROXY_MAXCONCHLEN];
30172 char lockPath[MAXPATHLEN];
30173 char *tempLockPath = NULL;
30174 int rc = SQLITE_OK;
30175 int createConch = 0;
30176 int hostIdMatch = 0;
30177 int readLen = 0;
30178 int tryOldLockPath = 0;
30179 int forceNewLockPath = 0;
30181 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
30182 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
30184 rc = proxyGetHostID(myHostID, &pError);
30185 if( (rc&0xff)==SQLITE_IOERR ){
30186 pFile->lastErrno = pError;
30187 goto end_takeconch;
30189 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
30190 if( rc!=SQLITE_OK ){
30191 goto end_takeconch;
30193 /* read the existing conch file */
30194 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
30195 if( readLen<0 ){
30196 /* I/O error: lastErrno set by seekAndRead */
30197 pFile->lastErrno = conchFile->lastErrno;
30198 rc = SQLITE_IOERR_READ;
30199 goto end_takeconch;
30200 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
30201 readBuf[0]!=(char)PROXY_CONCHVERSION ){
30202 /* a short read or version format mismatch means we need to create a new
30203 ** conch file.
30205 createConch = 1;
30207 /* if the host id matches and the lock path already exists in the conch
30208 ** we'll try to use the path there, if we can't open that path, we'll
30209 ** retry with a new auto-generated path
30211 do { /* in case we need to try again for an :auto: named lock file */
30213 if( !createConch && !forceNewLockPath ){
30214 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
30215 PROXY_HOSTIDLEN);
30216 /* if the conch has data compare the contents */
30217 if( !pCtx->lockProxyPath ){
30218 /* for auto-named local lock file, just check the host ID and we'll
30219 ** use the local lock file path that's already in there
30221 if( hostIdMatch ){
30222 size_t pathLen = (readLen - PROXY_PATHINDEX);
30224 if( pathLen>=MAXPATHLEN ){
30225 pathLen=MAXPATHLEN-1;
30227 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
30228 lockPath[pathLen] = 0;
30229 tempLockPath = lockPath;
30230 tryOldLockPath = 1;
30231 /* create a copy of the lock path if the conch is taken */
30232 goto end_takeconch;
30234 }else if( hostIdMatch
30235 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
30236 readLen-PROXY_PATHINDEX)
30238 /* conch host and lock path match */
30239 goto end_takeconch;
30243 /* if the conch isn't writable and doesn't match, we can't take it */
30244 if( (conchFile->openFlags&O_RDWR) == 0 ){
30245 rc = SQLITE_BUSY;
30246 goto end_takeconch;
30249 /* either the conch didn't match or we need to create a new one */
30250 if( !pCtx->lockProxyPath ){
30251 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
30252 tempLockPath = lockPath;
30253 /* create a copy of the lock path _only_ if the conch is taken */
30256 /* update conch with host and path (this will fail if other process
30257 ** has a shared lock already), if the host id matches, use the big
30258 ** stick.
30260 futimes(conchFile->h, NULL);
30261 if( hostIdMatch && !createConch ){
30262 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
30263 /* We are trying for an exclusive lock but another thread in this
30264 ** same process is still holding a shared lock. */
30265 rc = SQLITE_BUSY;
30266 } else {
30267 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
30269 }else{
30270 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
30272 if( rc==SQLITE_OK ){
30273 char writeBuffer[PROXY_MAXCONCHLEN];
30274 int writeSize = 0;
30276 writeBuffer[0] = (char)PROXY_CONCHVERSION;
30277 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
30278 if( pCtx->lockProxyPath!=NULL ){
30279 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
30280 }else{
30281 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
30283 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
30284 robust_ftruncate(conchFile->h, writeSize);
30285 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
30286 fsync(conchFile->h);
30287 /* If we created a new conch file (not just updated the contents of a
30288 ** valid conch file), try to match the permissions of the database
30290 if( rc==SQLITE_OK && createConch ){
30291 struct stat buf;
30292 int err = osFstat(pFile->h, &buf);
30293 if( err==0 ){
30294 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
30295 S_IROTH|S_IWOTH);
30296 /* try to match the database file R/W permissions, ignore failure */
30297 #ifndef SQLITE_PROXY_DEBUG
30298 osFchmod(conchFile->h, cmode);
30299 #else
30301 rc = osFchmod(conchFile->h, cmode);
30302 }while( rc==(-1) && errno==EINTR );
30303 if( rc!=0 ){
30304 int code = errno;
30305 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
30306 cmode, code, strerror(code));
30307 } else {
30308 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
30310 }else{
30311 int code = errno;
30312 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
30313 err, code, strerror(code));
30314 #endif
30318 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
30320 end_takeconch:
30321 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
30322 if( rc==SQLITE_OK && pFile->openFlags ){
30323 if( pFile->h>=0 ){
30324 robust_close(pFile, pFile->h, __LINE__);
30326 pFile->h = -1;
30327 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
30328 SQLITE_DEFAULT_FILE_PERMISSIONS);
30329 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
30330 if( fd>=0 ){
30331 pFile->h = fd;
30332 }else{
30333 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
30334 during locking */
30337 if( rc==SQLITE_OK && !pCtx->lockProxy ){
30338 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
30339 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
30340 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
30341 /* we couldn't create the proxy lock file with the old lock file path
30342 ** so try again via auto-naming
30344 forceNewLockPath = 1;
30345 tryOldLockPath = 0;
30346 continue; /* go back to the do {} while start point, try again */
30349 if( rc==SQLITE_OK ){
30350 /* Need to make a copy of path if we extracted the value
30351 ** from the conch file or the path was allocated on the stack
30353 if( tempLockPath ){
30354 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
30355 if( !pCtx->lockProxyPath ){
30356 rc = SQLITE_NOMEM;
30360 if( rc==SQLITE_OK ){
30361 pCtx->conchHeld = 1;
30363 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
30364 afpLockingContext *afpCtx;
30365 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
30366 afpCtx->dbPath = pCtx->lockProxyPath;
30368 } else {
30369 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30371 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
30372 rc==SQLITE_OK?"ok":"failed"));
30373 return rc;
30374 } while (1); /* in case we need to retry the :auto: lock file -
30375 ** we should never get here except via the 'continue' call. */
30380 ** If pFile holds a lock on a conch file, then release that lock.
30382 static int proxyReleaseConch(unixFile *pFile){
30383 int rc = SQLITE_OK; /* Subroutine return code */
30384 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
30385 unixFile *conchFile; /* Name of the conch file */
30387 pCtx = (proxyLockingContext *)pFile->lockingContext;
30388 conchFile = pCtx->conchFile;
30389 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
30390 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
30391 getpid()));
30392 if( pCtx->conchHeld>0 ){
30393 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30395 pCtx->conchHeld = 0;
30396 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
30397 (rc==SQLITE_OK ? "ok" : "failed")));
30398 return rc;
30402 ** Given the name of a database file, compute the name of its conch file.
30403 ** Store the conch filename in memory obtained from sqlite3_malloc().
30404 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
30405 ** or SQLITE_NOMEM if unable to obtain memory.
30407 ** The caller is responsible for ensuring that the allocated memory
30408 ** space is eventually freed.
30410 ** *pConchPath is set to NULL if a memory allocation error occurs.
30412 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30413 int i; /* Loop counter */
30414 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30415 char *conchPath; /* buffer in which to construct conch name */
30417 /* Allocate space for the conch filename and initialize the name to
30418 ** the name of the original database file. */
30419 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30420 if( conchPath==0 ){
30421 return SQLITE_NOMEM;
30423 memcpy(conchPath, dbPath, len+1);
30425 /* now insert a "." before the last / character */
30426 for( i=(len-1); i>=0; i-- ){
30427 if( conchPath[i]=='/' ){
30428 i++;
30429 break;
30432 conchPath[i]='.';
30433 while ( i<len ){
30434 conchPath[i+1]=dbPath[i];
30435 i++;
30438 /* append the "-conch" suffix to the file */
30439 memcpy(&conchPath[i+1], "-conch", 7);
30440 assert( (int)strlen(conchPath) == len+7 );
30442 return SQLITE_OK;
30446 /* Takes a fully configured proxy locking-style unix file and switches
30447 ** the local lock file path
30449 static int switchLockProxyPath(unixFile *pFile, const char *path) {
30450 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30451 char *oldPath = pCtx->lockProxyPath;
30452 int rc = SQLITE_OK;
30454 if( pFile->eFileLock!=NO_LOCK ){
30455 return SQLITE_BUSY;
30458 /* nothing to do if the path is NULL, :auto: or matches the existing path */
30459 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30460 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30461 return SQLITE_OK;
30462 }else{
30463 unixFile *lockProxy = pCtx->lockProxy;
30464 pCtx->lockProxy=NULL;
30465 pCtx->conchHeld = 0;
30466 if( lockProxy!=NULL ){
30467 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30468 if( rc ) return rc;
30469 sqlite3_free(lockProxy);
30471 sqlite3_free(oldPath);
30472 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30475 return rc;
30479 ** pFile is a file that has been opened by a prior xOpen call. dbPath
30480 ** is a string buffer at least MAXPATHLEN+1 characters in size.
30482 ** This routine find the filename associated with pFile and writes it
30483 ** int dbPath.
30485 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30486 #if defined(__APPLE__)
30487 if( pFile->pMethod == &afpIoMethods ){
30488 /* afp style keeps a reference to the db path in the filePath field
30489 ** of the struct */
30490 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30491 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30492 } else
30493 #endif
30494 if( pFile->pMethod == &dotlockIoMethods ){
30495 /* dot lock style uses the locking context to store the dot lock
30496 ** file path */
30497 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30498 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30499 }else{
30500 /* all other styles use the locking context to store the db file path */
30501 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30502 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30504 return SQLITE_OK;
30508 ** Takes an already filled in unix file and alters it so all file locking
30509 ** will be performed on the local proxy lock file. The following fields
30510 ** are preserved in the locking context so that they can be restored and
30511 ** the unix structure properly cleaned up at close time:
30512 ** ->lockingContext
30513 ** ->pMethod
30515 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30516 proxyLockingContext *pCtx;
30517 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
30518 char *lockPath=NULL;
30519 int rc = SQLITE_OK;
30521 if( pFile->eFileLock!=NO_LOCK ){
30522 return SQLITE_BUSY;
30524 proxyGetDbPathForUnixFile(pFile, dbPath);
30525 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30526 lockPath=NULL;
30527 }else{
30528 lockPath=(char *)path;
30531 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
30532 (lockPath ? lockPath : ":auto:"), getpid()));
30534 pCtx = sqlite3_malloc( sizeof(*pCtx) );
30535 if( pCtx==0 ){
30536 return SQLITE_NOMEM;
30538 memset(pCtx, 0, sizeof(*pCtx));
30540 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30541 if( rc==SQLITE_OK ){
30542 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30543 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30544 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30545 ** (c) the file system is read-only, then enable no-locking access.
30546 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30547 ** that openFlags will have only one of O_RDONLY or O_RDWR.
30549 struct statfs fsInfo;
30550 struct stat conchInfo;
30551 int goLockless = 0;
30553 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30554 int err = errno;
30555 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30556 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30559 if( goLockless ){
30560 pCtx->conchHeld = -1; /* read only FS/ lockless */
30561 rc = SQLITE_OK;
30565 if( rc==SQLITE_OK && lockPath ){
30566 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30569 if( rc==SQLITE_OK ){
30570 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
30571 if( pCtx->dbPath==NULL ){
30572 rc = SQLITE_NOMEM;
30575 if( rc==SQLITE_OK ){
30576 /* all memory is allocated, proxys are created and assigned,
30577 ** switch the locking context and pMethod then return.
30579 pCtx->oldLockingContext = pFile->lockingContext;
30580 pFile->lockingContext = pCtx;
30581 pCtx->pOldMethod = pFile->pMethod;
30582 pFile->pMethod = &proxyIoMethods;
30583 }else{
30584 if( pCtx->conchFile ){
30585 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
30586 sqlite3_free(pCtx->conchFile);
30588 sqlite3DbFree(0, pCtx->lockProxyPath);
30589 sqlite3_free(pCtx->conchFilePath);
30590 sqlite3_free(pCtx);
30592 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
30593 (rc==SQLITE_OK ? "ok" : "failed")));
30594 return rc;
30599 ** This routine handles sqlite3_file_control() calls that are specific
30600 ** to proxy locking.
30602 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
30603 switch( op ){
30604 case SQLITE_GET_LOCKPROXYFILE: {
30605 unixFile *pFile = (unixFile*)id;
30606 if( pFile->pMethod == &proxyIoMethods ){
30607 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30608 proxyTakeConch(pFile);
30609 if( pCtx->lockProxyPath ){
30610 *(const char **)pArg = pCtx->lockProxyPath;
30611 }else{
30612 *(const char **)pArg = ":auto: (not held)";
30614 } else {
30615 *(const char **)pArg = NULL;
30617 return SQLITE_OK;
30619 case SQLITE_SET_LOCKPROXYFILE: {
30620 unixFile *pFile = (unixFile*)id;
30621 int rc = SQLITE_OK;
30622 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
30623 if( pArg==NULL || (const char *)pArg==0 ){
30624 if( isProxyStyle ){
30625 /* turn off proxy locking - not supported */
30626 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
30627 }else{
30628 /* turn off proxy locking - already off - NOOP */
30629 rc = SQLITE_OK;
30631 }else{
30632 const char *proxyPath = (const char *)pArg;
30633 if( isProxyStyle ){
30634 proxyLockingContext *pCtx =
30635 (proxyLockingContext*)pFile->lockingContext;
30636 if( !strcmp(pArg, ":auto:")
30637 || (pCtx->lockProxyPath &&
30638 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
30640 rc = SQLITE_OK;
30641 }else{
30642 rc = switchLockProxyPath(pFile, proxyPath);
30644 }else{
30645 /* turn on proxy file locking */
30646 rc = proxyTransformUnixFile(pFile, proxyPath);
30649 return rc;
30651 default: {
30652 assert( 0 ); /* The call assures that only valid opcodes are sent */
30655 /*NOTREACHED*/
30656 return SQLITE_ERROR;
30660 ** Within this division (the proxying locking implementation) the procedures
30661 ** above this point are all utilities. The lock-related methods of the
30662 ** proxy-locking sqlite3_io_method object follow.
30667 ** This routine checks if there is a RESERVED lock held on the specified
30668 ** file by this or any other process. If such a lock is held, set *pResOut
30669 ** to a non-zero value otherwise *pResOut is set to zero. The return value
30670 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30672 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
30673 unixFile *pFile = (unixFile*)id;
30674 int rc = proxyTakeConch(pFile);
30675 if( rc==SQLITE_OK ){
30676 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30677 if( pCtx->conchHeld>0 ){
30678 unixFile *proxy = pCtx->lockProxy;
30679 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
30680 }else{ /* conchHeld < 0 is lockless */
30681 pResOut=0;
30684 return rc;
30688 ** Lock the file with the lock specified by parameter eFileLock - one
30689 ** of the following:
30691 ** (1) SHARED_LOCK
30692 ** (2) RESERVED_LOCK
30693 ** (3) PENDING_LOCK
30694 ** (4) EXCLUSIVE_LOCK
30696 ** Sometimes when requesting one lock state, additional lock states
30697 ** are inserted in between. The locking might fail on one of the later
30698 ** transitions leaving the lock state different from what it started but
30699 ** still short of its goal. The following chart shows the allowed
30700 ** transitions and the inserted intermediate states:
30702 ** UNLOCKED -> SHARED
30703 ** SHARED -> RESERVED
30704 ** SHARED -> (PENDING) -> EXCLUSIVE
30705 ** RESERVED -> (PENDING) -> EXCLUSIVE
30706 ** PENDING -> EXCLUSIVE
30708 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
30709 ** routine to lower a locking level.
30711 static int proxyLock(sqlite3_file *id, int eFileLock) {
30712 unixFile *pFile = (unixFile*)id;
30713 int rc = proxyTakeConch(pFile);
30714 if( rc==SQLITE_OK ){
30715 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30716 if( pCtx->conchHeld>0 ){
30717 unixFile *proxy = pCtx->lockProxy;
30718 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
30719 pFile->eFileLock = proxy->eFileLock;
30720 }else{
30721 /* conchHeld < 0 is lockless */
30724 return rc;
30729 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
30730 ** must be either NO_LOCK or SHARED_LOCK.
30732 ** If the locking level of the file descriptor is already at or below
30733 ** the requested locking level, this routine is a no-op.
30735 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
30736 unixFile *pFile = (unixFile*)id;
30737 int rc = proxyTakeConch(pFile);
30738 if( rc==SQLITE_OK ){
30739 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30740 if( pCtx->conchHeld>0 ){
30741 unixFile *proxy = pCtx->lockProxy;
30742 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
30743 pFile->eFileLock = proxy->eFileLock;
30744 }else{
30745 /* conchHeld < 0 is lockless */
30748 return rc;
30752 ** Close a file that uses proxy locks.
30754 static int proxyClose(sqlite3_file *id) {
30755 if( id ){
30756 unixFile *pFile = (unixFile*)id;
30757 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30758 unixFile *lockProxy = pCtx->lockProxy;
30759 unixFile *conchFile = pCtx->conchFile;
30760 int rc = SQLITE_OK;
30762 if( lockProxy ){
30763 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
30764 if( rc ) return rc;
30765 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
30766 if( rc ) return rc;
30767 sqlite3_free(lockProxy);
30768 pCtx->lockProxy = 0;
30770 if( conchFile ){
30771 if( pCtx->conchHeld ){
30772 rc = proxyReleaseConch(pFile);
30773 if( rc ) return rc;
30775 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
30776 if( rc ) return rc;
30777 sqlite3_free(conchFile);
30779 sqlite3DbFree(0, pCtx->lockProxyPath);
30780 sqlite3_free(pCtx->conchFilePath);
30781 sqlite3DbFree(0, pCtx->dbPath);
30782 /* restore the original locking context and pMethod then close it */
30783 pFile->lockingContext = pCtx->oldLockingContext;
30784 pFile->pMethod = pCtx->pOldMethod;
30785 sqlite3_free(pCtx);
30786 return pFile->pMethod->xClose(id);
30788 return SQLITE_OK;
30793 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30795 ** The proxy locking style is intended for use with AFP filesystems.
30796 ** And since AFP is only supported on MacOSX, the proxy locking is also
30797 ** restricted to MacOSX.
30800 ******************* End of the proxy lock implementation **********************
30801 ******************************************************************************/
30804 ** Initialize the operating system interface.
30806 ** This routine registers all VFS implementations for unix-like operating
30807 ** systems. This routine, and the sqlite3_os_end() routine that follows,
30808 ** should be the only routines in this file that are visible from other
30809 ** files.
30811 ** This routine is called once during SQLite initialization and by a
30812 ** single thread. The memory allocation and mutex subsystems have not
30813 ** necessarily been initialized when this routine is called, and so they
30814 ** should not be used.
30816 SQLITE_API int sqlite3_os_init(void){
30818 ** The following macro defines an initializer for an sqlite3_vfs object.
30819 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
30820 ** to the "finder" function. (pAppData is a pointer to a pointer because
30821 ** silly C90 rules prohibit a void* from being cast to a function pointer
30822 ** and so we have to go through the intermediate pointer to avoid problems
30823 ** when compiling with -pedantic-errors on GCC.)
30825 ** The FINDER parameter to this macro is the name of the pointer to the
30826 ** finder-function. The finder-function returns a pointer to the
30827 ** sqlite_io_methods object that implements the desired locking
30828 ** behaviors. See the division above that contains the IOMETHODS
30829 ** macro for addition information on finder-functions.
30831 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
30832 ** object. But the "autolockIoFinder" available on MacOSX does a little
30833 ** more than that; it looks at the filesystem type that hosts the
30834 ** database file and tries to choose an locking method appropriate for
30835 ** that filesystem time.
30837 #define UNIXVFS(VFSNAME, FINDER) { \
30838 3, /* iVersion */ \
30839 sizeof(unixFile), /* szOsFile */ \
30840 MAX_PATHNAME, /* mxPathname */ \
30841 0, /* pNext */ \
30842 VFSNAME, /* zName */ \
30843 (void*)&FINDER, /* pAppData */ \
30844 unixOpen, /* xOpen */ \
30845 unixDelete, /* xDelete */ \
30846 unixAccess, /* xAccess */ \
30847 unixFullPathname, /* xFullPathname */ \
30848 unixDlOpen, /* xDlOpen */ \
30849 unixDlError, /* xDlError */ \
30850 unixDlSym, /* xDlSym */ \
30851 unixDlClose, /* xDlClose */ \
30852 unixRandomness, /* xRandomness */ \
30853 unixSleep, /* xSleep */ \
30854 unixCurrentTime, /* xCurrentTime */ \
30855 unixGetLastError, /* xGetLastError */ \
30856 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
30857 unixSetSystemCall, /* xSetSystemCall */ \
30858 unixGetSystemCall, /* xGetSystemCall */ \
30859 unixNextSystemCall, /* xNextSystemCall */ \
30863 ** All default VFSes for unix are contained in the following array.
30865 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
30866 ** by the SQLite core when the VFS is registered. So the following
30867 ** array cannot be const.
30869 static sqlite3_vfs aVfs[] = {
30870 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
30871 UNIXVFS("unix", autolockIoFinder ),
30872 #else
30873 UNIXVFS("unix", posixIoFinder ),
30874 #endif
30875 UNIXVFS("unix-none", nolockIoFinder ),
30876 UNIXVFS("unix-dotfile", dotlockIoFinder ),
30877 UNIXVFS("unix-excl", posixIoFinder ),
30878 #if OS_VXWORKS
30879 UNIXVFS("unix-namedsem", semIoFinder ),
30880 #endif
30881 #if SQLITE_ENABLE_LOCKING_STYLE
30882 UNIXVFS("unix-posix", posixIoFinder ),
30883 #if !OS_VXWORKS
30884 UNIXVFS("unix-flock", flockIoFinder ),
30885 #endif
30886 #endif
30887 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30888 UNIXVFS("unix-afp", afpIoFinder ),
30889 UNIXVFS("unix-nfs", nfsIoFinder ),
30890 UNIXVFS("unix-proxy", proxyIoFinder ),
30891 #endif
30893 unsigned int i; /* Loop counter */
30895 /* Double-check that the aSyscall[] array has been constructed
30896 ** correctly. See ticket [bb3a86e890c8e96ab] */
30897 assert( ArraySize(aSyscall)==18 );
30899 /* Register all VFSes defined in the aVfs[] array */
30900 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
30901 sqlite3_vfs_register(&aVfs[i], i==0);
30903 return SQLITE_OK;
30907 ** Shutdown the operating system interface.
30909 ** Some operating systems might need to do some cleanup in this routine,
30910 ** to release dynamically allocated objects. But not on unix.
30911 ** This routine is a no-op for unix.
30913 SQLITE_API int sqlite3_os_end(void){
30914 return SQLITE_OK;
30917 #endif /* SQLITE_OS_UNIX */
30919 /************** End of os_unix.c *********************************************/
30920 /************** Begin file os_win.c ******************************************/
30922 ** 2004 May 22
30924 ** The author disclaims copyright to this source code. In place of
30925 ** a legal notice, here is a blessing:
30927 ** May you do good and not evil.
30928 ** May you find forgiveness for yourself and forgive others.
30929 ** May you share freely, never taking more than you give.
30931 ******************************************************************************
30933 ** This file contains code that is specific to windows.
30935 #if SQLITE_OS_WIN /* This file is used for windows only */
30939 ** A Note About Memory Allocation:
30941 ** This driver uses malloc()/free() directly rather than going through
30942 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
30943 ** are designed for use on embedded systems where memory is scarce and
30944 ** malloc failures happen frequently. Win32 does not typically run on
30945 ** embedded systems, and when it does the developers normally have bigger
30946 ** problems to worry about than running out of memory. So there is not
30947 ** a compelling need to use the wrappers.
30949 ** But there is a good reason to not use the wrappers. If we use the
30950 ** wrappers then we will get simulated malloc() failures within this
30951 ** driver. And that causes all kinds of problems for our tests. We
30952 ** could enhance SQLite to deal with simulated malloc failures within
30953 ** the OS driver, but the code to deal with those failure would not
30954 ** be exercised on Linux (which does not need to malloc() in the driver)
30955 ** and so we would have difficulty writing coverage tests for that
30956 ** code. Better to leave the code out, we think.
30958 ** The point of this discussion is as follows: When creating a new
30959 ** OS layer for an embedded system, if you use this file as an example,
30960 ** avoid the use of malloc()/free(). Those routines work ok on windows
30961 ** desktops but not so well in embedded systems.
30964 #include <winbase.h>
30966 #ifdef __CYGWIN__
30967 # include <sys/cygwin.h>
30968 #endif
30971 ** Macros used to determine whether or not to use threads.
30973 #if defined(THREADSAFE) && THREADSAFE
30974 # define SQLITE_W32_THREADS 1
30975 #endif
30978 ** Include code that is common to all os_*.c files
30980 /************** Include os_common.h in the middle of os_win.c ****************/
30981 /************** Begin file os_common.h ***************************************/
30983 ** 2004 May 22
30985 ** The author disclaims copyright to this source code. In place of
30986 ** a legal notice, here is a blessing:
30988 ** May you do good and not evil.
30989 ** May you find forgiveness for yourself and forgive others.
30990 ** May you share freely, never taking more than you give.
30992 ******************************************************************************
30994 ** This file contains macros and a little bit of code that is common to
30995 ** all of the platform-specific files (os_*.c) and is #included into those
30996 ** files.
30998 ** This file should be #included by the os_*.c files only. It is not a
30999 ** general purpose header file.
31001 #ifndef _OS_COMMON_H_
31002 #define _OS_COMMON_H_
31005 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
31006 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
31007 ** switch. The following code should catch this problem at compile-time.
31009 #ifdef MEMORY_DEBUG
31010 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
31011 #endif
31013 #ifdef SQLITE_DEBUG
31014 SQLITE_PRIVATE int sqlite3OSTrace = 0;
31015 #define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
31016 #else
31017 #define OSTRACE(X)
31018 #endif
31021 ** Macros for performance tracing. Normally turned off. Only works
31022 ** on i486 hardware.
31024 #ifdef SQLITE_PERFORMANCE_TRACE
31027 ** hwtime.h contains inline assembler code for implementing
31028 ** high-performance timing routines.
31030 /************** Include hwtime.h in the middle of os_common.h ****************/
31031 /************** Begin file hwtime.h ******************************************/
31033 ** 2008 May 27
31035 ** The author disclaims copyright to this source code. In place of
31036 ** a legal notice, here is a blessing:
31038 ** May you do good and not evil.
31039 ** May you find forgiveness for yourself and forgive others.
31040 ** May you share freely, never taking more than you give.
31042 ******************************************************************************
31044 ** This file contains inline asm code for retrieving "high-performance"
31045 ** counters for x86 class CPUs.
31047 #ifndef _HWTIME_H_
31048 #define _HWTIME_H_
31051 ** The following routine only works on pentium-class (or newer) processors.
31052 ** It uses the RDTSC opcode to read the cycle count value out of the
31053 ** processor and returns that value. This can be used for high-res
31054 ** profiling.
31056 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
31057 (defined(i386) || defined(__i386__) || defined(_M_IX86))
31059 #if defined(__GNUC__)
31061 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31062 unsigned int lo, hi;
31063 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
31064 return (sqlite_uint64)hi << 32 | lo;
31067 #elif defined(_MSC_VER)
31069 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
31070 __asm {
31071 rdtsc
31072 ret ; return value at EDX:EAX
31076 #endif
31078 #elif (defined(__GNUC__) && defined(__x86_64__))
31080 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31081 unsigned long val;
31082 __asm__ __volatile__ ("rdtsc" : "=A" (val));
31083 return val;
31086 #elif (defined(__GNUC__) && defined(__ppc__))
31088 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31089 unsigned long long retval;
31090 unsigned long junk;
31091 __asm__ __volatile__ ("\n\
31092 1: mftbu %1\n\
31093 mftb %L0\n\
31094 mftbu %0\n\
31095 cmpw %0,%1\n\
31096 bne 1b"
31097 : "=r" (retval), "=r" (junk));
31098 return retval;
31101 #else
31103 #error Need implementation of sqlite3Hwtime() for your platform.
31106 ** To compile without implementing sqlite3Hwtime() for your platform,
31107 ** you can remove the above #error and use the following
31108 ** stub function. You will lose timing support for many
31109 ** of the debugging and testing utilities, but it should at
31110 ** least compile and run.
31112 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
31114 #endif
31116 #endif /* !defined(_HWTIME_H_) */
31118 /************** End of hwtime.h **********************************************/
31119 /************** Continuing where we left off in os_common.h ******************/
31121 static sqlite_uint64 g_start;
31122 static sqlite_uint64 g_elapsed;
31123 #define TIMER_START g_start=sqlite3Hwtime()
31124 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
31125 #define TIMER_ELAPSED g_elapsed
31126 #else
31127 #define TIMER_START
31128 #define TIMER_END
31129 #define TIMER_ELAPSED ((sqlite_uint64)0)
31130 #endif
31133 ** If we compile with the SQLITE_TEST macro set, then the following block
31134 ** of code will give us the ability to simulate a disk I/O error. This
31135 ** is used for testing the I/O recovery logic.
31137 #ifdef SQLITE_TEST
31138 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
31139 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
31140 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
31141 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
31142 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
31143 SQLITE_API int sqlite3_diskfull_pending = 0;
31144 SQLITE_API int sqlite3_diskfull = 0;
31145 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
31146 #define SimulateIOError(CODE) \
31147 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
31148 || sqlite3_io_error_pending-- == 1 ) \
31149 { local_ioerr(); CODE; }
31150 static void local_ioerr(){
31151 IOTRACE(("IOERR\n"));
31152 sqlite3_io_error_hit++;
31153 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
31155 #define SimulateDiskfullError(CODE) \
31156 if( sqlite3_diskfull_pending ){ \
31157 if( sqlite3_diskfull_pending == 1 ){ \
31158 local_ioerr(); \
31159 sqlite3_diskfull = 1; \
31160 sqlite3_io_error_hit = 1; \
31161 CODE; \
31162 }else{ \
31163 sqlite3_diskfull_pending--; \
31166 #else
31167 #define SimulateIOErrorBenign(X)
31168 #define SimulateIOError(A)
31169 #define SimulateDiskfullError(A)
31170 #endif
31173 ** When testing, keep a count of the number of open files.
31175 #ifdef SQLITE_TEST
31176 SQLITE_API int sqlite3_open_file_count = 0;
31177 #define OpenCounter(X) sqlite3_open_file_count+=(X)
31178 #else
31179 #define OpenCounter(X)
31180 #endif
31182 #endif /* !defined(_OS_COMMON_H_) */
31184 /************** End of os_common.h *******************************************/
31185 /************** Continuing where we left off in os_win.c *********************/
31188 ** Some microsoft compilers lack this definition.
31190 #ifndef INVALID_FILE_ATTRIBUTES
31191 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
31192 #endif
31195 ** Determine if we are dealing with WindowsCE - which has a much
31196 ** reduced API.
31198 #if SQLITE_OS_WINCE
31199 # define AreFileApisANSI() 1
31200 # define FormatMessageW(a,b,c,d,e,f,g) 0
31201 #endif
31203 /* Forward references */
31204 typedef struct winShm winShm; /* A connection to shared-memory */
31205 typedef struct winShmNode winShmNode; /* A region of shared-memory */
31208 ** WinCE lacks native support for file locking so we have to fake it
31209 ** with some code of our own.
31211 #if SQLITE_OS_WINCE
31212 typedef struct winceLock {
31213 int nReaders; /* Number of reader locks obtained */
31214 BOOL bPending; /* Indicates a pending lock has been obtained */
31215 BOOL bReserved; /* Indicates a reserved lock has been obtained */
31216 BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
31217 } winceLock;
31218 #endif
31221 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
31222 ** portability layer.
31224 typedef struct winFile winFile;
31225 struct winFile {
31226 const sqlite3_io_methods *pMethod; /*** Must be first ***/
31227 sqlite3_vfs *pVfs; /* The VFS used to open this file */
31228 HANDLE h; /* Handle for accessing the file */
31229 unsigned char locktype; /* Type of lock currently held on this file */
31230 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
31231 DWORD lastErrno; /* The Windows errno from the last I/O error */
31232 DWORD sectorSize; /* Sector size of the device file is on */
31233 winShm *pShm; /* Instance of shared memory on this file */
31234 const char *zPath; /* Full pathname of this file */
31235 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
31236 #if SQLITE_OS_WINCE
31237 WCHAR *zDeleteOnClose; /* Name of file to delete when closing */
31238 HANDLE hMutex; /* Mutex used to control access to shared lock */
31239 HANDLE hShared; /* Shared memory segment used for locking */
31240 winceLock local; /* Locks obtained by this instance of winFile */
31241 winceLock *shared; /* Global shared lock memory for the file */
31242 #endif
31246 ** Forward prototypes.
31248 static int getSectorSize(
31249 sqlite3_vfs *pVfs,
31250 const char *zRelative /* UTF-8 file name */
31254 ** The following variable is (normally) set once and never changes
31255 ** thereafter. It records whether the operating system is Win95
31256 ** or WinNT.
31258 ** 0: Operating system unknown.
31259 ** 1: Operating system is Win95.
31260 ** 2: Operating system is WinNT.
31262 ** In order to facilitate testing on a WinNT system, the test fixture
31263 ** can manually set this value to 1 to emulate Win98 behavior.
31265 #ifdef SQLITE_TEST
31266 SQLITE_API int sqlite3_os_type = 0;
31267 #else
31268 static int sqlite3_os_type = 0;
31269 #endif
31272 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31273 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
31275 ** Here is an interesting observation: Win95, Win98, and WinME lack
31276 ** the LockFileEx() API. But we can still statically link against that
31277 ** API as long as we don't call it when running Win95/98/ME. A call to
31278 ** this routine is used to determine if the host is Win95/98/ME or
31279 ** WinNT/2K/XP so that we will know whether or not we can safely call
31280 ** the LockFileEx() API.
31282 #if SQLITE_OS_WINCE
31283 # define isNT() (1)
31284 #else
31285 static int isNT(void){
31286 if( sqlite3_os_type==0 ){
31287 OSVERSIONINFO sInfo;
31288 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31289 GetVersionEx(&sInfo);
31290 sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31292 return sqlite3_os_type==2;
31294 #endif /* SQLITE_OS_WINCE */
31297 ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
31299 ** Space to hold the returned string is obtained from malloc.
31301 static WCHAR *utf8ToUnicode(const char *zFilename){
31302 int nChar;
31303 WCHAR *zWideFilename;
31305 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31306 zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
31307 if( zWideFilename==0 ){
31308 return 0;
31310 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
31311 if( nChar==0 ){
31312 free(zWideFilename);
31313 zWideFilename = 0;
31315 return zWideFilename;
31319 ** Convert microsoft unicode to UTF-8. Space to hold the returned string is
31320 ** obtained from malloc().
31322 static char *unicodeToUtf8(const WCHAR *zWideFilename){
31323 int nByte;
31324 char *zFilename;
31326 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
31327 zFilename = malloc( nByte );
31328 if( zFilename==0 ){
31329 return 0;
31331 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
31332 0, 0);
31333 if( nByte == 0 ){
31334 free(zFilename);
31335 zFilename = 0;
31337 return zFilename;
31341 ** Convert an ansi string to microsoft unicode, based on the
31342 ** current codepage settings for file apis.
31344 ** Space to hold the returned string is obtained
31345 ** from malloc.
31347 static WCHAR *mbcsToUnicode(const char *zFilename){
31348 int nByte;
31349 WCHAR *zMbcsFilename;
31350 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31352 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
31353 zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
31354 if( zMbcsFilename==0 ){
31355 return 0;
31357 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
31358 if( nByte==0 ){
31359 free(zMbcsFilename);
31360 zMbcsFilename = 0;
31362 return zMbcsFilename;
31366 ** Convert microsoft unicode to multibyte character string, based on the
31367 ** user's Ansi codepage.
31369 ** Space to hold the returned string is obtained from
31370 ** malloc().
31372 static char *unicodeToMbcs(const WCHAR *zWideFilename){
31373 int nByte;
31374 char *zFilename;
31375 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31377 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
31378 zFilename = malloc( nByte );
31379 if( zFilename==0 ){
31380 return 0;
31382 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
31383 0, 0);
31384 if( nByte == 0 ){
31385 free(zFilename);
31386 zFilename = 0;
31388 return zFilename;
31392 ** Convert multibyte character string to UTF-8. Space to hold the
31393 ** returned string is obtained from malloc().
31395 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
31396 char *zFilenameUtf8;
31397 WCHAR *zTmpWide;
31399 zTmpWide = mbcsToUnicode(zFilename);
31400 if( zTmpWide==0 ){
31401 return 0;
31403 zFilenameUtf8 = unicodeToUtf8(zTmpWide);
31404 free(zTmpWide);
31405 return zFilenameUtf8;
31409 ** Convert UTF-8 to multibyte character string. Space to hold the
31410 ** returned string is obtained from malloc().
31412 static char *utf8ToMbcs(const char *zFilename){
31413 char *zFilenameMbcs;
31414 WCHAR *zTmpWide;
31416 zTmpWide = utf8ToUnicode(zFilename);
31417 if( zTmpWide==0 ){
31418 return 0;
31420 zFilenameMbcs = unicodeToMbcs(zTmpWide);
31421 free(zTmpWide);
31422 return zFilenameMbcs;
31425 #if SQLITE_OS_WINCE
31426 /*************************************************************************
31427 ** This section contains code for WinCE only.
31430 ** WindowsCE does not have a localtime() function. So create a
31431 ** substitute.
31433 struct tm *__cdecl localtime(const time_t *t)
31435 static struct tm y;
31436 FILETIME uTm, lTm;
31437 SYSTEMTIME pTm;
31438 sqlite3_int64 t64;
31439 t64 = *t;
31440 t64 = (t64 + 11644473600)*10000000;
31441 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
31442 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
31443 FileTimeToLocalFileTime(&uTm,&lTm);
31444 FileTimeToSystemTime(&lTm,&pTm);
31445 y.tm_year = pTm.wYear - 1900;
31446 y.tm_mon = pTm.wMonth - 1;
31447 y.tm_wday = pTm.wDayOfWeek;
31448 y.tm_mday = pTm.wDay;
31449 y.tm_hour = pTm.wHour;
31450 y.tm_min = pTm.wMinute;
31451 y.tm_sec = pTm.wSecond;
31452 return &y;
31455 /* This will never be called, but defined to make the code compile */
31456 #define GetTempPathA(a,b)
31458 #define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
31459 #define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
31460 #define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
31462 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
31465 ** Acquire a lock on the handle h
31467 static void winceMutexAcquire(HANDLE h){
31468 DWORD dwErr;
31469 do {
31470 dwErr = WaitForSingleObject(h, INFINITE);
31471 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
31474 ** Release a lock acquired by winceMutexAcquire()
31476 #define winceMutexRelease(h) ReleaseMutex(h)
31479 ** Create the mutex and shared memory used for locking in the file
31480 ** descriptor pFile
31482 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
31483 WCHAR *zTok;
31484 WCHAR *zName = utf8ToUnicode(zFilename);
31485 BOOL bInit = TRUE;
31487 /* Initialize the local lockdata */
31488 ZeroMemory(&pFile->local, sizeof(pFile->local));
31490 /* Replace the backslashes from the filename and lowercase it
31491 ** to derive a mutex name. */
31492 zTok = CharLowerW(zName);
31493 for (;*zTok;zTok++){
31494 if (*zTok == '\\') *zTok = '_';
31497 /* Create/open the named mutex */
31498 pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
31499 if (!pFile->hMutex){
31500 pFile->lastErrno = GetLastError();
31501 free(zName);
31502 return FALSE;
31505 /* Acquire the mutex before continuing */
31506 winceMutexAcquire(pFile->hMutex);
31508 /* Since the names of named mutexes, semaphores, file mappings etc are
31509 ** case-sensitive, take advantage of that by uppercasing the mutex name
31510 ** and using that as the shared filemapping name.
31512 CharUpperW(zName);
31513 pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
31514 PAGE_READWRITE, 0, sizeof(winceLock),
31515 zName);
31517 /* Set a flag that indicates we're the first to create the memory so it
31518 ** must be zero-initialized */
31519 if (GetLastError() == ERROR_ALREADY_EXISTS){
31520 bInit = FALSE;
31523 free(zName);
31525 /* If we succeeded in making the shared memory handle, map it. */
31526 if (pFile->hShared){
31527 pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
31528 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
31529 /* If mapping failed, close the shared memory handle and erase it */
31530 if (!pFile->shared){
31531 pFile->lastErrno = GetLastError();
31532 CloseHandle(pFile->hShared);
31533 pFile->hShared = NULL;
31537 /* If shared memory could not be created, then close the mutex and fail */
31538 if (pFile->hShared == NULL){
31539 winceMutexRelease(pFile->hMutex);
31540 CloseHandle(pFile->hMutex);
31541 pFile->hMutex = NULL;
31542 return FALSE;
31545 /* Initialize the shared memory if we're supposed to */
31546 if (bInit) {
31547 ZeroMemory(pFile->shared, sizeof(winceLock));
31550 winceMutexRelease(pFile->hMutex);
31551 return TRUE;
31555 ** Destroy the part of winFile that deals with wince locks
31557 static void winceDestroyLock(winFile *pFile){
31558 if (pFile->hMutex){
31559 /* Acquire the mutex */
31560 winceMutexAcquire(pFile->hMutex);
31562 /* The following blocks should probably assert in debug mode, but they
31563 are to cleanup in case any locks remained open */
31564 if (pFile->local.nReaders){
31565 pFile->shared->nReaders --;
31567 if (pFile->local.bReserved){
31568 pFile->shared->bReserved = FALSE;
31570 if (pFile->local.bPending){
31571 pFile->shared->bPending = FALSE;
31573 if (pFile->local.bExclusive){
31574 pFile->shared->bExclusive = FALSE;
31577 /* De-reference and close our copy of the shared memory handle */
31578 UnmapViewOfFile(pFile->shared);
31579 CloseHandle(pFile->hShared);
31581 /* Done with the mutex */
31582 winceMutexRelease(pFile->hMutex);
31583 CloseHandle(pFile->hMutex);
31584 pFile->hMutex = NULL;
31589 ** An implementation of the LockFile() API of windows for wince
31591 static BOOL winceLockFile(
31592 HANDLE *phFile,
31593 DWORD dwFileOffsetLow,
31594 DWORD dwFileOffsetHigh,
31595 DWORD nNumberOfBytesToLockLow,
31596 DWORD nNumberOfBytesToLockHigh
31598 winFile *pFile = HANDLE_TO_WINFILE(phFile);
31599 BOOL bReturn = FALSE;
31601 UNUSED_PARAMETER(dwFileOffsetHigh);
31602 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31604 if (!pFile->hMutex) return TRUE;
31605 winceMutexAcquire(pFile->hMutex);
31607 /* Wanting an exclusive lock? */
31608 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
31609 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31610 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
31611 pFile->shared->bExclusive = TRUE;
31612 pFile->local.bExclusive = TRUE;
31613 bReturn = TRUE;
31617 /* Want a read-only lock? */
31618 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
31619 nNumberOfBytesToLockLow == 1){
31620 if (pFile->shared->bExclusive == 0){
31621 pFile->local.nReaders ++;
31622 if (pFile->local.nReaders == 1){
31623 pFile->shared->nReaders ++;
31625 bReturn = TRUE;
31629 /* Want a pending lock? */
31630 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
31631 /* If no pending lock has been acquired, then acquire it */
31632 if (pFile->shared->bPending == 0) {
31633 pFile->shared->bPending = TRUE;
31634 pFile->local.bPending = TRUE;
31635 bReturn = TRUE;
31639 /* Want a reserved lock? */
31640 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
31641 if (pFile->shared->bReserved == 0) {
31642 pFile->shared->bReserved = TRUE;
31643 pFile->local.bReserved = TRUE;
31644 bReturn = TRUE;
31648 winceMutexRelease(pFile->hMutex);
31649 return bReturn;
31653 ** An implementation of the UnlockFile API of windows for wince
31655 static BOOL winceUnlockFile(
31656 HANDLE *phFile,
31657 DWORD dwFileOffsetLow,
31658 DWORD dwFileOffsetHigh,
31659 DWORD nNumberOfBytesToUnlockLow,
31660 DWORD nNumberOfBytesToUnlockHigh
31662 winFile *pFile = HANDLE_TO_WINFILE(phFile);
31663 BOOL bReturn = FALSE;
31665 UNUSED_PARAMETER(dwFileOffsetHigh);
31666 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
31668 if (!pFile->hMutex) return TRUE;
31669 winceMutexAcquire(pFile->hMutex);
31671 /* Releasing a reader lock or an exclusive lock */
31672 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
31673 /* Did we have an exclusive lock? */
31674 if (pFile->local.bExclusive){
31675 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
31676 pFile->local.bExclusive = FALSE;
31677 pFile->shared->bExclusive = FALSE;
31678 bReturn = TRUE;
31681 /* Did we just have a reader lock? */
31682 else if (pFile->local.nReaders){
31683 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
31684 pFile->local.nReaders --;
31685 if (pFile->local.nReaders == 0)
31687 pFile->shared->nReaders --;
31689 bReturn = TRUE;
31693 /* Releasing a pending lock */
31694 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
31695 if (pFile->local.bPending){
31696 pFile->local.bPending = FALSE;
31697 pFile->shared->bPending = FALSE;
31698 bReturn = TRUE;
31701 /* Releasing a reserved lock */
31702 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
31703 if (pFile->local.bReserved) {
31704 pFile->local.bReserved = FALSE;
31705 pFile->shared->bReserved = FALSE;
31706 bReturn = TRUE;
31710 winceMutexRelease(pFile->hMutex);
31711 return bReturn;
31715 ** An implementation of the LockFileEx() API of windows for wince
31717 static BOOL winceLockFileEx(
31718 HANDLE *phFile,
31719 DWORD dwFlags,
31720 DWORD dwReserved,
31721 DWORD nNumberOfBytesToLockLow,
31722 DWORD nNumberOfBytesToLockHigh,
31723 LPOVERLAPPED lpOverlapped
31725 UNUSED_PARAMETER(dwReserved);
31726 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31728 /* If the caller wants a shared read lock, forward this call
31729 ** to winceLockFile */
31730 if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
31731 dwFlags == 1 &&
31732 nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31733 return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
31735 return FALSE;
31738 ** End of the special code for wince
31739 *****************************************************************************/
31740 #endif /* SQLITE_OS_WINCE */
31742 /*****************************************************************************
31743 ** The next group of routines implement the I/O methods specified
31744 ** by the sqlite3_io_methods object.
31745 ******************************************************************************/
31748 ** Some microsoft compilers lack this definition.
31750 #ifndef INVALID_SET_FILE_POINTER
31751 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
31752 #endif
31755 ** Move the current position of the file handle passed as the first
31756 ** argument to offset iOffset within the file. If successful, return 0.
31757 ** Otherwise, set pFile->lastErrno and return non-zero.
31759 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
31760 LONG upperBits; /* Most sig. 32 bits of new offset */
31761 LONG lowerBits; /* Least sig. 32 bits of new offset */
31762 DWORD dwRet; /* Value returned by SetFilePointer() */
31764 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
31765 lowerBits = (LONG)(iOffset & 0xffffffff);
31767 /* API oddity: If successful, SetFilePointer() returns a dword
31768 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
31769 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
31770 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
31771 ** whether an error has actually occured, it is also necessary to call
31772 ** GetLastError().
31774 dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
31775 if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
31776 pFile->lastErrno = GetLastError();
31777 return 1;
31780 return 0;
31784 ** Close a file.
31786 ** It is reported that an attempt to close a handle might sometimes
31787 ** fail. This is a very unreasonable result, but windows is notorious
31788 ** for being unreasonable so I do not doubt that it might happen. If
31789 ** the close fails, we pause for 100 milliseconds and try again. As
31790 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
31791 ** giving up and returning an error.
31793 #define MX_CLOSE_ATTEMPT 3
31794 static int winClose(sqlite3_file *id){
31795 int rc, cnt = 0;
31796 winFile *pFile = (winFile*)id;
31798 assert( id!=0 );
31799 assert( pFile->pShm==0 );
31800 OSTRACE(("CLOSE %d\n", pFile->h));
31802 rc = CloseHandle(pFile->h);
31803 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
31804 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
31805 #if SQLITE_OS_WINCE
31806 #define WINCE_DELETION_ATTEMPTS 3
31807 winceDestroyLock(pFile);
31808 if( pFile->zDeleteOnClose ){
31809 int cnt = 0;
31810 while(
31811 DeleteFileW(pFile->zDeleteOnClose)==0
31812 && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
31813 && cnt++ < WINCE_DELETION_ATTEMPTS
31815 Sleep(100); /* Wait a little before trying again */
31817 free(pFile->zDeleteOnClose);
31819 #endif
31820 OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
31821 OpenCounter(-1);
31822 return rc ? SQLITE_OK : SQLITE_IOERR;
31826 ** Read data from a file into a buffer. Return SQLITE_OK if all
31827 ** bytes were read successfully and SQLITE_IOERR if anything goes
31828 ** wrong.
31830 static int winRead(
31831 sqlite3_file *id, /* File to read from */
31832 void *pBuf, /* Write content into this buffer */
31833 int amt, /* Number of bytes to read */
31834 sqlite3_int64 offset /* Begin reading at this offset */
31836 winFile *pFile = (winFile*)id; /* file handle */
31837 DWORD nRead; /* Number of bytes actually read from file */
31839 assert( id!=0 );
31840 SimulateIOError(return SQLITE_IOERR_READ);
31841 OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
31843 if( seekWinFile(pFile, offset) ){
31844 return SQLITE_FULL;
31846 if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
31847 pFile->lastErrno = GetLastError();
31848 return SQLITE_IOERR_READ;
31850 if( nRead<(DWORD)amt ){
31851 /* Unread parts of the buffer must be zero-filled */
31852 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
31853 return SQLITE_IOERR_SHORT_READ;
31856 return SQLITE_OK;
31860 ** Write data from a buffer into a file. Return SQLITE_OK on success
31861 ** or some other error code on failure.
31863 static int winWrite(
31864 sqlite3_file *id, /* File to write into */
31865 const void *pBuf, /* The bytes to be written */
31866 int amt, /* Number of bytes to write */
31867 sqlite3_int64 offset /* Offset into the file to begin writing at */
31869 int rc; /* True if error has occured, else false */
31870 winFile *pFile = (winFile*)id; /* File handle */
31872 assert( amt>0 );
31873 assert( pFile );
31874 SimulateIOError(return SQLITE_IOERR_WRITE);
31875 SimulateDiskfullError(return SQLITE_FULL);
31877 OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
31879 rc = seekWinFile(pFile, offset);
31880 if( rc==0 ){
31881 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
31882 int nRem = amt; /* Number of bytes yet to be written */
31883 DWORD nWrite; /* Bytes written by each WriteFile() call */
31885 while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
31886 aRem += nWrite;
31887 nRem -= nWrite;
31889 if( nRem>0 ){
31890 pFile->lastErrno = GetLastError();
31891 rc = 1;
31895 if( rc ){
31896 if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
31897 return SQLITE_FULL;
31899 return SQLITE_IOERR_WRITE;
31901 return SQLITE_OK;
31905 ** Truncate an open file to a specified size
31907 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
31908 winFile *pFile = (winFile*)id; /* File handle object */
31909 int rc = SQLITE_OK; /* Return code for this function */
31911 assert( pFile );
31913 OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
31914 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
31916 /* If the user has configured a chunk-size for this file, truncate the
31917 ** file so that it consists of an integer number of chunks (i.e. the
31918 ** actual file size after the operation may be larger than the requested
31919 ** size).
31921 if( pFile->szChunk ){
31922 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
31925 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
31926 if( seekWinFile(pFile, nByte) ){
31927 rc = SQLITE_IOERR_TRUNCATE;
31928 }else if( 0==SetEndOfFile(pFile->h) ){
31929 pFile->lastErrno = GetLastError();
31930 rc = SQLITE_IOERR_TRUNCATE;
31933 OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
31934 return rc;
31937 #ifdef SQLITE_TEST
31939 ** Count the number of fullsyncs and normal syncs. This is used to test
31940 ** that syncs and fullsyncs are occuring at the right times.
31942 SQLITE_API int sqlite3_sync_count = 0;
31943 SQLITE_API int sqlite3_fullsync_count = 0;
31944 #endif
31947 ** Make sure all writes to a particular file are committed to disk.
31949 static int winSync(sqlite3_file *id, int flags){
31950 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
31951 winFile *pFile = (winFile*)id;
31952 #else
31953 UNUSED_PARAMETER(id);
31954 #endif
31956 assert( pFile );
31957 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
31958 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
31959 || (flags&0x0F)==SQLITE_SYNC_FULL
31962 OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
31964 #ifndef SQLITE_TEST
31965 UNUSED_PARAMETER(flags);
31966 #else
31967 if( flags & SQLITE_SYNC_FULL ){
31968 sqlite3_fullsync_count++;
31970 sqlite3_sync_count++;
31971 #endif
31973 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
31974 ** line is to test that doing so does not cause any problems.
31976 SimulateDiskfullError( return SQLITE_FULL );
31977 SimulateIOError( return SQLITE_IOERR; );
31979 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
31980 ** no-op
31982 #ifdef SQLITE_NO_SYNC
31983 return SQLITE_OK;
31984 #else
31985 if( FlushFileBuffers(pFile->h) ){
31986 return SQLITE_OK;
31987 }else{
31988 pFile->lastErrno = GetLastError();
31989 return SQLITE_IOERR;
31991 #endif
31995 ** Determine the current size of a file in bytes
31997 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
31998 DWORD upperBits;
31999 DWORD lowerBits;
32000 winFile *pFile = (winFile*)id;
32001 DWORD error;
32003 assert( id!=0 );
32004 SimulateIOError(return SQLITE_IOERR_FSTAT);
32005 lowerBits = GetFileSize(pFile->h, &upperBits);
32006 if( (lowerBits == INVALID_FILE_SIZE)
32007 && ((error = GetLastError()) != NO_ERROR) )
32009 pFile->lastErrno = error;
32010 return SQLITE_IOERR_FSTAT;
32012 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
32013 return SQLITE_OK;
32017 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
32019 #ifndef LOCKFILE_FAIL_IMMEDIATELY
32020 # define LOCKFILE_FAIL_IMMEDIATELY 1
32021 #endif
32024 ** Acquire a reader lock.
32025 ** Different API routines are called depending on whether or not this
32026 ** is Win95 or WinNT.
32028 static int getReadLock(winFile *pFile){
32029 int res;
32030 if( isNT() ){
32031 OVERLAPPED ovlp;
32032 ovlp.Offset = SHARED_FIRST;
32033 ovlp.OffsetHigh = 0;
32034 ovlp.hEvent = 0;
32035 res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
32036 0, SHARED_SIZE, 0, &ovlp);
32037 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32039 #if SQLITE_OS_WINCE==0
32040 }else{
32041 int lk;
32042 sqlite3_randomness(sizeof(lk), &lk);
32043 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
32044 res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32045 #endif
32047 if( res == 0 ){
32048 pFile->lastErrno = GetLastError();
32050 return res;
32054 ** Undo a readlock
32056 static int unlockReadLock(winFile *pFile){
32057 int res;
32058 if( isNT() ){
32059 res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32060 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32062 #if SQLITE_OS_WINCE==0
32063 }else{
32064 res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
32065 #endif
32067 if( res == 0 ){
32068 pFile->lastErrno = GetLastError();
32070 return res;
32074 ** Lock the file with the lock specified by parameter locktype - one
32075 ** of the following:
32077 ** (1) SHARED_LOCK
32078 ** (2) RESERVED_LOCK
32079 ** (3) PENDING_LOCK
32080 ** (4) EXCLUSIVE_LOCK
32082 ** Sometimes when requesting one lock state, additional lock states
32083 ** are inserted in between. The locking might fail on one of the later
32084 ** transitions leaving the lock state different from what it started but
32085 ** still short of its goal. The following chart shows the allowed
32086 ** transitions and the inserted intermediate states:
32088 ** UNLOCKED -> SHARED
32089 ** SHARED -> RESERVED
32090 ** SHARED -> (PENDING) -> EXCLUSIVE
32091 ** RESERVED -> (PENDING) -> EXCLUSIVE
32092 ** PENDING -> EXCLUSIVE
32094 ** This routine will only increase a lock. The winUnlock() routine
32095 ** erases all locks at once and returns us immediately to locking level 0.
32096 ** It is not possible to lower the locking level one step at a time. You
32097 ** must go straight to locking level 0.
32099 static int winLock(sqlite3_file *id, int locktype){
32100 int rc = SQLITE_OK; /* Return code from subroutines */
32101 int res = 1; /* Result of a windows lock call */
32102 int newLocktype; /* Set pFile->locktype to this value before exiting */
32103 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
32104 winFile *pFile = (winFile*)id;
32105 DWORD error = NO_ERROR;
32107 assert( id!=0 );
32108 OSTRACE(("LOCK %d %d was %d(%d)\n",
32109 pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
32111 /* If there is already a lock of this type or more restrictive on the
32112 ** OsFile, do nothing. Don't use the end_lock: exit path, as
32113 ** sqlite3OsEnterMutex() hasn't been called yet.
32115 if( pFile->locktype>=locktype ){
32116 return SQLITE_OK;
32119 /* Make sure the locking sequence is correct
32121 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
32122 assert( locktype!=PENDING_LOCK );
32123 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
32125 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
32126 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
32127 ** the PENDING_LOCK byte is temporary.
32129 newLocktype = pFile->locktype;
32130 if( (pFile->locktype==NO_LOCK)
32131 || ( (locktype==EXCLUSIVE_LOCK)
32132 && (pFile->locktype==RESERVED_LOCK))
32134 int cnt = 3;
32135 while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
32136 /* Try 3 times to get the pending lock. The pending lock might be
32137 ** held by another reader process who will release it momentarily.
32139 OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
32140 Sleep(1);
32142 gotPendingLock = res;
32143 if( !res ){
32144 error = GetLastError();
32148 /* Acquire a shared lock
32150 if( locktype==SHARED_LOCK && res ){
32151 assert( pFile->locktype==NO_LOCK );
32152 res = getReadLock(pFile);
32153 if( res ){
32154 newLocktype = SHARED_LOCK;
32155 }else{
32156 error = GetLastError();
32160 /* Acquire a RESERVED lock
32162 if( locktype==RESERVED_LOCK && res ){
32163 assert( pFile->locktype==SHARED_LOCK );
32164 res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32165 if( res ){
32166 newLocktype = RESERVED_LOCK;
32167 }else{
32168 error = GetLastError();
32172 /* Acquire a PENDING lock
32174 if( locktype==EXCLUSIVE_LOCK && res ){
32175 newLocktype = PENDING_LOCK;
32176 gotPendingLock = 0;
32179 /* Acquire an EXCLUSIVE lock
32181 if( locktype==EXCLUSIVE_LOCK && res ){
32182 assert( pFile->locktype>=SHARED_LOCK );
32183 res = unlockReadLock(pFile);
32184 OSTRACE(("unreadlock = %d\n", res));
32185 res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32186 if( res ){
32187 newLocktype = EXCLUSIVE_LOCK;
32188 }else{
32189 error = GetLastError();
32190 OSTRACE(("error-code = %d\n", error));
32191 getReadLock(pFile);
32195 /* If we are holding a PENDING lock that ought to be released, then
32196 ** release it now.
32198 if( gotPendingLock && locktype==SHARED_LOCK ){
32199 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32202 /* Update the state of the lock has held in the file descriptor then
32203 ** return the appropriate result code.
32205 if( res ){
32206 rc = SQLITE_OK;
32207 }else{
32208 OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
32209 locktype, newLocktype));
32210 pFile->lastErrno = error;
32211 rc = SQLITE_BUSY;
32213 pFile->locktype = (u8)newLocktype;
32214 return rc;
32218 ** This routine checks if there is a RESERVED lock held on the specified
32219 ** file by this or any other process. If such a lock is held, return
32220 ** non-zero, otherwise zero.
32222 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
32223 int rc;
32224 winFile *pFile = (winFile*)id;
32226 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32228 assert( id!=0 );
32229 if( pFile->locktype>=RESERVED_LOCK ){
32230 rc = 1;
32231 OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
32232 }else{
32233 rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32234 if( rc ){
32235 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32237 rc = !rc;
32238 OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
32240 *pResOut = rc;
32241 return SQLITE_OK;
32245 ** Lower the locking level on file descriptor id to locktype. locktype
32246 ** must be either NO_LOCK or SHARED_LOCK.
32248 ** If the locking level of the file descriptor is already at or below
32249 ** the requested locking level, this routine is a no-op.
32251 ** It is not possible for this routine to fail if the second argument
32252 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
32253 ** might return SQLITE_IOERR;
32255 static int winUnlock(sqlite3_file *id, int locktype){
32256 int type;
32257 winFile *pFile = (winFile*)id;
32258 int rc = SQLITE_OK;
32259 assert( pFile!=0 );
32260 assert( locktype<=SHARED_LOCK );
32261 OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
32262 pFile->locktype, pFile->sharedLockByte));
32263 type = pFile->locktype;
32264 if( type>=EXCLUSIVE_LOCK ){
32265 UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32266 if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
32267 /* This should never happen. We should always be able to
32268 ** reacquire the read lock */
32269 rc = SQLITE_IOERR_UNLOCK;
32272 if( type>=RESERVED_LOCK ){
32273 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32275 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
32276 unlockReadLock(pFile);
32278 if( type>=PENDING_LOCK ){
32279 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32281 pFile->locktype = (u8)locktype;
32282 return rc;
32286 ** Control and query of the open file handle.
32288 static int winFileControl(sqlite3_file *id, int op, void *pArg){
32289 switch( op ){
32290 case SQLITE_FCNTL_LOCKSTATE: {
32291 *(int*)pArg = ((winFile*)id)->locktype;
32292 return SQLITE_OK;
32294 case SQLITE_LAST_ERRNO: {
32295 *(int*)pArg = (int)((winFile*)id)->lastErrno;
32296 return SQLITE_OK;
32298 case SQLITE_FCNTL_CHUNK_SIZE: {
32299 ((winFile*)id)->szChunk = *(int *)pArg;
32300 return SQLITE_OK;
32302 case SQLITE_FCNTL_SIZE_HINT: {
32303 sqlite3_int64 sz = *(sqlite3_int64*)pArg;
32304 SimulateIOErrorBenign(1);
32305 winTruncate(id, sz);
32306 SimulateIOErrorBenign(0);
32307 return SQLITE_OK;
32309 case SQLITE_FCNTL_SYNC_OMITTED: {
32310 return SQLITE_OK;
32313 return SQLITE_NOTFOUND;
32317 ** Return the sector size in bytes of the underlying block device for
32318 ** the specified file. This is almost always 512 bytes, but may be
32319 ** larger for some devices.
32321 ** SQLite code assumes this function cannot fail. It also assumes that
32322 ** if two files are created in the same file-system directory (i.e.
32323 ** a database and its journal file) that the sector size will be the
32324 ** same for both.
32326 static int winSectorSize(sqlite3_file *id){
32327 assert( id!=0 );
32328 return (int)(((winFile*)id)->sectorSize);
32332 ** Return a vector of device characteristics.
32334 static int winDeviceCharacteristics(sqlite3_file *id){
32335 UNUSED_PARAMETER(id);
32336 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
32339 #ifndef SQLITE_OMIT_WAL
32342 ** Windows will only let you create file view mappings
32343 ** on allocation size granularity boundaries.
32344 ** During sqlite3_os_init() we do a GetSystemInfo()
32345 ** to get the granularity size.
32347 SYSTEM_INFO winSysInfo;
32350 ** Helper functions to obtain and relinquish the global mutex. The
32351 ** global mutex is used to protect the winLockInfo objects used by
32352 ** this file, all of which may be shared by multiple threads.
32354 ** Function winShmMutexHeld() is used to assert() that the global mutex
32355 ** is held when required. This function is only used as part of assert()
32356 ** statements. e.g.
32358 ** winShmEnterMutex()
32359 ** assert( winShmMutexHeld() );
32360 ** winShmLeaveMutex()
32362 static void winShmEnterMutex(void){
32363 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32365 static void winShmLeaveMutex(void){
32366 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32368 #ifdef SQLITE_DEBUG
32369 static int winShmMutexHeld(void) {
32370 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32372 #endif
32375 ** Object used to represent a single file opened and mmapped to provide
32376 ** shared memory. When multiple threads all reference the same
32377 ** log-summary, each thread has its own winFile object, but they all
32378 ** point to a single instance of this object. In other words, each
32379 ** log-summary is opened only once per process.
32381 ** winShmMutexHeld() must be true when creating or destroying
32382 ** this object or while reading or writing the following fields:
32384 ** nRef
32385 ** pNext
32387 ** The following fields are read-only after the object is created:
32389 ** fid
32390 ** zFilename
32392 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
32393 ** winShmMutexHeld() is true when reading or writing any other field
32394 ** in this structure.
32397 struct winShmNode {
32398 sqlite3_mutex *mutex; /* Mutex to access this object */
32399 char *zFilename; /* Name of the file */
32400 winFile hFile; /* File handle from winOpen */
32402 int szRegion; /* Size of shared-memory regions */
32403 int nRegion; /* Size of array apRegion */
32404 struct ShmRegion {
32405 HANDLE hMap; /* File handle from CreateFileMapping */
32406 void *pMap;
32407 } *aRegion;
32408 DWORD lastErrno; /* The Windows errno from the last I/O error */
32410 int nRef; /* Number of winShm objects pointing to this */
32411 winShm *pFirst; /* All winShm objects pointing to this */
32412 winShmNode *pNext; /* Next in list of all winShmNode objects */
32413 #ifdef SQLITE_DEBUG
32414 u8 nextShmId; /* Next available winShm.id value */
32415 #endif
32419 ** A global array of all winShmNode objects.
32421 ** The winShmMutexHeld() must be true while reading or writing this list.
32423 static winShmNode *winShmNodeList = 0;
32426 ** Structure used internally by this VFS to record the state of an
32427 ** open shared memory connection.
32429 ** The following fields are initialized when this object is created and
32430 ** are read-only thereafter:
32432 ** winShm.pShmNode
32433 ** winShm.id
32435 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
32436 ** while accessing any read/write fields.
32438 struct winShm {
32439 winShmNode *pShmNode; /* The underlying winShmNode object */
32440 winShm *pNext; /* Next winShm with the same winShmNode */
32441 u8 hasMutex; /* True if holding the winShmNode mutex */
32442 u16 sharedMask; /* Mask of shared locks held */
32443 u16 exclMask; /* Mask of exclusive locks held */
32444 #ifdef SQLITE_DEBUG
32445 u8 id; /* Id of this connection with its winShmNode */
32446 #endif
32450 ** Constants used for locking
32452 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
32453 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
32456 ** Apply advisory locks for all n bytes beginning at ofst.
32458 #define _SHM_UNLCK 1
32459 #define _SHM_RDLCK 2
32460 #define _SHM_WRLCK 3
32461 static int winShmSystemLock(
32462 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
32463 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
32464 int ofst, /* Offset to first byte to be locked/unlocked */
32465 int nByte /* Number of bytes to lock or unlock */
32467 OVERLAPPED ovlp;
32468 DWORD dwFlags;
32469 int rc = 0; /* Result code form Lock/UnlockFileEx() */
32471 /* Access to the winShmNode object is serialized by the caller */
32472 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
32474 /* Initialize the locking parameters */
32475 dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
32476 if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
32478 memset(&ovlp, 0, sizeof(OVERLAPPED));
32479 ovlp.Offset = ofst;
32481 /* Release/Acquire the system-level lock */
32482 if( lockType==_SHM_UNLCK ){
32483 rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
32484 }else{
32485 rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
32488 if( rc!= 0 ){
32489 rc = SQLITE_OK;
32490 }else{
32491 pFile->lastErrno = GetLastError();
32492 rc = SQLITE_BUSY;
32495 OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
32496 pFile->hFile.h,
32497 rc==SQLITE_OK ? "ok" : "failed",
32498 lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
32499 pFile->lastErrno));
32501 return rc;
32504 /* Forward references to VFS methods */
32505 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
32506 static int winDelete(sqlite3_vfs *,const char*,int);
32509 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
32511 ** This is not a VFS shared-memory method; it is a utility function called
32512 ** by VFS shared-memory methods.
32514 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
32515 winShmNode **pp;
32516 winShmNode *p;
32517 BOOL bRc;
32518 assert( winShmMutexHeld() );
32519 pp = &winShmNodeList;
32520 while( (p = *pp)!=0 ){
32521 if( p->nRef==0 ){
32522 int i;
32523 if( p->mutex ) sqlite3_mutex_free(p->mutex);
32524 for(i=0; i<p->nRegion; i++){
32525 bRc = UnmapViewOfFile(p->aRegion[i].pMap);
32526 OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
32527 (int)GetCurrentProcessId(), i,
32528 bRc ? "ok" : "failed"));
32529 bRc = CloseHandle(p->aRegion[i].hMap);
32530 OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
32531 (int)GetCurrentProcessId(), i,
32532 bRc ? "ok" : "failed"));
32534 if( p->hFile.h != INVALID_HANDLE_VALUE ){
32535 SimulateIOErrorBenign(1);
32536 winClose((sqlite3_file *)&p->hFile);
32537 SimulateIOErrorBenign(0);
32539 if( deleteFlag ){
32540 SimulateIOErrorBenign(1);
32541 winDelete(pVfs, p->zFilename, 0);
32542 SimulateIOErrorBenign(0);
32544 *pp = p->pNext;
32545 sqlite3_free(p->aRegion);
32546 sqlite3_free(p);
32547 }else{
32548 pp = &p->pNext;
32554 ** Open the shared-memory area associated with database file pDbFd.
32556 ** When opening a new shared-memory file, if no other instances of that
32557 ** file are currently open, in this process or in other processes, then
32558 ** the file must be truncated to zero length or have its header cleared.
32560 static int winOpenSharedMemory(winFile *pDbFd){
32561 struct winShm *p; /* The connection to be opened */
32562 struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
32563 int rc; /* Result code */
32564 struct winShmNode *pNew; /* Newly allocated winShmNode */
32565 int nName; /* Size of zName in bytes */
32567 assert( pDbFd->pShm==0 ); /* Not previously opened */
32569 /* Allocate space for the new sqlite3_shm object. Also speculatively
32570 ** allocate space for a new winShmNode and filename.
32572 p = sqlite3_malloc( sizeof(*p) );
32573 if( p==0 ) return SQLITE_NOMEM;
32574 memset(p, 0, sizeof(*p));
32575 nName = sqlite3Strlen30(pDbFd->zPath);
32576 pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
32577 if( pNew==0 ){
32578 sqlite3_free(p);
32579 return SQLITE_NOMEM;
32581 memset(pNew, 0, sizeof(*pNew));
32582 pNew->zFilename = (char*)&pNew[1];
32583 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
32585 /* Look to see if there is an existing winShmNode that can be used.
32586 ** If no matching winShmNode currently exists, create a new one.
32588 winShmEnterMutex();
32589 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
32590 /* TBD need to come up with better match here. Perhaps
32591 ** use FILE_ID_BOTH_DIR_INFO Structure.
32593 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
32595 if( pShmNode ){
32596 sqlite3_free(pNew);
32597 }else{
32598 pShmNode = pNew;
32599 pNew = 0;
32600 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
32601 pShmNode->pNext = winShmNodeList;
32602 winShmNodeList = pShmNode;
32604 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
32605 if( pShmNode->mutex==0 ){
32606 rc = SQLITE_NOMEM;
32607 goto shm_open_err;
32610 rc = winOpen(pDbFd->pVfs,
32611 pShmNode->zFilename, /* Name of the file (UTF-8) */
32612 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
32613 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
32615 if( SQLITE_OK!=rc ){
32616 rc = SQLITE_CANTOPEN_BKPT;
32617 goto shm_open_err;
32620 /* Check to see if another process is holding the dead-man switch.
32621 ** If not, truncate the file to zero length.
32623 if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
32624 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
32625 if( rc!=SQLITE_OK ){
32626 rc = SQLITE_IOERR_SHMOPEN;
32629 if( rc==SQLITE_OK ){
32630 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32631 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
32633 if( rc ) goto shm_open_err;
32636 /* Make the new connection a child of the winShmNode */
32637 p->pShmNode = pShmNode;
32638 #ifdef SQLITE_DEBUG
32639 p->id = pShmNode->nextShmId++;
32640 #endif
32641 pShmNode->nRef++;
32642 pDbFd->pShm = p;
32643 winShmLeaveMutex();
32645 /* The reference count on pShmNode has already been incremented under
32646 ** the cover of the winShmEnterMutex() mutex and the pointer from the
32647 ** new (struct winShm) object to the pShmNode has been set. All that is
32648 ** left to do is to link the new object into the linked list starting
32649 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
32650 ** mutex.
32652 sqlite3_mutex_enter(pShmNode->mutex);
32653 p->pNext = pShmNode->pFirst;
32654 pShmNode->pFirst = p;
32655 sqlite3_mutex_leave(pShmNode->mutex);
32656 return SQLITE_OK;
32658 /* Jump here on any error */
32659 shm_open_err:
32660 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32661 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
32662 sqlite3_free(p);
32663 sqlite3_free(pNew);
32664 winShmLeaveMutex();
32665 return rc;
32669 ** Close a connection to shared-memory. Delete the underlying
32670 ** storage if deleteFlag is true.
32672 static int winShmUnmap(
32673 sqlite3_file *fd, /* Database holding shared memory */
32674 int deleteFlag /* Delete after closing if true */
32676 winFile *pDbFd; /* Database holding shared-memory */
32677 winShm *p; /* The connection to be closed */
32678 winShmNode *pShmNode; /* The underlying shared-memory file */
32679 winShm **pp; /* For looping over sibling connections */
32681 pDbFd = (winFile*)fd;
32682 p = pDbFd->pShm;
32683 if( p==0 ) return SQLITE_OK;
32684 pShmNode = p->pShmNode;
32686 /* Remove connection p from the set of connections associated
32687 ** with pShmNode */
32688 sqlite3_mutex_enter(pShmNode->mutex);
32689 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
32690 *pp = p->pNext;
32692 /* Free the connection p */
32693 sqlite3_free(p);
32694 pDbFd->pShm = 0;
32695 sqlite3_mutex_leave(pShmNode->mutex);
32697 /* If pShmNode->nRef has reached 0, then close the underlying
32698 ** shared-memory file, too */
32699 winShmEnterMutex();
32700 assert( pShmNode->nRef>0 );
32701 pShmNode->nRef--;
32702 if( pShmNode->nRef==0 ){
32703 winShmPurge(pDbFd->pVfs, deleteFlag);
32705 winShmLeaveMutex();
32707 return SQLITE_OK;
32711 ** Change the lock state for a shared-memory segment.
32713 static int winShmLock(
32714 sqlite3_file *fd, /* Database file holding the shared memory */
32715 int ofst, /* First lock to acquire or release */
32716 int n, /* Number of locks to acquire or release */
32717 int flags /* What to do with the lock */
32719 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
32720 winShm *p = pDbFd->pShm; /* The shared memory being locked */
32721 winShm *pX; /* For looping over all siblings */
32722 winShmNode *pShmNode = p->pShmNode;
32723 int rc = SQLITE_OK; /* Result code */
32724 u16 mask; /* Mask of locks to take or release */
32726 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
32727 assert( n>=1 );
32728 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
32729 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
32730 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
32731 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
32732 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
32734 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
32735 assert( n>1 || mask==(1<<ofst) );
32736 sqlite3_mutex_enter(pShmNode->mutex);
32737 if( flags & SQLITE_SHM_UNLOCK ){
32738 u16 allMask = 0; /* Mask of locks held by siblings */
32740 /* See if any siblings hold this same lock */
32741 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32742 if( pX==p ) continue;
32743 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
32744 allMask |= pX->sharedMask;
32747 /* Unlock the system-level locks */
32748 if( (mask & allMask)==0 ){
32749 rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
32750 }else{
32751 rc = SQLITE_OK;
32754 /* Undo the local locks */
32755 if( rc==SQLITE_OK ){
32756 p->exclMask &= ~mask;
32757 p->sharedMask &= ~mask;
32759 }else if( flags & SQLITE_SHM_SHARED ){
32760 u16 allShared = 0; /* Union of locks held by connections other than "p" */
32762 /* Find out which shared locks are already held by sibling connections.
32763 ** If any sibling already holds an exclusive lock, go ahead and return
32764 ** SQLITE_BUSY.
32766 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32767 if( (pX->exclMask & mask)!=0 ){
32768 rc = SQLITE_BUSY;
32769 break;
32771 allShared |= pX->sharedMask;
32774 /* Get shared locks at the system level, if necessary */
32775 if( rc==SQLITE_OK ){
32776 if( (allShared & mask)==0 ){
32777 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
32778 }else{
32779 rc = SQLITE_OK;
32783 /* Get the local shared locks */
32784 if( rc==SQLITE_OK ){
32785 p->sharedMask |= mask;
32787 }else{
32788 /* Make sure no sibling connections hold locks that will block this
32789 ** lock. If any do, return SQLITE_BUSY right away.
32791 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32792 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
32793 rc = SQLITE_BUSY;
32794 break;
32798 /* Get the exclusive locks at the system level. Then if successful
32799 ** also mark the local connection as being locked.
32801 if( rc==SQLITE_OK ){
32802 rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
32803 if( rc==SQLITE_OK ){
32804 assert( (p->sharedMask & mask)==0 );
32805 p->exclMask |= mask;
32809 sqlite3_mutex_leave(pShmNode->mutex);
32810 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
32811 p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
32812 rc ? "failed" : "ok"));
32813 return rc;
32817 ** Implement a memory barrier or memory fence on shared memory.
32819 ** All loads and stores begun before the barrier must complete before
32820 ** any load or store begun after the barrier.
32822 static void winShmBarrier(
32823 sqlite3_file *fd /* Database holding the shared memory */
32825 UNUSED_PARAMETER(fd);
32826 /* MemoryBarrier(); // does not work -- do not know why not */
32827 winShmEnterMutex();
32828 winShmLeaveMutex();
32832 ** This function is called to obtain a pointer to region iRegion of the
32833 ** shared-memory associated with the database file fd. Shared-memory regions
32834 ** are numbered starting from zero. Each shared-memory region is szRegion
32835 ** bytes in size.
32837 ** If an error occurs, an error code is returned and *pp is set to NULL.
32839 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
32840 ** region has not been allocated (by any client, including one running in a
32841 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
32842 ** isWrite is non-zero and the requested shared-memory region has not yet
32843 ** been allocated, it is allocated by this function.
32845 ** If the shared-memory region has already been allocated or is allocated by
32846 ** this call as described above, then it is mapped into this processes
32847 ** address space (if it is not already), *pp is set to point to the mapped
32848 ** memory and SQLITE_OK returned.
32850 static int winShmMap(
32851 sqlite3_file *fd, /* Handle open on database file */
32852 int iRegion, /* Region to retrieve */
32853 int szRegion, /* Size of regions */
32854 int isWrite, /* True to extend file if necessary */
32855 void volatile **pp /* OUT: Mapped memory */
32857 winFile *pDbFd = (winFile*)fd;
32858 winShm *p = pDbFd->pShm;
32859 winShmNode *pShmNode;
32860 int rc = SQLITE_OK;
32862 if( !p ){
32863 rc = winOpenSharedMemory(pDbFd);
32864 if( rc!=SQLITE_OK ) return rc;
32865 p = pDbFd->pShm;
32867 pShmNode = p->pShmNode;
32869 sqlite3_mutex_enter(pShmNode->mutex);
32870 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
32872 if( pShmNode->nRegion<=iRegion ){
32873 struct ShmRegion *apNew; /* New aRegion[] array */
32874 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
32875 sqlite3_int64 sz; /* Current size of wal-index file */
32877 pShmNode->szRegion = szRegion;
32879 /* The requested region is not mapped into this processes address space.
32880 ** Check to see if it has been allocated (i.e. if the wal-index file is
32881 ** large enough to contain the requested region).
32883 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
32884 if( rc!=SQLITE_OK ){
32885 rc = SQLITE_IOERR_SHMSIZE;
32886 goto shmpage_out;
32889 if( sz<nByte ){
32890 /* The requested memory region does not exist. If isWrite is set to
32891 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
32893 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
32894 ** the requested memory region.
32896 if( !isWrite ) goto shmpage_out;
32897 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
32898 if( rc!=SQLITE_OK ){
32899 rc = SQLITE_IOERR_SHMSIZE;
32900 goto shmpage_out;
32904 /* Map the requested memory region into this processes address space. */
32905 apNew = (struct ShmRegion *)sqlite3_realloc(
32906 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
32908 if( !apNew ){
32909 rc = SQLITE_IOERR_NOMEM;
32910 goto shmpage_out;
32912 pShmNode->aRegion = apNew;
32914 while( pShmNode->nRegion<=iRegion ){
32915 HANDLE hMap; /* file-mapping handle */
32916 void *pMap = 0; /* Mapped memory region */
32918 hMap = CreateFileMapping(pShmNode->hFile.h,
32919 NULL, PAGE_READWRITE, 0, nByte, NULL
32921 OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
32922 (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
32923 hMap ? "ok" : "failed"));
32924 if( hMap ){
32925 int iOffset = pShmNode->nRegion*szRegion;
32926 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
32927 pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
32928 0, iOffset - iOffsetShift, szRegion + iOffsetShift
32930 OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
32931 (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
32932 pMap ? "ok" : "failed"));
32934 if( !pMap ){
32935 pShmNode->lastErrno = GetLastError();
32936 rc = SQLITE_IOERR;
32937 if( hMap ) CloseHandle(hMap);
32938 goto shmpage_out;
32941 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
32942 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
32943 pShmNode->nRegion++;
32947 shmpage_out:
32948 if( pShmNode->nRegion>iRegion ){
32949 int iOffset = iRegion*szRegion;
32950 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
32951 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
32952 *pp = (void *)&p[iOffsetShift];
32953 }else{
32954 *pp = 0;
32956 sqlite3_mutex_leave(pShmNode->mutex);
32957 return rc;
32960 #else
32961 # define winShmMap 0
32962 # define winShmLock 0
32963 # define winShmBarrier 0
32964 # define winShmUnmap 0
32965 #endif /* #ifndef SQLITE_OMIT_WAL */
32968 ** Here ends the implementation of all sqlite3_file methods.
32970 ********************** End sqlite3_file Methods *******************************
32971 ******************************************************************************/
32974 ** This vector defines all the methods that can operate on an
32975 ** sqlite3_file for win32.
32977 static const sqlite3_io_methods winIoMethod = {
32978 2, /* iVersion */
32979 winClose, /* xClose */
32980 winRead, /* xRead */
32981 winWrite, /* xWrite */
32982 winTruncate, /* xTruncate */
32983 winSync, /* xSync */
32984 winFileSize, /* xFileSize */
32985 winLock, /* xLock */
32986 winUnlock, /* xUnlock */
32987 winCheckReservedLock, /* xCheckReservedLock */
32988 winFileControl, /* xFileControl */
32989 winSectorSize, /* xSectorSize */
32990 winDeviceCharacteristics, /* xDeviceCharacteristics */
32991 winShmMap, /* xShmMap */
32992 winShmLock, /* xShmLock */
32993 winShmBarrier, /* xShmBarrier */
32994 winShmUnmap /* xShmUnmap */
32997 /****************************************************************************
32998 **************************** sqlite3_vfs methods ****************************
33000 ** This division contains the implementation of methods on the
33001 ** sqlite3_vfs object.
33005 ** Convert a UTF-8 filename into whatever form the underlying
33006 ** operating system wants filenames in. Space to hold the result
33007 ** is obtained from malloc and must be freed by the calling
33008 ** function.
33010 static void *convertUtf8Filename(const char *zFilename){
33011 void *zConverted = 0;
33012 if( isNT() ){
33013 zConverted = utf8ToUnicode(zFilename);
33014 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33016 #if SQLITE_OS_WINCE==0
33017 }else{
33018 zConverted = utf8ToMbcs(zFilename);
33019 #endif
33021 /* caller will handle out of memory */
33022 return zConverted;
33026 ** Create a temporary file name in zBuf. zBuf must be big enough to
33027 ** hold at pVfs->mxPathname characters.
33029 static int getTempname(int nBuf, char *zBuf){
33030 static char zChars[] =
33031 "abcdefghijklmnopqrstuvwxyz"
33032 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33033 "0123456789";
33034 size_t i, j;
33035 char zTempPath[MAX_PATH+1];
33037 /* It's odd to simulate an io-error here, but really this is just
33038 ** using the io-error infrastructure to test that SQLite handles this
33039 ** function failing.
33041 SimulateIOError( return SQLITE_IOERR );
33043 if( sqlite3_temp_directory ){
33044 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
33045 }else if( isNT() ){
33046 char *zMulti;
33047 WCHAR zWidePath[MAX_PATH];
33048 GetTempPathW(MAX_PATH-30, zWidePath);
33049 zMulti = unicodeToUtf8(zWidePath);
33050 if( zMulti ){
33051 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
33052 free(zMulti);
33053 }else{
33054 return SQLITE_NOMEM;
33056 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33057 ** Since the ASCII version of these Windows API do not exist for WINCE,
33058 ** it's important to not reference them for WINCE builds.
33060 #if SQLITE_OS_WINCE==0
33061 }else{
33062 char *zUtf8;
33063 char zMbcsPath[MAX_PATH];
33064 GetTempPathA(MAX_PATH-30, zMbcsPath);
33065 zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
33066 if( zUtf8 ){
33067 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
33068 free(zUtf8);
33069 }else{
33070 return SQLITE_NOMEM;
33072 #endif
33075 /* Check that the output buffer is large enough for the temporary file
33076 ** name. If it is not, return SQLITE_ERROR.
33078 if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
33079 return SQLITE_ERROR;
33082 for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
33083 zTempPath[i] = 0;
33085 sqlite3_snprintf(nBuf-17, zBuf,
33086 "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
33087 j = sqlite3Strlen30(zBuf);
33088 sqlite3_randomness(15, &zBuf[j]);
33089 for(i=0; i<15; i++, j++){
33090 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
33092 zBuf[j] = 0;
33094 OSTRACE(("TEMP FILENAME: %s\n", zBuf));
33095 return SQLITE_OK;
33099 ** The return value of getLastErrorMsg
33100 ** is zero if the error message fits in the buffer, or non-zero
33101 ** otherwise (if the message was truncated).
33103 static int getLastErrorMsg(int nBuf, char *zBuf){
33104 /* FormatMessage returns 0 on failure. Otherwise it
33105 ** returns the number of TCHARs written to the output
33106 ** buffer, excluding the terminating null char.
33108 DWORD error = GetLastError();
33109 DWORD dwLen = 0;
33110 char *zOut = 0;
33112 if( isNT() ){
33113 WCHAR *zTempWide = NULL;
33114 dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
33115 NULL,
33116 error,
33118 (LPWSTR) &zTempWide,
33121 if( dwLen > 0 ){
33122 /* allocate a buffer and convert to UTF8 */
33123 zOut = unicodeToUtf8(zTempWide);
33124 /* free the system buffer allocated by FormatMessage */
33125 LocalFree(zTempWide);
33127 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33128 ** Since the ASCII version of these Windows API do not exist for WINCE,
33129 ** it's important to not reference them for WINCE builds.
33131 #if SQLITE_OS_WINCE==0
33132 }else{
33133 char *zTemp = NULL;
33134 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
33135 NULL,
33136 error,
33138 (LPSTR) &zTemp,
33141 if( dwLen > 0 ){
33142 /* allocate a buffer and convert to UTF8 */
33143 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33144 /* free the system buffer allocated by FormatMessage */
33145 LocalFree(zTemp);
33147 #endif
33149 if( 0 == dwLen ){
33150 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
33151 }else{
33152 /* copy a maximum of nBuf chars to output buffer */
33153 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
33154 /* free the UTF8 buffer */
33155 free(zOut);
33157 return 0;
33161 ** Open a file.
33163 static int winOpen(
33164 sqlite3_vfs *pVfs, /* Not used */
33165 const char *zName, /* Name of the file (UTF-8) */
33166 sqlite3_file *id, /* Write the SQLite file handle here */
33167 int flags, /* Open mode flags */
33168 int *pOutFlags /* Status return flags */
33170 HANDLE h;
33171 DWORD dwDesiredAccess;
33172 DWORD dwShareMode;
33173 DWORD dwCreationDisposition;
33174 DWORD dwFlagsAndAttributes = 0;
33175 #if SQLITE_OS_WINCE
33176 int isTemp = 0;
33177 #endif
33178 winFile *pFile = (winFile*)id;
33179 void *zConverted; /* Filename in OS encoding */
33180 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
33182 /* If argument zPath is a NULL pointer, this function is required to open
33183 ** a temporary file. Use this buffer to store the file name in.
33185 char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
33187 int rc = SQLITE_OK; /* Function Return Code */
33188 #if !defined(NDEBUG) || SQLITE_OS_WINCE
33189 int eType = flags&0xFFFFFF00; /* Type of file to open */
33190 #endif
33192 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
33193 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
33194 int isCreate = (flags & SQLITE_OPEN_CREATE);
33195 #ifndef NDEBUG
33196 int isReadonly = (flags & SQLITE_OPEN_READONLY);
33197 #endif
33198 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
33200 #ifndef NDEBUG
33201 int isOpenJournal = (isCreate && (
33202 eType==SQLITE_OPEN_MASTER_JOURNAL
33203 || eType==SQLITE_OPEN_MAIN_JOURNAL
33204 || eType==SQLITE_OPEN_WAL
33206 #endif
33208 /* Check the following statements are true:
33210 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
33211 ** (b) if CREATE is set, then READWRITE must also be set, and
33212 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
33213 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
33215 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
33216 assert(isCreate==0 || isReadWrite);
33217 assert(isExclusive==0 || isCreate);
33218 assert(isDelete==0 || isCreate);
33220 /* The main DB, main journal, WAL file and master journal are never
33221 ** automatically deleted. Nor are they ever temporary files. */
33222 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
33223 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
33224 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
33225 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
33227 /* Assert that the upper layer has set one of the "file-type" flags. */
33228 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
33229 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
33230 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
33231 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
33234 assert( id!=0 );
33235 UNUSED_PARAMETER(pVfs);
33237 pFile->h = INVALID_HANDLE_VALUE;
33239 /* If the second argument to this function is NULL, generate a
33240 ** temporary file name to use
33242 if( !zUtf8Name ){
33243 assert(isDelete && !isOpenJournal);
33244 rc = getTempname(MAX_PATH+1, zTmpname);
33245 if( rc!=SQLITE_OK ){
33246 return rc;
33248 zUtf8Name = zTmpname;
33251 /* Convert the filename to the system encoding. */
33252 zConverted = convertUtf8Filename(zUtf8Name);
33253 if( zConverted==0 ){
33254 return SQLITE_NOMEM;
33257 if( isReadWrite ){
33258 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
33259 }else{
33260 dwDesiredAccess = GENERIC_READ;
33263 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
33264 ** created. SQLite doesn't use it to indicate "exclusive access"
33265 ** as it is usually understood.
33267 if( isExclusive ){
33268 /* Creates a new file, only if it does not already exist. */
33269 /* If the file exists, it fails. */
33270 dwCreationDisposition = CREATE_NEW;
33271 }else if( isCreate ){
33272 /* Open existing file, or create if it doesn't exist */
33273 dwCreationDisposition = OPEN_ALWAYS;
33274 }else{
33275 /* Opens a file, only if it exists. */
33276 dwCreationDisposition = OPEN_EXISTING;
33279 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
33281 if( isDelete ){
33282 #if SQLITE_OS_WINCE
33283 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
33284 isTemp = 1;
33285 #else
33286 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
33287 | FILE_ATTRIBUTE_HIDDEN
33288 | FILE_FLAG_DELETE_ON_CLOSE;
33289 #endif
33290 }else{
33291 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
33293 /* Reports from the internet are that performance is always
33294 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
33295 #if SQLITE_OS_WINCE
33296 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
33297 #endif
33299 if( isNT() ){
33300 h = CreateFileW((WCHAR*)zConverted,
33301 dwDesiredAccess,
33302 dwShareMode,
33303 NULL,
33304 dwCreationDisposition,
33305 dwFlagsAndAttributes,
33306 NULL
33308 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33309 ** Since the ASCII version of these Windows API do not exist for WINCE,
33310 ** it's important to not reference them for WINCE builds.
33312 #if SQLITE_OS_WINCE==0
33313 }else{
33314 h = CreateFileA((char*)zConverted,
33315 dwDesiredAccess,
33316 dwShareMode,
33317 NULL,
33318 dwCreationDisposition,
33319 dwFlagsAndAttributes,
33320 NULL
33322 #endif
33325 OSTRACE(("OPEN %d %s 0x%lx %s\n",
33326 h, zName, dwDesiredAccess,
33327 h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
33329 if( h==INVALID_HANDLE_VALUE ){
33330 pFile->lastErrno = GetLastError();
33331 free(zConverted);
33332 if( isReadWrite ){
33333 return winOpen(pVfs, zName, id,
33334 ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
33335 }else{
33336 return SQLITE_CANTOPEN_BKPT;
33340 if( pOutFlags ){
33341 if( isReadWrite ){
33342 *pOutFlags = SQLITE_OPEN_READWRITE;
33343 }else{
33344 *pOutFlags = SQLITE_OPEN_READONLY;
33348 memset(pFile, 0, sizeof(*pFile));
33349 pFile->pMethod = &winIoMethod;
33350 pFile->h = h;
33351 pFile->lastErrno = NO_ERROR;
33352 pFile->pVfs = pVfs;
33353 pFile->pShm = 0;
33354 pFile->zPath = zName;
33355 pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
33357 #if SQLITE_OS_WINCE
33358 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
33359 && !winceCreateLock(zName, pFile)
33361 CloseHandle(h);
33362 free(zConverted);
33363 return SQLITE_CANTOPEN_BKPT;
33365 if( isTemp ){
33366 pFile->zDeleteOnClose = zConverted;
33367 }else
33368 #endif
33370 free(zConverted);
33373 OpenCounter(+1);
33374 return rc;
33378 ** Delete the named file.
33380 ** Note that windows does not allow a file to be deleted if some other
33381 ** process has it open. Sometimes a virus scanner or indexing program
33382 ** will open a journal file shortly after it is created in order to do
33383 ** whatever it does. While this other process is holding the
33384 ** file open, we will be unable to delete it. To work around this
33385 ** problem, we delay 100 milliseconds and try to delete again. Up
33386 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
33387 ** up and returning an error.
33389 #define MX_DELETION_ATTEMPTS 5
33390 static int winDelete(
33391 sqlite3_vfs *pVfs, /* Not used on win32 */
33392 const char *zFilename, /* Name of file to delete */
33393 int syncDir /* Not used on win32 */
33395 int cnt = 0;
33396 DWORD rc;
33397 DWORD error = 0;
33398 void *zConverted;
33399 UNUSED_PARAMETER(pVfs);
33400 UNUSED_PARAMETER(syncDir);
33402 SimulateIOError(return SQLITE_IOERR_DELETE);
33403 zConverted = convertUtf8Filename(zFilename);
33404 if( zConverted==0 ){
33405 return SQLITE_NOMEM;
33407 if( isNT() ){
33409 DeleteFileW(zConverted);
33410 }while( ( ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
33411 || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33412 && (++cnt < MX_DELETION_ATTEMPTS)
33413 && (Sleep(100), 1) );
33414 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33415 ** Since the ASCII version of these Windows API do not exist for WINCE,
33416 ** it's important to not reference them for WINCE builds.
33418 #if SQLITE_OS_WINCE==0
33419 }else{
33421 DeleteFileA(zConverted);
33422 }while( ( ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
33423 || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33424 && (++cnt < MX_DELETION_ATTEMPTS)
33425 && (Sleep(100), 1) );
33426 #endif
33428 free(zConverted);
33429 OSTRACE(("DELETE \"%s\" %s\n", zFilename,
33430 ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
33431 "ok" : "failed" ));
33433 return ( (rc == INVALID_FILE_ATTRIBUTES)
33434 && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
33438 ** Check the existance and status of a file.
33440 static int winAccess(
33441 sqlite3_vfs *pVfs, /* Not used on win32 */
33442 const char *zFilename, /* Name of file to check */
33443 int flags, /* Type of test to make on this file */
33444 int *pResOut /* OUT: Result */
33446 DWORD attr;
33447 int rc = 0;
33448 void *zConverted;
33449 UNUSED_PARAMETER(pVfs);
33451 SimulateIOError( return SQLITE_IOERR_ACCESS; );
33452 zConverted = convertUtf8Filename(zFilename);
33453 if( zConverted==0 ){
33454 return SQLITE_NOMEM;
33456 if( isNT() ){
33457 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33458 memset(&sAttrData, 0, sizeof(sAttrData));
33459 if( GetFileAttributesExW((WCHAR*)zConverted,
33460 GetFileExInfoStandard,
33461 &sAttrData) ){
33462 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
33463 ** as if it does not exist.
33465 if( flags==SQLITE_ACCESS_EXISTS
33466 && sAttrData.nFileSizeHigh==0
33467 && sAttrData.nFileSizeLow==0 ){
33468 attr = INVALID_FILE_ATTRIBUTES;
33469 }else{
33470 attr = sAttrData.dwFileAttributes;
33472 }else{
33473 if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
33474 free(zConverted);
33475 return SQLITE_IOERR_ACCESS;
33476 }else{
33477 attr = INVALID_FILE_ATTRIBUTES;
33480 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33481 ** Since the ASCII version of these Windows API do not exist for WINCE,
33482 ** it's important to not reference them for WINCE builds.
33484 #if SQLITE_OS_WINCE==0
33485 }else{
33486 attr = GetFileAttributesA((char*)zConverted);
33487 #endif
33489 free(zConverted);
33490 switch( flags ){
33491 case SQLITE_ACCESS_READ:
33492 case SQLITE_ACCESS_EXISTS:
33493 rc = attr!=INVALID_FILE_ATTRIBUTES;
33494 break;
33495 case SQLITE_ACCESS_READWRITE:
33496 rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
33497 break;
33498 default:
33499 assert(!"Invalid flags argument");
33501 *pResOut = rc;
33502 return SQLITE_OK;
33507 ** Turn a relative pathname into a full pathname. Write the full
33508 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
33509 ** bytes in size.
33511 static int winFullPathname(
33512 sqlite3_vfs *pVfs, /* Pointer to vfs object */
33513 const char *zRelative, /* Possibly relative input path */
33514 int nFull, /* Size of output buffer in bytes */
33515 char *zFull /* Output buffer */
33518 #if defined(__CYGWIN__)
33519 SimulateIOError( return SQLITE_ERROR );
33520 UNUSED_PARAMETER(nFull);
33521 cygwin_conv_to_full_win32_path(zRelative, zFull);
33522 return SQLITE_OK;
33523 #endif
33525 #if SQLITE_OS_WINCE
33526 SimulateIOError( return SQLITE_ERROR );
33527 UNUSED_PARAMETER(nFull);
33528 /* WinCE has no concept of a relative pathname, or so I am told. */
33529 sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
33530 return SQLITE_OK;
33531 #endif
33533 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
33534 int nByte;
33535 void *zConverted;
33536 char *zOut;
33538 /* It's odd to simulate an io-error here, but really this is just
33539 ** using the io-error infrastructure to test that SQLite handles this
33540 ** function failing. This function could fail if, for example, the
33541 ** current working directory has been unlinked.
33543 SimulateIOError( return SQLITE_ERROR );
33544 UNUSED_PARAMETER(nFull);
33545 zConverted = convertUtf8Filename(zRelative);
33546 if( isNT() ){
33547 WCHAR *zTemp;
33548 nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
33549 zTemp = malloc( nByte*sizeof(zTemp[0]) );
33550 if( zTemp==0 ){
33551 free(zConverted);
33552 return SQLITE_NOMEM;
33554 GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
33555 free(zConverted);
33556 zOut = unicodeToUtf8(zTemp);
33557 free(zTemp);
33558 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33559 ** Since the ASCII version of these Windows API do not exist for WINCE,
33560 ** it's important to not reference them for WINCE builds.
33562 #if SQLITE_OS_WINCE==0
33563 }else{
33564 char *zTemp;
33565 nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
33566 zTemp = malloc( nByte*sizeof(zTemp[0]) );
33567 if( zTemp==0 ){
33568 free(zConverted);
33569 return SQLITE_NOMEM;
33571 GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
33572 free(zConverted);
33573 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33574 free(zTemp);
33575 #endif
33577 if( zOut ){
33578 sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
33579 free(zOut);
33580 return SQLITE_OK;
33581 }else{
33582 return SQLITE_NOMEM;
33584 #endif
33588 ** Get the sector size of the device used to store
33589 ** file.
33591 static int getSectorSize(
33592 sqlite3_vfs *pVfs,
33593 const char *zRelative /* UTF-8 file name */
33595 DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
33596 /* GetDiskFreeSpace is not supported under WINCE */
33597 #if SQLITE_OS_WINCE
33598 UNUSED_PARAMETER(pVfs);
33599 UNUSED_PARAMETER(zRelative);
33600 #else
33601 char zFullpath[MAX_PATH+1];
33602 int rc;
33603 DWORD dwRet = 0;
33604 DWORD dwDummy;
33607 ** We need to get the full path name of the file
33608 ** to get the drive letter to look up the sector
33609 ** size.
33611 SimulateIOErrorBenign(1);
33612 rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
33613 SimulateIOErrorBenign(0);
33614 if( rc == SQLITE_OK )
33616 void *zConverted = convertUtf8Filename(zFullpath);
33617 if( zConverted ){
33618 if( isNT() ){
33619 /* trim path to just drive reference */
33620 WCHAR *p = zConverted;
33621 for(;*p;p++){
33622 if( *p == '\\' ){
33623 *p = '\0';
33624 break;
33627 dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
33628 &dwDummy,
33629 &bytesPerSector,
33630 &dwDummy,
33631 &dwDummy);
33632 }else{
33633 /* trim path to just drive reference */
33634 char *p = (char *)zConverted;
33635 for(;*p;p++){
33636 if( *p == '\\' ){
33637 *p = '\0';
33638 break;
33641 dwRet = GetDiskFreeSpaceA((char*)zConverted,
33642 &dwDummy,
33643 &bytesPerSector,
33644 &dwDummy,
33645 &dwDummy);
33647 free(zConverted);
33649 if( !dwRet ){
33650 bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
33653 #endif
33654 return (int) bytesPerSector;
33657 #ifndef SQLITE_OMIT_LOAD_EXTENSION
33659 ** Interfaces for opening a shared library, finding entry points
33660 ** within the shared library, and closing the shared library.
33663 ** Interfaces for opening a shared library, finding entry points
33664 ** within the shared library, and closing the shared library.
33666 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
33667 HANDLE h;
33668 void *zConverted = convertUtf8Filename(zFilename);
33669 UNUSED_PARAMETER(pVfs);
33670 if( zConverted==0 ){
33671 return 0;
33673 if( isNT() ){
33674 h = LoadLibraryW((WCHAR*)zConverted);
33675 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33676 ** Since the ASCII version of these Windows API do not exist for WINCE,
33677 ** it's important to not reference them for WINCE builds.
33679 #if SQLITE_OS_WINCE==0
33680 }else{
33681 h = LoadLibraryA((char*)zConverted);
33682 #endif
33684 free(zConverted);
33685 return (void*)h;
33687 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
33688 UNUSED_PARAMETER(pVfs);
33689 getLastErrorMsg(nBuf, zBufOut);
33691 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
33692 UNUSED_PARAMETER(pVfs);
33693 #if SQLITE_OS_WINCE
33694 /* The GetProcAddressA() routine is only available on wince. */
33695 return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
33696 #else
33697 /* All other windows platforms expect GetProcAddress() to take
33698 ** an Ansi string regardless of the _UNICODE setting */
33699 return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
33700 #endif
33702 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
33703 UNUSED_PARAMETER(pVfs);
33704 FreeLibrary((HANDLE)pHandle);
33706 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
33707 #define winDlOpen 0
33708 #define winDlError 0
33709 #define winDlSym 0
33710 #define winDlClose 0
33711 #endif
33715 ** Write up to nBuf bytes of randomness into zBuf.
33717 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33718 int n = 0;
33719 UNUSED_PARAMETER(pVfs);
33720 #if defined(SQLITE_TEST)
33721 n = nBuf;
33722 memset(zBuf, 0, nBuf);
33723 #else
33724 if( sizeof(SYSTEMTIME)<=nBuf-n ){
33725 SYSTEMTIME x;
33726 GetSystemTime(&x);
33727 memcpy(&zBuf[n], &x, sizeof(x));
33728 n += sizeof(x);
33730 if( sizeof(DWORD)<=nBuf-n ){
33731 DWORD pid = GetCurrentProcessId();
33732 memcpy(&zBuf[n], &pid, sizeof(pid));
33733 n += sizeof(pid);
33735 if( sizeof(DWORD)<=nBuf-n ){
33736 DWORD cnt = GetTickCount();
33737 memcpy(&zBuf[n], &cnt, sizeof(cnt));
33738 n += sizeof(cnt);
33740 if( sizeof(LARGE_INTEGER)<=nBuf-n ){
33741 LARGE_INTEGER i;
33742 QueryPerformanceCounter(&i);
33743 memcpy(&zBuf[n], &i, sizeof(i));
33744 n += sizeof(i);
33746 #endif
33747 return n;
33752 ** Sleep for a little while. Return the amount of time slept.
33754 static int winSleep(sqlite3_vfs *pVfs, int microsec){
33755 Sleep((microsec+999)/1000);
33756 UNUSED_PARAMETER(pVfs);
33757 return ((microsec+999)/1000)*1000;
33761 ** The following variable, if set to a non-zero value, is interpreted as
33762 ** the number of seconds since 1970 and is used to set the result of
33763 ** sqlite3OsCurrentTime() during testing.
33765 #ifdef SQLITE_TEST
33766 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
33767 #endif
33770 ** Find the current time (in Universal Coordinated Time). Write into *piNow
33771 ** the current time and date as a Julian Day number times 86_400_000. In
33772 ** other words, write into *piNow the number of milliseconds since the Julian
33773 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
33774 ** proleptic Gregorian calendar.
33776 ** On success, return 0. Return 1 if the time and date cannot be found.
33778 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
33779 /* FILETIME structure is a 64-bit value representing the number of
33780 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
33782 FILETIME ft;
33783 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
33784 #ifdef SQLITE_TEST
33785 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
33786 #endif
33787 /* 2^32 - to avoid use of LL and warnings in gcc */
33788 static const sqlite3_int64 max32BitValue =
33789 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
33791 #if SQLITE_OS_WINCE
33792 SYSTEMTIME time;
33793 GetSystemTime(&time);
33794 /* if SystemTimeToFileTime() fails, it returns zero. */
33795 if (!SystemTimeToFileTime(&time,&ft)){
33796 return 1;
33798 #else
33799 GetSystemTimeAsFileTime( &ft );
33800 #endif
33802 *piNow = winFiletimeEpoch +
33803 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
33804 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
33806 #ifdef SQLITE_TEST
33807 if( sqlite3_current_time ){
33808 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
33810 #endif
33811 UNUSED_PARAMETER(pVfs);
33812 return 0;
33816 ** Find the current time (in Universal Coordinated Time). Write the
33817 ** current time and date as a Julian Day number into *prNow and
33818 ** return 0. Return 1 if the time and date cannot be found.
33820 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
33821 int rc;
33822 sqlite3_int64 i;
33823 rc = winCurrentTimeInt64(pVfs, &i);
33824 if( !rc ){
33825 *prNow = i/86400000.0;
33827 return rc;
33831 ** The idea is that this function works like a combination of
33832 ** GetLastError() and FormatMessage() on windows (or errno and
33833 ** strerror_r() on unix). After an error is returned by an OS
33834 ** function, SQLite calls this function with zBuf pointing to
33835 ** a buffer of nBuf bytes. The OS layer should populate the
33836 ** buffer with a nul-terminated UTF-8 encoded error message
33837 ** describing the last IO error to have occurred within the calling
33838 ** thread.
33840 ** If the error message is too large for the supplied buffer,
33841 ** it should be truncated. The return value of xGetLastError
33842 ** is zero if the error message fits in the buffer, or non-zero
33843 ** otherwise (if the message was truncated). If non-zero is returned,
33844 ** then it is not necessary to include the nul-terminator character
33845 ** in the output buffer.
33847 ** Not supplying an error message will have no adverse effect
33848 ** on SQLite. It is fine to have an implementation that never
33849 ** returns an error message:
33851 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33852 ** assert(zBuf[0]=='\0');
33853 ** return 0;
33854 ** }
33856 ** However if an error message is supplied, it will be incorporated
33857 ** by sqlite into the error message available to the user using
33858 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
33860 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33861 UNUSED_PARAMETER(pVfs);
33862 return getLastErrorMsg(nBuf, zBuf);
33868 ** Initialize and deinitialize the operating system interface.
33870 SQLITE_API int sqlite3_os_init(void){
33871 static sqlite3_vfs winVfs = {
33872 3, /* iVersion */
33873 sizeof(winFile), /* szOsFile */
33874 MAX_PATH, /* mxPathname */
33875 0, /* pNext */
33876 "win32", /* zName */
33877 0, /* pAppData */
33878 winOpen, /* xOpen */
33879 winDelete, /* xDelete */
33880 winAccess, /* xAccess */
33881 winFullPathname, /* xFullPathname */
33882 winDlOpen, /* xDlOpen */
33883 winDlError, /* xDlError */
33884 winDlSym, /* xDlSym */
33885 winDlClose, /* xDlClose */
33886 winRandomness, /* xRandomness */
33887 winSleep, /* xSleep */
33888 winCurrentTime, /* xCurrentTime */
33889 winGetLastError, /* xGetLastError */
33890 winCurrentTimeInt64, /* xCurrentTimeInt64 */
33891 0, /* xSetSystemCall */
33892 0, /* xGetSystemCall */
33893 0, /* xNextSystemCall */
33896 #ifndef SQLITE_OMIT_WAL
33897 /* get memory map allocation granularity */
33898 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
33899 GetSystemInfo(&winSysInfo);
33900 assert(winSysInfo.dwAllocationGranularity > 0);
33901 #endif
33903 sqlite3_vfs_register(&winVfs, 1);
33904 return SQLITE_OK;
33906 SQLITE_API int sqlite3_os_end(void){
33907 return SQLITE_OK;
33910 void chromium_sqlite3_initialize_win_sqlite3_file(sqlite3_file* file, HANDLE handle) {
33911 winFile* winSQLite3File = (winFile*)file;
33912 memset(file, 0, sizeof(*file));
33913 winSQLite3File->pMethod = &winIoMethod;
33914 winSQLite3File->h = handle;
33917 #endif /* SQLITE_OS_WIN */
33919 /************** End of os_win.c **********************************************/
33920 /************** Begin file bitvec.c ******************************************/
33922 ** 2008 February 16
33924 ** The author disclaims copyright to this source code. In place of
33925 ** a legal notice, here is a blessing:
33927 ** May you do good and not evil.
33928 ** May you find forgiveness for yourself and forgive others.
33929 ** May you share freely, never taking more than you give.
33931 *************************************************************************
33932 ** This file implements an object that represents a fixed-length
33933 ** bitmap. Bits are numbered starting with 1.
33935 ** A bitmap is used to record which pages of a database file have been
33936 ** journalled during a transaction, or which pages have the "dont-write"
33937 ** property. Usually only a few pages are meet either condition.
33938 ** So the bitmap is usually sparse and has low cardinality.
33939 ** But sometimes (for example when during a DROP of a large table) most
33940 ** or all of the pages in a database can get journalled. In those cases,
33941 ** the bitmap becomes dense with high cardinality. The algorithm needs
33942 ** to handle both cases well.
33944 ** The size of the bitmap is fixed when the object is created.
33946 ** All bits are clear when the bitmap is created. Individual bits
33947 ** may be set or cleared one at a time.
33949 ** Test operations are about 100 times more common that set operations.
33950 ** Clear operations are exceedingly rare. There are usually between
33951 ** 5 and 500 set operations per Bitvec object, though the number of sets can
33952 ** sometimes grow into tens of thousands or larger. The size of the
33953 ** Bitvec object is the number of pages in the database file at the
33954 ** start of a transaction, and is thus usually less than a few thousand,
33955 ** but can be as large as 2 billion for a really big database.
33958 /* Size of the Bitvec structure in bytes. */
33959 #define BITVEC_SZ 512
33961 /* Round the union size down to the nearest pointer boundary, since that's how
33962 ** it will be aligned within the Bitvec struct. */
33963 #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
33965 /* Type of the array "element" for the bitmap representation.
33966 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
33967 ** Setting this to the "natural word" size of your CPU may improve
33968 ** performance. */
33969 #define BITVEC_TELEM u8
33970 /* Size, in bits, of the bitmap element. */
33971 #define BITVEC_SZELEM 8
33972 /* Number of elements in a bitmap array. */
33973 #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
33974 /* Number of bits in the bitmap array. */
33975 #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
33977 /* Number of u32 values in hash table. */
33978 #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
33979 /* Maximum number of entries in hash table before
33980 ** sub-dividing and re-hashing. */
33981 #define BITVEC_MXHASH (BITVEC_NINT/2)
33982 /* Hashing function for the aHash representation.
33983 ** Empirical testing showed that the *37 multiplier
33984 ** (an arbitrary prime)in the hash function provided
33985 ** no fewer collisions than the no-op *1. */
33986 #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
33988 #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
33992 ** A bitmap is an instance of the following structure.
33994 ** This bitmap records the existance of zero or more bits
33995 ** with values between 1 and iSize, inclusive.
33997 ** There are three possible representations of the bitmap.
33998 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
33999 ** bitmap. The least significant bit is bit 1.
34001 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
34002 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
34004 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
34005 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
34006 ** handles up to iDivisor separate values of i. apSub[0] holds
34007 ** values between 1 and iDivisor. apSub[1] holds values between
34008 ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
34009 ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
34010 ** to hold deal with values between 1 and iDivisor.
34012 struct Bitvec {
34013 u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
34014 u32 nSet; /* Number of bits that are set - only valid for aHash
34015 ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
34016 ** this would be 125. */
34017 u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
34018 /* Should >=0 for apSub element. */
34019 /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
34020 /* For a BITVEC_SZ of 512, this would be 34,359,739. */
34021 union {
34022 BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
34023 u32 aHash[BITVEC_NINT]; /* Hash table representation */
34024 Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
34025 } u;
34029 ** Create a new bitmap object able to handle bits between 0 and iSize,
34030 ** inclusive. Return a pointer to the new object. Return NULL if
34031 ** malloc fails.
34033 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
34034 Bitvec *p;
34035 assert( sizeof(*p)==BITVEC_SZ );
34036 p = sqlite3MallocZero( sizeof(*p) );
34037 if( p ){
34038 p->iSize = iSize;
34040 return p;
34044 ** Check to see if the i-th bit is set. Return true or false.
34045 ** If p is NULL (if the bitmap has not been created) or if
34046 ** i is out of range, then return false.
34048 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
34049 if( p==0 ) return 0;
34050 if( i>p->iSize || i==0 ) return 0;
34051 i--;
34052 while( p->iDivisor ){
34053 u32 bin = i/p->iDivisor;
34054 i = i%p->iDivisor;
34055 p = p->u.apSub[bin];
34056 if (!p) {
34057 return 0;
34060 if( p->iSize<=BITVEC_NBIT ){
34061 return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
34062 } else{
34063 u32 h = BITVEC_HASH(i++);
34064 while( p->u.aHash[h] ){
34065 if( p->u.aHash[h]==i ) return 1;
34066 h = (h+1) % BITVEC_NINT;
34068 return 0;
34073 ** Set the i-th bit. Return 0 on success and an error code if
34074 ** anything goes wrong.
34076 ** This routine might cause sub-bitmaps to be allocated. Failing
34077 ** to get the memory needed to hold the sub-bitmap is the only
34078 ** that can go wrong with an insert, assuming p and i are valid.
34080 ** The calling function must ensure that p is a valid Bitvec object
34081 ** and that the value for "i" is within range of the Bitvec object.
34082 ** Otherwise the behavior is undefined.
34084 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
34085 u32 h;
34086 if( p==0 ) return SQLITE_OK;
34087 assert( i>0 );
34088 assert( i<=p->iSize );
34089 i--;
34090 while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
34091 u32 bin = i/p->iDivisor;
34092 i = i%p->iDivisor;
34093 if( p->u.apSub[bin]==0 ){
34094 p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34095 if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34097 p = p->u.apSub[bin];
34099 if( p->iSize<=BITVEC_NBIT ){
34100 p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34101 return SQLITE_OK;
34103 h = BITVEC_HASH(i++);
34104 /* if there wasn't a hash collision, and this doesn't */
34105 /* completely fill the hash, then just add it without */
34106 /* worring about sub-dividing and re-hashing. */
34107 if( !p->u.aHash[h] ){
34108 if (p->nSet<(BITVEC_NINT-1)) {
34109 goto bitvec_set_end;
34110 } else {
34111 goto bitvec_set_rehash;
34114 /* there was a collision, check to see if it's already */
34115 /* in hash, if not, try to find a spot for it */
34116 do {
34117 if( p->u.aHash[h]==i ) return SQLITE_OK;
34118 h++;
34119 if( h>=BITVEC_NINT ) h = 0;
34120 } while( p->u.aHash[h] );
34121 /* we didn't find it in the hash. h points to the first */
34122 /* available free spot. check to see if this is going to */
34123 /* make our hash too "full". */
34124 bitvec_set_rehash:
34125 if( p->nSet>=BITVEC_MXHASH ){
34126 unsigned int j;
34127 int rc;
34128 u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
34129 if( aiValues==0 ){
34130 return SQLITE_NOMEM;
34131 }else{
34132 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34133 memset(p->u.apSub, 0, sizeof(p->u.apSub));
34134 p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
34135 rc = sqlite3BitvecSet(p, i);
34136 for(j=0; j<BITVEC_NINT; j++){
34137 if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
34139 sqlite3StackFree(0, aiValues);
34140 return rc;
34143 bitvec_set_end:
34144 p->nSet++;
34145 p->u.aHash[h] = i;
34146 return SQLITE_OK;
34150 ** Clear the i-th bit.
34152 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
34153 ** that BitvecClear can use to rebuilt its hash table.
34155 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
34156 if( p==0 ) return;
34157 assert( i>0 );
34158 i--;
34159 while( p->iDivisor ){
34160 u32 bin = i/p->iDivisor;
34161 i = i%p->iDivisor;
34162 p = p->u.apSub[bin];
34163 if (!p) {
34164 return;
34167 if( p->iSize<=BITVEC_NBIT ){
34168 p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
34169 }else{
34170 unsigned int j;
34171 u32 *aiValues = pBuf;
34172 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34173 memset(p->u.aHash, 0, sizeof(p->u.aHash));
34174 p->nSet = 0;
34175 for(j=0; j<BITVEC_NINT; j++){
34176 if( aiValues[j] && aiValues[j]!=(i+1) ){
34177 u32 h = BITVEC_HASH(aiValues[j]-1);
34178 p->nSet++;
34179 while( p->u.aHash[h] ){
34180 h++;
34181 if( h>=BITVEC_NINT ) h = 0;
34183 p->u.aHash[h] = aiValues[j];
34190 ** Destroy a bitmap object. Reclaim all memory used.
34192 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
34193 if( p==0 ) return;
34194 if( p->iDivisor ){
34195 unsigned int i;
34196 for(i=0; i<BITVEC_NPTR; i++){
34197 sqlite3BitvecDestroy(p->u.apSub[i]);
34200 sqlite3_free(p);
34204 ** Return the value of the iSize parameter specified when Bitvec *p
34205 ** was created.
34207 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
34208 return p->iSize;
34211 #ifndef SQLITE_OMIT_BUILTIN_TEST
34213 ** Let V[] be an array of unsigned characters sufficient to hold
34214 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
34215 ** Then the following macros can be used to set, clear, or test
34216 ** individual bits within V.
34218 #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
34219 #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
34220 #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
34223 ** This routine runs an extensive test of the Bitvec code.
34225 ** The input is an array of integers that acts as a program
34226 ** to test the Bitvec. The integers are opcodes followed
34227 ** by 0, 1, or 3 operands, depending on the opcode. Another
34228 ** opcode follows immediately after the last operand.
34230 ** There are 6 opcodes numbered from 0 through 5. 0 is the
34231 ** "halt" opcode and causes the test to end.
34233 ** 0 Halt and return the number of errors
34234 ** 1 N S X Set N bits beginning with S and incrementing by X
34235 ** 2 N S X Clear N bits beginning with S and incrementing by X
34236 ** 3 N Set N randomly chosen bits
34237 ** 4 N Clear N randomly chosen bits
34238 ** 5 N S X Set N bits from S increment X in array only, not in bitvec
34240 ** The opcodes 1 through 4 perform set and clear operations are performed
34241 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
34242 ** Opcode 5 works on the linear array only, not on the Bitvec.
34243 ** Opcode 5 is used to deliberately induce a fault in order to
34244 ** confirm that error detection works.
34246 ** At the conclusion of the test the linear array is compared
34247 ** against the Bitvec object. If there are any differences,
34248 ** an error is returned. If they are the same, zero is returned.
34250 ** If a memory allocation error occurs, return -1.
34252 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
34253 Bitvec *pBitvec = 0;
34254 unsigned char *pV = 0;
34255 int rc = -1;
34256 int i, nx, pc, op;
34257 void *pTmpSpace;
34259 /* Allocate the Bitvec to be tested and a linear array of
34260 ** bits to act as the reference */
34261 pBitvec = sqlite3BitvecCreate( sz );
34262 pV = sqlite3_malloc( (sz+7)/8 + 1 );
34263 pTmpSpace = sqlite3_malloc(BITVEC_SZ);
34264 if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
34265 memset(pV, 0, (sz+7)/8 + 1);
34267 /* NULL pBitvec tests */
34268 sqlite3BitvecSet(0, 1);
34269 sqlite3BitvecClear(0, 1, pTmpSpace);
34271 /* Run the program */
34272 pc = 0;
34273 while( (op = aOp[pc])!=0 ){
34274 switch( op ){
34275 case 1:
34276 case 2:
34277 case 5: {
34278 nx = 4;
34279 i = aOp[pc+2] - 1;
34280 aOp[pc+2] += aOp[pc+3];
34281 break;
34283 case 3:
34284 case 4:
34285 default: {
34286 nx = 2;
34287 sqlite3_randomness(sizeof(i), &i);
34288 break;
34291 if( (--aOp[pc+1]) > 0 ) nx = 0;
34292 pc += nx;
34293 i = (i & 0x7fffffff)%sz;
34294 if( (op & 1)!=0 ){
34295 SETBIT(pV, (i+1));
34296 if( op!=5 ){
34297 if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
34299 }else{
34300 CLEARBIT(pV, (i+1));
34301 sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
34305 /* Test to make sure the linear array exactly matches the
34306 ** Bitvec object. Start with the assumption that they do
34307 ** match (rc==0). Change rc to non-zero if a discrepancy
34308 ** is found.
34310 rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
34311 + sqlite3BitvecTest(pBitvec, 0)
34312 + (sqlite3BitvecSize(pBitvec) - sz);
34313 for(i=1; i<=sz; i++){
34314 if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
34315 rc = i;
34316 break;
34320 /* Free allocated structure */
34321 bitvec_end:
34322 sqlite3_free(pTmpSpace);
34323 sqlite3_free(pV);
34324 sqlite3BitvecDestroy(pBitvec);
34325 return rc;
34327 #endif /* SQLITE_OMIT_BUILTIN_TEST */
34329 /************** End of bitvec.c **********************************************/
34330 /************** Begin file pcache.c ******************************************/
34332 ** 2008 August 05
34334 ** The author disclaims copyright to this source code. In place of
34335 ** a legal notice, here is a blessing:
34337 ** May you do good and not evil.
34338 ** May you find forgiveness for yourself and forgive others.
34339 ** May you share freely, never taking more than you give.
34341 *************************************************************************
34342 ** This file implements that page cache.
34346 ** A complete page cache is an instance of this structure.
34348 struct PCache {
34349 PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
34350 PgHdr *pSynced; /* Last synced page in dirty page list */
34351 int nRef; /* Number of referenced pages */
34352 int nMax; /* Configured cache size */
34353 int szPage; /* Size of every page in this cache */
34354 int szExtra; /* Size of extra space for each page */
34355 int bPurgeable; /* True if pages are on backing store */
34356 int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
34357 void *pStress; /* Argument to xStress */
34358 sqlite3_pcache *pCache; /* Pluggable cache module */
34359 PgHdr *pPage1; /* Reference to page 1 */
34363 ** Some of the assert() macros in this code are too expensive to run
34364 ** even during normal debugging. Use them only rarely on long-running
34365 ** tests. Enable the expensive asserts using the
34366 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
34368 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
34369 # define expensive_assert(X) assert(X)
34370 #else
34371 # define expensive_assert(X)
34372 #endif
34374 /********************************** Linked List Management ********************/
34376 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
34378 ** Check that the pCache->pSynced variable is set correctly. If it
34379 ** is not, either fail an assert or return zero. Otherwise, return
34380 ** non-zero. This is only used in debugging builds, as follows:
34382 ** expensive_assert( pcacheCheckSynced(pCache) );
34384 static int pcacheCheckSynced(PCache *pCache){
34385 PgHdr *p;
34386 for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
34387 assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
34389 return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
34391 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
34394 ** Remove page pPage from the list of dirty pages.
34396 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
34397 PCache *p = pPage->pCache;
34399 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
34400 assert( pPage->pDirtyPrev || pPage==p->pDirty );
34402 /* Update the PCache1.pSynced variable if necessary. */
34403 if( p->pSynced==pPage ){
34404 PgHdr *pSynced = pPage->pDirtyPrev;
34405 while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
34406 pSynced = pSynced->pDirtyPrev;
34408 p->pSynced = pSynced;
34411 if( pPage->pDirtyNext ){
34412 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
34413 }else{
34414 assert( pPage==p->pDirtyTail );
34415 p->pDirtyTail = pPage->pDirtyPrev;
34417 if( pPage->pDirtyPrev ){
34418 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
34419 }else{
34420 assert( pPage==p->pDirty );
34421 p->pDirty = pPage->pDirtyNext;
34423 pPage->pDirtyNext = 0;
34424 pPage->pDirtyPrev = 0;
34426 expensive_assert( pcacheCheckSynced(p) );
34430 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
34431 ** pPage).
34433 static void pcacheAddToDirtyList(PgHdr *pPage){
34434 PCache *p = pPage->pCache;
34436 assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
34438 pPage->pDirtyNext = p->pDirty;
34439 if( pPage->pDirtyNext ){
34440 assert( pPage->pDirtyNext->pDirtyPrev==0 );
34441 pPage->pDirtyNext->pDirtyPrev = pPage;
34443 p->pDirty = pPage;
34444 if( !p->pDirtyTail ){
34445 p->pDirtyTail = pPage;
34447 if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
34448 p->pSynced = pPage;
34450 expensive_assert( pcacheCheckSynced(p) );
34454 ** Wrapper around the pluggable caches xUnpin method. If the cache is
34455 ** being used for an in-memory database, this function is a no-op.
34457 static void pcacheUnpin(PgHdr *p){
34458 PCache *pCache = p->pCache;
34459 if( pCache->bPurgeable ){
34460 if( p->pgno==1 ){
34461 pCache->pPage1 = 0;
34463 sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
34467 /*************************************************** General Interfaces ******
34469 ** Initialize and shutdown the page cache subsystem. Neither of these
34470 ** functions are threadsafe.
34472 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
34473 if( sqlite3GlobalConfig.pcache.xInit==0 ){
34474 /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
34475 ** built-in default page cache is used instead of the application defined
34476 ** page cache. */
34477 sqlite3PCacheSetDefault();
34479 return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
34481 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
34482 if( sqlite3GlobalConfig.pcache.xShutdown ){
34483 /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
34484 sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
34489 ** Return the size in bytes of a PCache object.
34491 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
34494 ** Create a new PCache object. Storage space to hold the object
34495 ** has already been allocated and is passed in as the p pointer.
34496 ** The caller discovers how much space needs to be allocated by
34497 ** calling sqlite3PcacheSize().
34499 SQLITE_PRIVATE void sqlite3PcacheOpen(
34500 int szPage, /* Size of every page */
34501 int szExtra, /* Extra space associated with each page */
34502 int bPurgeable, /* True if pages are on backing store */
34503 int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
34504 void *pStress, /* Argument to xStress */
34505 PCache *p /* Preallocated space for the PCache */
34507 memset(p, 0, sizeof(PCache));
34508 p->szPage = szPage;
34509 p->szExtra = szExtra;
34510 p->bPurgeable = bPurgeable;
34511 p->xStress = xStress;
34512 p->pStress = pStress;
34513 p->nMax = 100;
34517 ** Change the page size for PCache object. The caller must ensure that there
34518 ** are no outstanding page references when this function is called.
34520 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
34521 assert( pCache->nRef==0 && pCache->pDirty==0 );
34522 if( pCache->pCache ){
34523 sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
34524 pCache->pCache = 0;
34525 pCache->pPage1 = 0;
34527 pCache->szPage = szPage;
34531 ** Try to obtain a page from the cache.
34533 SQLITE_PRIVATE int sqlite3PcacheFetch(
34534 PCache *pCache, /* Obtain the page from this cache */
34535 Pgno pgno, /* Page number to obtain */
34536 int createFlag, /* If true, create page if it does not exist already */
34537 PgHdr **ppPage /* Write the page here */
34539 PgHdr *pPage = 0;
34540 int eCreate;
34542 assert( pCache!=0 );
34543 assert( createFlag==1 || createFlag==0 );
34544 assert( pgno>0 );
34546 /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
34547 ** allocate it now.
34549 if( !pCache->pCache && createFlag ){
34550 sqlite3_pcache *p;
34551 int nByte;
34552 nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
34553 p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
34554 if( !p ){
34555 return SQLITE_NOMEM;
34557 sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
34558 pCache->pCache = p;
34561 eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
34562 if( pCache->pCache ){
34563 pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
34566 if( !pPage && eCreate==1 ){
34567 PgHdr *pPg;
34569 /* Find a dirty page to write-out and recycle. First try to find a
34570 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
34571 ** cleared), but if that is not possible settle for any other
34572 ** unreferenced dirty page.
34574 expensive_assert( pcacheCheckSynced(pCache) );
34575 for(pPg=pCache->pSynced;
34576 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
34577 pPg=pPg->pDirtyPrev
34579 pCache->pSynced = pPg;
34580 if( !pPg ){
34581 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
34583 if( pPg ){
34584 int rc;
34585 rc = pCache->xStress(pCache->pStress, pPg);
34586 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
34587 return rc;
34591 pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
34594 if( pPage ){
34595 if( !pPage->pData ){
34596 memset(pPage, 0, sizeof(PgHdr));
34597 pPage->pData = (void *)&pPage[1];
34598 pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
34599 memset(pPage->pExtra, 0, pCache->szExtra);
34600 pPage->pCache = pCache;
34601 pPage->pgno = pgno;
34603 assert( pPage->pCache==pCache );
34604 assert( pPage->pgno==pgno );
34605 assert( pPage->pData==(void *)&pPage[1] );
34606 assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
34608 if( 0==pPage->nRef ){
34609 pCache->nRef++;
34611 pPage->nRef++;
34612 if( pgno==1 ){
34613 pCache->pPage1 = pPage;
34616 *ppPage = pPage;
34617 return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
34621 ** Decrement the reference count on a page. If the page is clean and the
34622 ** reference count drops to 0, then it is made elible for recycling.
34624 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
34625 assert( p->nRef>0 );
34626 p->nRef--;
34627 if( p->nRef==0 ){
34628 PCache *pCache = p->pCache;
34629 pCache->nRef--;
34630 if( (p->flags&PGHDR_DIRTY)==0 ){
34631 pcacheUnpin(p);
34632 }else{
34633 /* Move the page to the head of the dirty list. */
34634 pcacheRemoveFromDirtyList(p);
34635 pcacheAddToDirtyList(p);
34641 ** Increase the reference count of a supplied page by 1.
34643 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
34644 assert(p->nRef>0);
34645 p->nRef++;
34649 ** Drop a page from the cache. There must be exactly one reference to the
34650 ** page. This function deletes that reference, so after it returns the
34651 ** page pointed to by p is invalid.
34653 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
34654 PCache *pCache;
34655 assert( p->nRef==1 );
34656 if( p->flags&PGHDR_DIRTY ){
34657 pcacheRemoveFromDirtyList(p);
34659 pCache = p->pCache;
34660 pCache->nRef--;
34661 if( p->pgno==1 ){
34662 pCache->pPage1 = 0;
34664 sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
34668 ** Make sure the page is marked as dirty. If it isn't dirty already,
34669 ** make it so.
34671 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
34672 p->flags &= ~PGHDR_DONT_WRITE;
34673 assert( p->nRef>0 );
34674 if( 0==(p->flags & PGHDR_DIRTY) ){
34675 p->flags |= PGHDR_DIRTY;
34676 pcacheAddToDirtyList( p);
34681 ** Make sure the page is marked as clean. If it isn't clean already,
34682 ** make it so.
34684 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
34685 if( (p->flags & PGHDR_DIRTY) ){
34686 pcacheRemoveFromDirtyList(p);
34687 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
34688 if( p->nRef==0 ){
34689 pcacheUnpin(p);
34695 ** Make every page in the cache clean.
34697 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
34698 PgHdr *p;
34699 while( (p = pCache->pDirty)!=0 ){
34700 sqlite3PcacheMakeClean(p);
34705 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
34707 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
34708 PgHdr *p;
34709 for(p=pCache->pDirty; p; p=p->pDirtyNext){
34710 p->flags &= ~PGHDR_NEED_SYNC;
34712 pCache->pSynced = pCache->pDirtyTail;
34716 ** Change the page number of page p to newPgno.
34718 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
34719 PCache *pCache = p->pCache;
34720 assert( p->nRef>0 );
34721 assert( newPgno>0 );
34722 sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
34723 p->pgno = newPgno;
34724 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
34725 pcacheRemoveFromDirtyList(p);
34726 pcacheAddToDirtyList(p);
34731 ** Drop every cache entry whose page number is greater than "pgno". The
34732 ** caller must ensure that there are no outstanding references to any pages
34733 ** other than page 1 with a page number greater than pgno.
34735 ** If there is a reference to page 1 and the pgno parameter passed to this
34736 ** function is 0, then the data area associated with page 1 is zeroed, but
34737 ** the page object is not dropped.
34739 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
34740 if( pCache->pCache ){
34741 PgHdr *p;
34742 PgHdr *pNext;
34743 for(p=pCache->pDirty; p; p=pNext){
34744 pNext = p->pDirtyNext;
34745 /* This routine never gets call with a positive pgno except right
34746 ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
34747 ** it must be that pgno==0.
34749 assert( p->pgno>0 );
34750 if( ALWAYS(p->pgno>pgno) ){
34751 assert( p->flags&PGHDR_DIRTY );
34752 sqlite3PcacheMakeClean(p);
34755 if( pgno==0 && pCache->pPage1 ){
34756 memset(pCache->pPage1->pData, 0, pCache->szPage);
34757 pgno = 1;
34759 sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
34764 ** Close a cache.
34766 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
34767 if( pCache->pCache ){
34768 sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
34773 ** Discard the contents of the cache.
34775 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
34776 sqlite3PcacheTruncate(pCache, 0);
34780 ** Merge two lists of pages connected by pDirty and in pgno order.
34781 ** Do not both fixing the pDirtyPrev pointers.
34783 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
34784 PgHdr result, *pTail;
34785 pTail = &result;
34786 while( pA && pB ){
34787 if( pA->pgno<pB->pgno ){
34788 pTail->pDirty = pA;
34789 pTail = pA;
34790 pA = pA->pDirty;
34791 }else{
34792 pTail->pDirty = pB;
34793 pTail = pB;
34794 pB = pB->pDirty;
34797 if( pA ){
34798 pTail->pDirty = pA;
34799 }else if( pB ){
34800 pTail->pDirty = pB;
34801 }else{
34802 pTail->pDirty = 0;
34804 return result.pDirty;
34808 ** Sort the list of pages in accending order by pgno. Pages are
34809 ** connected by pDirty pointers. The pDirtyPrev pointers are
34810 ** corrupted by this sort.
34812 ** Since there cannot be more than 2^31 distinct pages in a database,
34813 ** there cannot be more than 31 buckets required by the merge sorter.
34814 ** One extra bucket is added to catch overflow in case something
34815 ** ever changes to make the previous sentence incorrect.
34817 #define N_SORT_BUCKET 32
34818 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
34819 PgHdr *a[N_SORT_BUCKET], *p;
34820 int i;
34821 memset(a, 0, sizeof(a));
34822 while( pIn ){
34823 p = pIn;
34824 pIn = p->pDirty;
34825 p->pDirty = 0;
34826 for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
34827 if( a[i]==0 ){
34828 a[i] = p;
34829 break;
34830 }else{
34831 p = pcacheMergeDirtyList(a[i], p);
34832 a[i] = 0;
34835 if( NEVER(i==N_SORT_BUCKET-1) ){
34836 /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
34837 ** the input list. But that is impossible.
34839 a[i] = pcacheMergeDirtyList(a[i], p);
34842 p = a[0];
34843 for(i=1; i<N_SORT_BUCKET; i++){
34844 p = pcacheMergeDirtyList(p, a[i]);
34846 return p;
34850 ** Return a list of all dirty pages in the cache, sorted by page number.
34852 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
34853 PgHdr *p;
34854 for(p=pCache->pDirty; p; p=p->pDirtyNext){
34855 p->pDirty = p->pDirtyNext;
34857 return pcacheSortDirtyList(pCache->pDirty);
34861 ** Return the total number of referenced pages held by the cache.
34863 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
34864 return pCache->nRef;
34868 ** Return the number of references to the page supplied as an argument.
34870 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
34871 return p->nRef;
34875 ** Return the total number of pages in the cache.
34877 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
34878 int nPage = 0;
34879 if( pCache->pCache ){
34880 nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
34882 return nPage;
34886 ** Get the suggested cache-size value.
34888 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
34889 return pCache->nMax;
34893 ** Set the suggested cache-size value.
34895 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
34896 pCache->nMax = mxPage;
34897 if( pCache->pCache ){
34898 sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
34902 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
34904 ** For all dirty pages currently in the cache, invoke the specified
34905 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
34906 ** defined.
34908 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
34909 PgHdr *pDirty;
34910 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
34911 xIter(pDirty);
34914 #endif
34916 /************** End of pcache.c **********************************************/
34917 /************** Begin file pcache1.c *****************************************/
34919 ** 2008 November 05
34921 ** The author disclaims copyright to this source code. In place of
34922 ** a legal notice, here is a blessing:
34924 ** May you do good and not evil.
34925 ** May you find forgiveness for yourself and forgive others.
34926 ** May you share freely, never taking more than you give.
34928 *************************************************************************
34930 ** This file implements the default page cache implementation (the
34931 ** sqlite3_pcache interface). It also contains part of the implementation
34932 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
34933 ** If the default page cache implementation is overriden, then neither of
34934 ** these two features are available.
34938 typedef struct PCache1 PCache1;
34939 typedef struct PgHdr1 PgHdr1;
34940 typedef struct PgFreeslot PgFreeslot;
34941 typedef struct PGroup PGroup;
34943 /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
34944 ** of one or more PCaches that are able to recycle each others unpinned
34945 ** pages when they are under memory pressure. A PGroup is an instance of
34946 ** the following object.
34948 ** This page cache implementation works in one of two modes:
34950 ** (1) Every PCache is the sole member of its own PGroup. There is
34951 ** one PGroup per PCache.
34953 ** (2) There is a single global PGroup that all PCaches are a member
34954 ** of.
34956 ** Mode 1 uses more memory (since PCache instances are not able to rob
34957 ** unused pages from other PCaches) but it also operates without a mutex,
34958 ** and is therefore often faster. Mode 2 requires a mutex in order to be
34959 ** threadsafe, but is able recycle pages more efficient.
34961 ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
34962 ** PGroup which is the pcache1.grp global variable and its mutex is
34963 ** SQLITE_MUTEX_STATIC_LRU.
34965 struct PGroup {
34966 sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
34967 int nMaxPage; /* Sum of nMax for purgeable caches */
34968 int nMinPage; /* Sum of nMin for purgeable caches */
34969 int mxPinned; /* nMaxpage + 10 - nMinPage */
34970 int nCurrentPage; /* Number of purgeable pages allocated */
34971 PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
34974 /* Each page cache is an instance of the following object. Every
34975 ** open database file (including each in-memory database and each
34976 ** temporary or transient database) has a single page cache which
34977 ** is an instance of this object.
34979 ** Pointers to structures of this type are cast and returned as
34980 ** opaque sqlite3_pcache* handles.
34982 struct PCache1 {
34983 /* Cache configuration parameters. Page size (szPage) and the purgeable
34984 ** flag (bPurgeable) are set when the cache is created. nMax may be
34985 ** modified at any time by a call to the pcache1CacheSize() method.
34986 ** The PGroup mutex must be held when accessing nMax.
34988 PGroup *pGroup; /* PGroup this cache belongs to */
34989 int szPage; /* Size of allocated pages in bytes */
34990 int bPurgeable; /* True if cache is purgeable */
34991 unsigned int nMin; /* Minimum number of pages reserved */
34992 unsigned int nMax; /* Configured "cache_size" value */
34993 unsigned int n90pct; /* nMax*9/10 */
34995 /* Hash table of all pages. The following variables may only be accessed
34996 ** when the accessor is holding the PGroup mutex.
34998 unsigned int nRecyclable; /* Number of pages in the LRU list */
34999 unsigned int nPage; /* Total number of pages in apHash */
35000 unsigned int nHash; /* Number of slots in apHash[] */
35001 PgHdr1 **apHash; /* Hash table for fast lookup by key */
35003 unsigned int iMaxKey; /* Largest key seen since xTruncate() */
35007 ** Each cache entry is represented by an instance of the following
35008 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
35009 ** directly before this structure in memory (see the PGHDR1_TO_PAGE()
35010 ** macro below).
35012 struct PgHdr1 {
35013 unsigned int iKey; /* Key value (page number) */
35014 PgHdr1 *pNext; /* Next in hash table chain */
35015 PCache1 *pCache; /* Cache that currently owns this page */
35016 PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
35017 PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
35021 ** Free slots in the allocator used to divide up the buffer provided using
35022 ** the SQLITE_CONFIG_PAGECACHE mechanism.
35024 struct PgFreeslot {
35025 PgFreeslot *pNext; /* Next free slot */
35029 ** Global data used by this cache.
35031 static SQLITE_WSD struct PCacheGlobal {
35032 PGroup grp; /* The global PGroup for mode (2) */
35034 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
35035 ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
35036 ** fixed at sqlite3_initialize() time and do not require mutex protection.
35037 ** The nFreeSlot and pFree values do require mutex protection.
35039 int isInit; /* True if initialized */
35040 int szSlot; /* Size of each free slot */
35041 int nSlot; /* The number of pcache slots */
35042 int nReserve; /* Try to keep nFreeSlot above this */
35043 void *pStart, *pEnd; /* Bounds of pagecache malloc range */
35044 /* Above requires no mutex. Use mutex below for variable that follow. */
35045 sqlite3_mutex *mutex; /* Mutex for accessing the following: */
35046 int nFreeSlot; /* Number of unused pcache slots */
35047 PgFreeslot *pFree; /* Free page blocks */
35048 /* The following value requires a mutex to change. We skip the mutex on
35049 ** reading because (1) most platforms read a 32-bit integer atomically and
35050 ** (2) even if an incorrect value is read, no great harm is done since this
35051 ** is really just an optimization. */
35052 int bUnderPressure; /* True if low on PAGECACHE memory */
35053 } pcache1_g;
35056 ** All code in this file should access the global structure above via the
35057 ** alias "pcache1". This ensures that the WSD emulation is used when
35058 ** compiling for systems that do not support real WSD.
35060 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
35063 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
35064 ** bytes of data are located directly before it in memory (i.e. the total
35065 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
35066 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
35067 ** an argument and returns a pointer to the associated block of szPage
35068 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
35069 ** a pointer to a block of szPage bytes of data and the return value is
35070 ** a pointer to the associated PgHdr1 structure.
35072 ** assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
35074 #define PGHDR1_TO_PAGE(p) (void*)(((char*)p) - p->pCache->szPage)
35075 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
35078 ** Macros to enter and leave the PCache LRU mutex.
35080 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
35081 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
35083 /******************************************************************************/
35084 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
35087 ** This function is called during initialization if a static buffer is
35088 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
35089 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
35090 ** enough to contain 'n' buffers of 'sz' bytes each.
35092 ** This routine is called from sqlite3_initialize() and so it is guaranteed
35093 ** to be serialized already. There is no need for further mutexing.
35095 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
35096 if( pcache1.isInit ){
35097 PgFreeslot *p;
35098 sz = ROUNDDOWN8(sz);
35099 pcache1.szSlot = sz;
35100 pcache1.nSlot = pcache1.nFreeSlot = n;
35101 pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
35102 pcache1.pStart = pBuf;
35103 pcache1.pFree = 0;
35104 pcache1.bUnderPressure = 0;
35105 while( n-- ){
35106 p = (PgFreeslot*)pBuf;
35107 p->pNext = pcache1.pFree;
35108 pcache1.pFree = p;
35109 pBuf = (void*)&((char*)pBuf)[sz];
35111 pcache1.pEnd = pBuf;
35116 ** Malloc function used within this file to allocate space from the buffer
35117 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
35118 ** such buffer exists or there is no space left in it, this function falls
35119 ** back to sqlite3Malloc().
35121 ** Multiple threads can run this routine at the same time. Global variables
35122 ** in pcache1 need to be protected via mutex.
35124 static void *pcache1Alloc(int nByte){
35125 void *p = 0;
35126 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35127 sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
35128 if( nByte<=pcache1.szSlot ){
35129 sqlite3_mutex_enter(pcache1.mutex);
35130 p = (PgHdr1 *)pcache1.pFree;
35131 if( p ){
35132 pcache1.pFree = pcache1.pFree->pNext;
35133 pcache1.nFreeSlot--;
35134 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35135 assert( pcache1.nFreeSlot>=0 );
35136 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
35138 sqlite3_mutex_leave(pcache1.mutex);
35140 if( p==0 ){
35141 /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
35142 ** it from sqlite3Malloc instead.
35144 p = sqlite3Malloc(nByte);
35145 if( p ){
35146 int sz = sqlite3MallocSize(p);
35147 sqlite3_mutex_enter(pcache1.mutex);
35148 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
35149 sqlite3_mutex_leave(pcache1.mutex);
35151 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35153 return p;
35157 ** Free an allocated buffer obtained from pcache1Alloc().
35159 static void pcache1Free(void *p){
35160 if( p==0 ) return;
35161 if( p>=pcache1.pStart && p<pcache1.pEnd ){
35162 PgFreeslot *pSlot;
35163 sqlite3_mutex_enter(pcache1.mutex);
35164 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
35165 pSlot = (PgFreeslot*)p;
35166 pSlot->pNext = pcache1.pFree;
35167 pcache1.pFree = pSlot;
35168 pcache1.nFreeSlot++;
35169 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35170 assert( pcache1.nFreeSlot<=pcache1.nSlot );
35171 sqlite3_mutex_leave(pcache1.mutex);
35172 }else{
35173 int iSize;
35174 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35175 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35176 iSize = sqlite3MallocSize(p);
35177 sqlite3_mutex_enter(pcache1.mutex);
35178 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
35179 sqlite3_mutex_leave(pcache1.mutex);
35180 sqlite3_free(p);
35184 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35186 ** Return the size of a pcache allocation
35188 static int pcache1MemSize(void *p){
35189 if( p>=pcache1.pStart && p<pcache1.pEnd ){
35190 return pcache1.szSlot;
35191 }else{
35192 int iSize;
35193 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35194 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35195 iSize = sqlite3MallocSize(p);
35196 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35197 return iSize;
35200 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35203 ** Allocate a new page object initially associated with cache pCache.
35205 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
35206 int nByte = sizeof(PgHdr1) + pCache->szPage;
35207 void *pPg = pcache1Alloc(nByte);
35208 PgHdr1 *p;
35209 if( pPg ){
35210 p = PAGE_TO_PGHDR1(pCache, pPg);
35211 if( pCache->bPurgeable ){
35212 pCache->pGroup->nCurrentPage++;
35214 }else{
35215 p = 0;
35217 return p;
35221 ** Free a page object allocated by pcache1AllocPage().
35223 ** The pointer is allowed to be NULL, which is prudent. But it turns out
35224 ** that the current implementation happens to never call this routine
35225 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
35227 static void pcache1FreePage(PgHdr1 *p){
35228 if( ALWAYS(p) ){
35229 PCache1 *pCache = p->pCache;
35230 if( pCache->bPurgeable ){
35231 pCache->pGroup->nCurrentPage--;
35233 pcache1Free(PGHDR1_TO_PAGE(p));
35238 ** Malloc function used by SQLite to obtain space from the buffer configured
35239 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
35240 ** exists, this function falls back to sqlite3Malloc().
35242 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
35243 return pcache1Alloc(sz);
35247 ** Free an allocated buffer obtained from sqlite3PageMalloc().
35249 SQLITE_PRIVATE void sqlite3PageFree(void *p){
35250 pcache1Free(p);
35255 ** Return true if it desirable to avoid allocating a new page cache
35256 ** entry.
35258 ** If memory was allocated specifically to the page cache using
35259 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
35260 ** it is desirable to avoid allocating a new page cache entry because
35261 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
35262 ** for all page cache needs and we should not need to spill the
35263 ** allocation onto the heap.
35265 ** Or, the heap is used for all page cache memory put the heap is
35266 ** under memory pressure, then again it is desirable to avoid
35267 ** allocating a new page cache entry in order to avoid stressing
35268 ** the heap even further.
35270 static int pcache1UnderMemoryPressure(PCache1 *pCache){
35271 if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
35272 return pcache1.bUnderPressure;
35273 }else{
35274 return sqlite3HeapNearlyFull();
35278 /******************************************************************************/
35279 /******** General Implementation Functions ************************************/
35282 ** This function is used to resize the hash table used by the cache passed
35283 ** as the first argument.
35285 ** The PCache mutex must be held when this function is called.
35287 static int pcache1ResizeHash(PCache1 *p){
35288 PgHdr1 **apNew;
35289 unsigned int nNew;
35290 unsigned int i;
35292 assert( sqlite3_mutex_held(p->pGroup->mutex) );
35294 nNew = p->nHash*2;
35295 if( nNew<256 ){
35296 nNew = 256;
35299 pcache1LeaveMutex(p->pGroup);
35300 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
35301 apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
35302 if( p->nHash ){ sqlite3EndBenignMalloc(); }
35303 pcache1EnterMutex(p->pGroup);
35304 if( apNew ){
35305 memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
35306 for(i=0; i<p->nHash; i++){
35307 PgHdr1 *pPage;
35308 PgHdr1 *pNext = p->apHash[i];
35309 while( (pPage = pNext)!=0 ){
35310 unsigned int h = pPage->iKey % nNew;
35311 pNext = pPage->pNext;
35312 pPage->pNext = apNew[h];
35313 apNew[h] = pPage;
35316 sqlite3_free(p->apHash);
35317 p->apHash = apNew;
35318 p->nHash = nNew;
35321 return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
35325 ** This function is used internally to remove the page pPage from the
35326 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
35327 ** LRU list, then this function is a no-op.
35329 ** The PGroup mutex must be held when this function is called.
35331 ** If pPage is NULL then this routine is a no-op.
35333 static void pcache1PinPage(PgHdr1 *pPage){
35334 PCache1 *pCache;
35335 PGroup *pGroup;
35337 if( pPage==0 ) return;
35338 pCache = pPage->pCache;
35339 pGroup = pCache->pGroup;
35340 assert( sqlite3_mutex_held(pGroup->mutex) );
35341 if( pPage->pLruNext || pPage==pGroup->pLruTail ){
35342 if( pPage->pLruPrev ){
35343 pPage->pLruPrev->pLruNext = pPage->pLruNext;
35345 if( pPage->pLruNext ){
35346 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
35348 if( pGroup->pLruHead==pPage ){
35349 pGroup->pLruHead = pPage->pLruNext;
35351 if( pGroup->pLruTail==pPage ){
35352 pGroup->pLruTail = pPage->pLruPrev;
35354 pPage->pLruNext = 0;
35355 pPage->pLruPrev = 0;
35356 pPage->pCache->nRecyclable--;
35362 ** Remove the page supplied as an argument from the hash table
35363 ** (PCache1.apHash structure) that it is currently stored in.
35365 ** The PGroup mutex must be held when this function is called.
35367 static void pcache1RemoveFromHash(PgHdr1 *pPage){
35368 unsigned int h;
35369 PCache1 *pCache = pPage->pCache;
35370 PgHdr1 **pp;
35372 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35373 h = pPage->iKey % pCache->nHash;
35374 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
35375 *pp = (*pp)->pNext;
35377 pCache->nPage--;
35381 ** If there are currently more than nMaxPage pages allocated, try
35382 ** to recycle pages to reduce the number allocated to nMaxPage.
35384 static void pcache1EnforceMaxPage(PGroup *pGroup){
35385 assert( sqlite3_mutex_held(pGroup->mutex) );
35386 while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
35387 PgHdr1 *p = pGroup->pLruTail;
35388 assert( p->pCache->pGroup==pGroup );
35389 pcache1PinPage(p);
35390 pcache1RemoveFromHash(p);
35391 pcache1FreePage(p);
35396 ** Discard all pages from cache pCache with a page number (key value)
35397 ** greater than or equal to iLimit. Any pinned pages that meet this
35398 ** criteria are unpinned before they are discarded.
35400 ** The PCache mutex must be held when this function is called.
35402 static void pcache1TruncateUnsafe(
35403 PCache1 *pCache, /* The cache to truncate */
35404 unsigned int iLimit /* Drop pages with this pgno or larger */
35406 TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
35407 unsigned int h;
35408 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35409 for(h=0; h<pCache->nHash; h++){
35410 PgHdr1 **pp = &pCache->apHash[h];
35411 PgHdr1 *pPage;
35412 while( (pPage = *pp)!=0 ){
35413 if( pPage->iKey>=iLimit ){
35414 pCache->nPage--;
35415 *pp = pPage->pNext;
35416 pcache1PinPage(pPage);
35417 pcache1FreePage(pPage);
35418 }else{
35419 pp = &pPage->pNext;
35420 TESTONLY( nPage++; )
35424 assert( pCache->nPage==nPage );
35427 /******************************************************************************/
35428 /******** sqlite3_pcache Methods **********************************************/
35431 ** Implementation of the sqlite3_pcache.xInit method.
35433 static int pcache1Init(void *NotUsed){
35434 UNUSED_PARAMETER(NotUsed);
35435 assert( pcache1.isInit==0 );
35436 memset(&pcache1, 0, sizeof(pcache1));
35437 if( sqlite3GlobalConfig.bCoreMutex ){
35438 pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
35439 pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
35441 pcache1.grp.mxPinned = 10;
35442 pcache1.isInit = 1;
35443 return SQLITE_OK;
35447 ** Implementation of the sqlite3_pcache.xShutdown method.
35448 ** Note that the static mutex allocated in xInit does
35449 ** not need to be freed.
35451 static void pcache1Shutdown(void *NotUsed){
35452 UNUSED_PARAMETER(NotUsed);
35453 assert( pcache1.isInit!=0 );
35454 memset(&pcache1, 0, sizeof(pcache1));
35458 ** Implementation of the sqlite3_pcache.xCreate method.
35460 ** Allocate a new cache.
35462 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
35463 PCache1 *pCache; /* The newly created page cache */
35464 PGroup *pGroup; /* The group the new page cache will belong to */
35465 int sz; /* Bytes of memory required to allocate the new cache */
35468 ** The seperateCache variable is true if each PCache has its own private
35469 ** PGroup. In other words, separateCache is true for mode (1) where no
35470 ** mutexing is required.
35472 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
35474 ** * Always use a unified cache in single-threaded applications
35476 ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
35477 ** use separate caches (mode-1)
35479 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
35480 const int separateCache = 0;
35481 #else
35482 int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
35483 #endif
35485 sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
35486 pCache = (PCache1 *)sqlite3_malloc(sz);
35487 if( pCache ){
35488 memset(pCache, 0, sz);
35489 if( separateCache ){
35490 pGroup = (PGroup*)&pCache[1];
35491 pGroup->mxPinned = 10;
35492 }else{
35493 pGroup = &pcache1_g.grp;
35495 pCache->pGroup = pGroup;
35496 pCache->szPage = szPage;
35497 pCache->bPurgeable = (bPurgeable ? 1 : 0);
35498 if( bPurgeable ){
35499 pCache->nMin = 10;
35500 pcache1EnterMutex(pGroup);
35501 pGroup->nMinPage += pCache->nMin;
35502 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35503 pcache1LeaveMutex(pGroup);
35506 return (sqlite3_pcache *)pCache;
35510 ** Implementation of the sqlite3_pcache.xCachesize method.
35512 ** Configure the cache_size limit for a cache.
35514 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
35515 PCache1 *pCache = (PCache1 *)p;
35516 if( pCache->bPurgeable ){
35517 PGroup *pGroup = pCache->pGroup;
35518 pcache1EnterMutex(pGroup);
35519 pGroup->nMaxPage += (nMax - pCache->nMax);
35520 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35521 pCache->nMax = nMax;
35522 pCache->n90pct = pCache->nMax*9/10;
35523 pcache1EnforceMaxPage(pGroup);
35524 pcache1LeaveMutex(pGroup);
35529 ** Implementation of the sqlite3_pcache.xPagecount method.
35531 static int pcache1Pagecount(sqlite3_pcache *p){
35532 int n;
35533 PCache1 *pCache = (PCache1*)p;
35534 pcache1EnterMutex(pCache->pGroup);
35535 n = pCache->nPage;
35536 pcache1LeaveMutex(pCache->pGroup);
35537 return n;
35541 ** Implementation of the sqlite3_pcache.xFetch method.
35543 ** Fetch a page by key value.
35545 ** Whether or not a new page may be allocated by this function depends on
35546 ** the value of the createFlag argument. 0 means do not allocate a new
35547 ** page. 1 means allocate a new page if space is easily available. 2
35548 ** means to try really hard to allocate a new page.
35550 ** For a non-purgeable cache (a cache used as the storage for an in-memory
35551 ** database) there is really no difference between createFlag 1 and 2. So
35552 ** the calling function (pcache.c) will never have a createFlag of 1 on
35553 ** a non-purgable cache.
35555 ** There are three different approaches to obtaining space for a page,
35556 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
35558 ** 1. Regardless of the value of createFlag, the cache is searched for a
35559 ** copy of the requested page. If one is found, it is returned.
35561 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
35562 ** returned.
35564 ** 3. If createFlag is 1, and the page is not already in the cache, then
35565 ** return NULL (do not allocate a new page) if any of the following
35566 ** conditions are true:
35568 ** (a) the number of pages pinned by the cache is greater than
35569 ** PCache1.nMax, or
35571 ** (b) the number of pages pinned by the cache is greater than
35572 ** the sum of nMax for all purgeable caches, less the sum of
35573 ** nMin for all other purgeable caches, or
35575 ** 4. If none of the first three conditions apply and the cache is marked
35576 ** as purgeable, and if one of the following is true:
35578 ** (a) The number of pages allocated for the cache is already
35579 ** PCache1.nMax, or
35581 ** (b) The number of pages allocated for all purgeable caches is
35582 ** already equal to or greater than the sum of nMax for all
35583 ** purgeable caches,
35585 ** (c) The system is under memory pressure and wants to avoid
35586 ** unnecessary pages cache entry allocations
35588 ** then attempt to recycle a page from the LRU list. If it is the right
35589 ** size, return the recycled buffer. Otherwise, free the buffer and
35590 ** proceed to step 5.
35592 ** 5. Otherwise, allocate and return a new page buffer.
35594 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
35595 int nPinned;
35596 PCache1 *pCache = (PCache1 *)p;
35597 PGroup *pGroup;
35598 PgHdr1 *pPage = 0;
35600 assert( pCache->bPurgeable || createFlag!=1 );
35601 assert( pCache->bPurgeable || pCache->nMin==0 );
35602 assert( pCache->bPurgeable==0 || pCache->nMin==10 );
35603 assert( pCache->nMin==0 || pCache->bPurgeable );
35604 pcache1EnterMutex(pGroup = pCache->pGroup);
35606 /* Step 1: Search the hash table for an existing entry. */
35607 if( pCache->nHash>0 ){
35608 unsigned int h = iKey % pCache->nHash;
35609 for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
35612 /* Step 2: Abort if no existing page is found and createFlag is 0 */
35613 if( pPage || createFlag==0 ){
35614 pcache1PinPage(pPage);
35615 goto fetch_out;
35618 /* The pGroup local variable will normally be initialized by the
35619 ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
35620 ** then pcache1EnterMutex() is a no-op, so we have to initialize the
35621 ** local variable here. Delaying the initialization of pGroup is an
35622 ** optimization: The common case is to exit the module before reaching
35623 ** this point.
35625 #ifdef SQLITE_MUTEX_OMIT
35626 pGroup = pCache->pGroup;
35627 #endif
35630 /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
35631 nPinned = pCache->nPage - pCache->nRecyclable;
35632 assert( nPinned>=0 );
35633 assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
35634 assert( pCache->n90pct == pCache->nMax*9/10 );
35635 if( createFlag==1 && (
35636 nPinned>=pGroup->mxPinned
35637 || nPinned>=(int)pCache->n90pct
35638 || pcache1UnderMemoryPressure(pCache)
35640 goto fetch_out;
35643 if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
35644 goto fetch_out;
35647 /* Step 4. Try to recycle a page. */
35648 if( pCache->bPurgeable && pGroup->pLruTail && (
35649 (pCache->nPage+1>=pCache->nMax)
35650 || pGroup->nCurrentPage>=pGroup->nMaxPage
35651 || pcache1UnderMemoryPressure(pCache)
35653 PCache1 *pOtherCache;
35654 pPage = pGroup->pLruTail;
35655 pcache1RemoveFromHash(pPage);
35656 pcache1PinPage(pPage);
35657 if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
35658 pcache1FreePage(pPage);
35659 pPage = 0;
35660 }else{
35661 pGroup->nCurrentPage -=
35662 (pOtherCache->bPurgeable - pCache->bPurgeable);
35666 /* Step 5. If a usable page buffer has still not been found,
35667 ** attempt to allocate a new one.
35669 if( !pPage ){
35670 if( createFlag==1 ) sqlite3BeginBenignMalloc();
35671 pcache1LeaveMutex(pGroup);
35672 pPage = pcache1AllocPage(pCache);
35673 pcache1EnterMutex(pGroup);
35674 if( createFlag==1 ) sqlite3EndBenignMalloc();
35677 if( pPage ){
35678 unsigned int h = iKey % pCache->nHash;
35679 pCache->nPage++;
35680 pPage->iKey = iKey;
35681 pPage->pNext = pCache->apHash[h];
35682 pPage->pCache = pCache;
35683 pPage->pLruPrev = 0;
35684 pPage->pLruNext = 0;
35685 *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
35686 pCache->apHash[h] = pPage;
35689 fetch_out:
35690 if( pPage && iKey>pCache->iMaxKey ){
35691 pCache->iMaxKey = iKey;
35693 pcache1LeaveMutex(pGroup);
35694 return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
35699 ** Implementation of the sqlite3_pcache.xUnpin method.
35701 ** Mark a page as unpinned (eligible for asynchronous recycling).
35703 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
35704 PCache1 *pCache = (PCache1 *)p;
35705 PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
35706 PGroup *pGroup = pCache->pGroup;
35708 assert( pPage->pCache==pCache );
35709 pcache1EnterMutex(pGroup);
35711 /* It is an error to call this function if the page is already
35712 ** part of the PGroup LRU list.
35714 assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
35715 assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
35717 if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
35718 pcache1RemoveFromHash(pPage);
35719 pcache1FreePage(pPage);
35720 }else{
35721 /* Add the page to the PGroup LRU list. */
35722 if( pGroup->pLruHead ){
35723 pGroup->pLruHead->pLruPrev = pPage;
35724 pPage->pLruNext = pGroup->pLruHead;
35725 pGroup->pLruHead = pPage;
35726 }else{
35727 pGroup->pLruTail = pPage;
35728 pGroup->pLruHead = pPage;
35730 pCache->nRecyclable++;
35733 pcache1LeaveMutex(pCache->pGroup);
35737 ** Implementation of the sqlite3_pcache.xRekey method.
35739 static void pcache1Rekey(
35740 sqlite3_pcache *p,
35741 void *pPg,
35742 unsigned int iOld,
35743 unsigned int iNew
35745 PCache1 *pCache = (PCache1 *)p;
35746 PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
35747 PgHdr1 **pp;
35748 unsigned int h;
35749 assert( pPage->iKey==iOld );
35750 assert( pPage->pCache==pCache );
35752 pcache1EnterMutex(pCache->pGroup);
35754 h = iOld%pCache->nHash;
35755 pp = &pCache->apHash[h];
35756 while( (*pp)!=pPage ){
35757 pp = &(*pp)->pNext;
35759 *pp = pPage->pNext;
35761 h = iNew%pCache->nHash;
35762 pPage->iKey = iNew;
35763 pPage->pNext = pCache->apHash[h];
35764 pCache->apHash[h] = pPage;
35765 if( iNew>pCache->iMaxKey ){
35766 pCache->iMaxKey = iNew;
35769 pcache1LeaveMutex(pCache->pGroup);
35773 ** Implementation of the sqlite3_pcache.xTruncate method.
35775 ** Discard all unpinned pages in the cache with a page number equal to
35776 ** or greater than parameter iLimit. Any pinned pages with a page number
35777 ** equal to or greater than iLimit are implicitly unpinned.
35779 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
35780 PCache1 *pCache = (PCache1 *)p;
35781 pcache1EnterMutex(pCache->pGroup);
35782 if( iLimit<=pCache->iMaxKey ){
35783 pcache1TruncateUnsafe(pCache, iLimit);
35784 pCache->iMaxKey = iLimit-1;
35786 pcache1LeaveMutex(pCache->pGroup);
35790 ** Implementation of the sqlite3_pcache.xDestroy method.
35792 ** Destroy a cache allocated using pcache1Create().
35794 static void pcache1Destroy(sqlite3_pcache *p){
35795 PCache1 *pCache = (PCache1 *)p;
35796 PGroup *pGroup = pCache->pGroup;
35797 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
35798 pcache1EnterMutex(pGroup);
35799 pcache1TruncateUnsafe(pCache, 0);
35800 pGroup->nMaxPage -= pCache->nMax;
35801 pGroup->nMinPage -= pCache->nMin;
35802 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35803 pcache1EnforceMaxPage(pGroup);
35804 pcache1LeaveMutex(pGroup);
35805 sqlite3_free(pCache->apHash);
35806 sqlite3_free(pCache);
35810 ** This function is called during initialization (sqlite3_initialize()) to
35811 ** install the default pluggable cache module, assuming the user has not
35812 ** already provided an alternative.
35814 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
35815 static const sqlite3_pcache_methods defaultMethods = {
35816 0, /* pArg */
35817 pcache1Init, /* xInit */
35818 pcache1Shutdown, /* xShutdown */
35819 pcache1Create, /* xCreate */
35820 pcache1Cachesize, /* xCachesize */
35821 pcache1Pagecount, /* xPagecount */
35822 pcache1Fetch, /* xFetch */
35823 pcache1Unpin, /* xUnpin */
35824 pcache1Rekey, /* xRekey */
35825 pcache1Truncate, /* xTruncate */
35826 pcache1Destroy /* xDestroy */
35828 sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
35831 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35833 ** This function is called to free superfluous dynamically allocated memory
35834 ** held by the pager system. Memory in use by any SQLite pager allocated
35835 ** by the current thread may be sqlite3_free()ed.
35837 ** nReq is the number of bytes of memory required. Once this much has
35838 ** been released, the function returns. The return value is the total number
35839 ** of bytes of memory released.
35841 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
35842 int nFree = 0;
35843 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35844 assert( sqlite3_mutex_notheld(pcache1.mutex) );
35845 if( pcache1.pStart==0 ){
35846 PgHdr1 *p;
35847 pcache1EnterMutex(&pcache1.grp);
35848 while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
35849 nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
35850 pcache1PinPage(p);
35851 pcache1RemoveFromHash(p);
35852 pcache1FreePage(p);
35854 pcache1LeaveMutex(&pcache1.grp);
35856 return nFree;
35858 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35860 #ifdef SQLITE_TEST
35862 ** This function is used by test procedures to inspect the internal state
35863 ** of the global cache.
35865 SQLITE_PRIVATE void sqlite3PcacheStats(
35866 int *pnCurrent, /* OUT: Total number of pages cached */
35867 int *pnMax, /* OUT: Global maximum cache size */
35868 int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
35869 int *pnRecyclable /* OUT: Total number of pages available for recycling */
35871 PgHdr1 *p;
35872 int nRecyclable = 0;
35873 for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
35874 nRecyclable++;
35876 *pnCurrent = pcache1.grp.nCurrentPage;
35877 *pnMax = pcache1.grp.nMaxPage;
35878 *pnMin = pcache1.grp.nMinPage;
35879 *pnRecyclable = nRecyclable;
35881 #endif
35883 /************** End of pcache1.c *********************************************/
35884 /************** Begin file rowset.c ******************************************/
35886 ** 2008 December 3
35888 ** The author disclaims copyright to this source code. In place of
35889 ** a legal notice, here is a blessing:
35891 ** May you do good and not evil.
35892 ** May you find forgiveness for yourself and forgive others.
35893 ** May you share freely, never taking more than you give.
35895 *************************************************************************
35897 ** This module implements an object we call a "RowSet".
35899 ** The RowSet object is a collection of rowids. Rowids
35900 ** are inserted into the RowSet in an arbitrary order. Inserts
35901 ** can be intermixed with tests to see if a given rowid has been
35902 ** previously inserted into the RowSet.
35904 ** After all inserts are finished, it is possible to extract the
35905 ** elements of the RowSet in sorted order. Once this extraction
35906 ** process has started, no new elements may be inserted.
35908 ** Hence, the primitive operations for a RowSet are:
35910 ** CREATE
35911 ** INSERT
35912 ** TEST
35913 ** SMALLEST
35914 ** DESTROY
35916 ** The CREATE and DESTROY primitives are the constructor and destructor,
35917 ** obviously. The INSERT primitive adds a new element to the RowSet.
35918 ** TEST checks to see if an element is already in the RowSet. SMALLEST
35919 ** extracts the least value from the RowSet.
35921 ** The INSERT primitive might allocate additional memory. Memory is
35922 ** allocated in chunks so most INSERTs do no allocation. There is an
35923 ** upper bound on the size of allocated memory. No memory is freed
35924 ** until DESTROY.
35926 ** The TEST primitive includes a "batch" number. The TEST primitive
35927 ** will only see elements that were inserted before the last change
35928 ** in the batch number. In other words, if an INSERT occurs between
35929 ** two TESTs where the TESTs have the same batch nubmer, then the
35930 ** value added by the INSERT will not be visible to the second TEST.
35931 ** The initial batch number is zero, so if the very first TEST contains
35932 ** a non-zero batch number, it will see all prior INSERTs.
35934 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
35935 ** that is attempted.
35937 ** The cost of an INSERT is roughly constant. (Sometime new memory
35938 ** has to be allocated on an INSERT.) The cost of a TEST with a new
35939 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
35940 ** The cost of a TEST using the same batch number is O(logN). The cost
35941 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
35942 ** primitives are constant time. The cost of DESTROY is O(N).
35944 ** There is an added cost of O(N) when switching between TEST and
35945 ** SMALLEST primitives.
35950 ** Target size for allocation chunks.
35952 #define ROWSET_ALLOCATION_SIZE 1024
35955 ** The number of rowset entries per allocation chunk.
35957 #define ROWSET_ENTRY_PER_CHUNK \
35958 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
35961 ** Each entry in a RowSet is an instance of the following object.
35963 struct RowSetEntry {
35964 i64 v; /* ROWID value for this entry */
35965 struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
35966 struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
35970 ** RowSetEntry objects are allocated in large chunks (instances of the
35971 ** following structure) to reduce memory allocation overhead. The
35972 ** chunks are kept on a linked list so that they can be deallocated
35973 ** when the RowSet is destroyed.
35975 struct RowSetChunk {
35976 struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
35977 struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
35981 ** A RowSet in an instance of the following structure.
35983 ** A typedef of this structure if found in sqliteInt.h.
35985 struct RowSet {
35986 struct RowSetChunk *pChunk; /* List of all chunk allocations */
35987 sqlite3 *db; /* The database connection */
35988 struct RowSetEntry *pEntry; /* List of entries using pRight */
35989 struct RowSetEntry *pLast; /* Last entry on the pEntry list */
35990 struct RowSetEntry *pFresh; /* Source of new entry objects */
35991 struct RowSetEntry *pTree; /* Binary tree of entries */
35992 u16 nFresh; /* Number of objects on pFresh */
35993 u8 isSorted; /* True if pEntry is sorted */
35994 u8 iBatch; /* Current insert batch */
35998 ** Turn bulk memory into a RowSet object. N bytes of memory
35999 ** are available at pSpace. The db pointer is used as a memory context
36000 ** for any subsequent allocations that need to occur.
36001 ** Return a pointer to the new RowSet object.
36003 ** It must be the case that N is sufficient to make a Rowset. If not
36004 ** an assertion fault occurs.
36006 ** If N is larger than the minimum, use the surplus as an initial
36007 ** allocation of entries available to be filled.
36009 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
36010 RowSet *p;
36011 assert( N >= ROUND8(sizeof(*p)) );
36012 p = pSpace;
36013 p->pChunk = 0;
36014 p->db = db;
36015 p->pEntry = 0;
36016 p->pLast = 0;
36017 p->pTree = 0;
36018 p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
36019 p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
36020 p->isSorted = 1;
36021 p->iBatch = 0;
36022 return p;
36026 ** Deallocate all chunks from a RowSet. This frees all memory that
36027 ** the RowSet has allocated over its lifetime. This routine is
36028 ** the destructor for the RowSet.
36030 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
36031 struct RowSetChunk *pChunk, *pNextChunk;
36032 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
36033 pNextChunk = pChunk->pNextChunk;
36034 sqlite3DbFree(p->db, pChunk);
36036 p->pChunk = 0;
36037 p->nFresh = 0;
36038 p->pEntry = 0;
36039 p->pLast = 0;
36040 p->pTree = 0;
36041 p->isSorted = 1;
36045 ** Insert a new value into a RowSet.
36047 ** The mallocFailed flag of the database connection is set if a
36048 ** memory allocation fails.
36050 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
36051 struct RowSetEntry *pEntry; /* The new entry */
36052 struct RowSetEntry *pLast; /* The last prior entry */
36053 assert( p!=0 );
36054 if( p->nFresh==0 ){
36055 struct RowSetChunk *pNew;
36056 pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
36057 if( pNew==0 ){
36058 return;
36060 pNew->pNextChunk = p->pChunk;
36061 p->pChunk = pNew;
36062 p->pFresh = pNew->aEntry;
36063 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
36065 pEntry = p->pFresh++;
36066 p->nFresh--;
36067 pEntry->v = rowid;
36068 pEntry->pRight = 0;
36069 pLast = p->pLast;
36070 if( pLast ){
36071 if( p->isSorted && rowid<=pLast->v ){
36072 p->isSorted = 0;
36074 pLast->pRight = pEntry;
36075 }else{
36076 assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
36077 p->pEntry = pEntry;
36079 p->pLast = pEntry;
36083 ** Merge two lists of RowSetEntry objects. Remove duplicates.
36085 ** The input lists are connected via pRight pointers and are
36086 ** assumed to each already be in sorted order.
36088 static struct RowSetEntry *rowSetMerge(
36089 struct RowSetEntry *pA, /* First sorted list to be merged */
36090 struct RowSetEntry *pB /* Second sorted list to be merged */
36092 struct RowSetEntry head;
36093 struct RowSetEntry *pTail;
36095 pTail = &head;
36096 while( pA && pB ){
36097 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36098 assert( pB->pRight==0 || pB->v<=pB->pRight->v );
36099 if( pA->v<pB->v ){
36100 pTail->pRight = pA;
36101 pA = pA->pRight;
36102 pTail = pTail->pRight;
36103 }else if( pB->v<pA->v ){
36104 pTail->pRight = pB;
36105 pB = pB->pRight;
36106 pTail = pTail->pRight;
36107 }else{
36108 pA = pA->pRight;
36111 if( pA ){
36112 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36113 pTail->pRight = pA;
36114 }else{
36115 assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
36116 pTail->pRight = pB;
36118 return head.pRight;
36122 ** Sort all elements on the pEntry list of the RowSet into ascending order.
36124 static void rowSetSort(RowSet *p){
36125 unsigned int i;
36126 struct RowSetEntry *pEntry;
36127 struct RowSetEntry *aBucket[40];
36129 assert( p->isSorted==0 );
36130 memset(aBucket, 0, sizeof(aBucket));
36131 while( p->pEntry ){
36132 pEntry = p->pEntry;
36133 p->pEntry = pEntry->pRight;
36134 pEntry->pRight = 0;
36135 for(i=0; aBucket[i]; i++){
36136 pEntry = rowSetMerge(aBucket[i], pEntry);
36137 aBucket[i] = 0;
36139 aBucket[i] = pEntry;
36141 pEntry = 0;
36142 for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
36143 pEntry = rowSetMerge(pEntry, aBucket[i]);
36145 p->pEntry = pEntry;
36146 p->pLast = 0;
36147 p->isSorted = 1;
36152 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
36153 ** Convert this tree into a linked list connected by the pRight pointers
36154 ** and return pointers to the first and last elements of the new list.
36156 static void rowSetTreeToList(
36157 struct RowSetEntry *pIn, /* Root of the input tree */
36158 struct RowSetEntry **ppFirst, /* Write head of the output list here */
36159 struct RowSetEntry **ppLast /* Write tail of the output list here */
36161 assert( pIn!=0 );
36162 if( pIn->pLeft ){
36163 struct RowSetEntry *p;
36164 rowSetTreeToList(pIn->pLeft, ppFirst, &p);
36165 p->pRight = pIn;
36166 }else{
36167 *ppFirst = pIn;
36169 if( pIn->pRight ){
36170 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
36171 }else{
36172 *ppLast = pIn;
36174 assert( (*ppLast)->pRight==0 );
36179 ** Convert a sorted list of elements (connected by pRight) into a binary
36180 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
36181 ** node taken from the head of *ppList. A depth of 2 means a tree with
36182 ** three nodes. And so forth.
36184 ** Use as many entries from the input list as required and update the
36185 ** *ppList to point to the unused elements of the list. If the input
36186 ** list contains too few elements, then construct an incomplete tree
36187 ** and leave *ppList set to NULL.
36189 ** Return a pointer to the root of the constructed binary tree.
36191 static struct RowSetEntry *rowSetNDeepTree(
36192 struct RowSetEntry **ppList,
36193 int iDepth
36195 struct RowSetEntry *p; /* Root of the new tree */
36196 struct RowSetEntry *pLeft; /* Left subtree */
36197 if( *ppList==0 ){
36198 return 0;
36200 if( iDepth==1 ){
36201 p = *ppList;
36202 *ppList = p->pRight;
36203 p->pLeft = p->pRight = 0;
36204 return p;
36206 pLeft = rowSetNDeepTree(ppList, iDepth-1);
36207 p = *ppList;
36208 if( p==0 ){
36209 return pLeft;
36211 p->pLeft = pLeft;
36212 *ppList = p->pRight;
36213 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
36214 return p;
36218 ** Convert a sorted list of elements into a binary tree. Make the tree
36219 ** as deep as it needs to be in order to contain the entire list.
36221 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
36222 int iDepth; /* Depth of the tree so far */
36223 struct RowSetEntry *p; /* Current tree root */
36224 struct RowSetEntry *pLeft; /* Left subtree */
36226 assert( pList!=0 );
36227 p = pList;
36228 pList = p->pRight;
36229 p->pLeft = p->pRight = 0;
36230 for(iDepth=1; pList; iDepth++){
36231 pLeft = p;
36232 p = pList;
36233 pList = p->pRight;
36234 p->pLeft = pLeft;
36235 p->pRight = rowSetNDeepTree(&pList, iDepth);
36237 return p;
36241 ** Convert the list in p->pEntry into a sorted list if it is not
36242 ** sorted already. If there is a binary tree on p->pTree, then
36243 ** convert it into a list too and merge it into the p->pEntry list.
36245 static void rowSetToList(RowSet *p){
36246 if( !p->isSorted ){
36247 rowSetSort(p);
36249 if( p->pTree ){
36250 struct RowSetEntry *pHead, *pTail;
36251 rowSetTreeToList(p->pTree, &pHead, &pTail);
36252 p->pTree = 0;
36253 p->pEntry = rowSetMerge(p->pEntry, pHead);
36258 ** Extract the smallest element from the RowSet.
36259 ** Write the element into *pRowid. Return 1 on success. Return
36260 ** 0 if the RowSet is already empty.
36262 ** After this routine has been called, the sqlite3RowSetInsert()
36263 ** routine may not be called again.
36265 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
36266 rowSetToList(p);
36267 if( p->pEntry ){
36268 *pRowid = p->pEntry->v;
36269 p->pEntry = p->pEntry->pRight;
36270 if( p->pEntry==0 ){
36271 sqlite3RowSetClear(p);
36273 return 1;
36274 }else{
36275 return 0;
36280 ** Check to see if element iRowid was inserted into the the rowset as
36281 ** part of any insert batch prior to iBatch. Return 1 or 0.
36283 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
36284 struct RowSetEntry *p;
36285 if( iBatch!=pRowSet->iBatch ){
36286 if( pRowSet->pEntry ){
36287 rowSetToList(pRowSet);
36288 pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
36289 pRowSet->pEntry = 0;
36290 pRowSet->pLast = 0;
36292 pRowSet->iBatch = iBatch;
36294 p = pRowSet->pTree;
36295 while( p ){
36296 if( p->v<iRowid ){
36297 p = p->pRight;
36298 }else if( p->v>iRowid ){
36299 p = p->pLeft;
36300 }else{
36301 return 1;
36304 return 0;
36307 /************** End of rowset.c **********************************************/
36308 /************** Begin file pager.c *******************************************/
36310 ** 2001 September 15
36312 ** The author disclaims copyright to this source code. In place of
36313 ** a legal notice, here is a blessing:
36315 ** May you do good and not evil.
36316 ** May you find forgiveness for yourself and forgive others.
36317 ** May you share freely, never taking more than you give.
36319 *************************************************************************
36320 ** This is the implementation of the page cache subsystem or "pager".
36322 ** The pager is used to access a database disk file. It implements
36323 ** atomic commit and rollback through the use of a journal file that
36324 ** is separate from the database file. The pager also implements file
36325 ** locking to prevent two processes from writing the same database
36326 ** file simultaneously, or one process from reading the database while
36327 ** another is writing.
36329 #ifndef SQLITE_OMIT_DISKIO
36330 /************** Include wal.h in the middle of pager.c ***********************/
36331 /************** Begin file wal.h *********************************************/
36333 ** 2010 February 1
36335 ** The author disclaims copyright to this source code. In place of
36336 ** a legal notice, here is a blessing:
36338 ** May you do good and not evil.
36339 ** May you find forgiveness for yourself and forgive others.
36340 ** May you share freely, never taking more than you give.
36342 *************************************************************************
36343 ** This header file defines the interface to the write-ahead logging
36344 ** system. Refer to the comments below and the header comment attached to
36345 ** the implementation of each function in log.c for further details.
36348 #ifndef _WAL_H_
36349 #define _WAL_H_
36352 #ifdef SQLITE_OMIT_WAL
36353 # define sqlite3WalOpen(x,y,z) 0
36354 # define sqlite3WalClose(w,x,y,z) 0
36355 # define sqlite3WalBeginReadTransaction(y,z) 0
36356 # define sqlite3WalEndReadTransaction(z)
36357 # define sqlite3WalRead(v,w,x,y,z) 0
36358 # define sqlite3WalDbsize(y) 0
36359 # define sqlite3WalBeginWriteTransaction(y) 0
36360 # define sqlite3WalEndWriteTransaction(x) 0
36361 # define sqlite3WalUndo(x,y,z) 0
36362 # define sqlite3WalSavepoint(y,z)
36363 # define sqlite3WalSavepointUndo(y,z) 0
36364 # define sqlite3WalFrames(u,v,w,x,y,z) 0
36365 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
36366 # define sqlite3WalCallback(z) 0
36367 # define sqlite3WalExclusiveMode(y,z) 0
36368 # define sqlite3WalHeapMemory(z) 0
36369 #else
36371 #define WAL_SAVEPOINT_NDATA 4
36373 /* Connection to a write-ahead log (WAL) file.
36374 ** There is one object of this type for each pager.
36376 typedef struct Wal Wal;
36378 /* Open and close a connection to a write-ahead log. */
36379 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, int, Wal**);
36380 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
36382 /* Used by readers to open (lock) and close (unlock) a snapshot. A
36383 ** snapshot is like a read-transaction. It is the state of the database
36384 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
36385 ** preserves the current state even if the other threads or processes
36386 ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
36387 ** transaction and releases the lock.
36389 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
36390 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
36392 /* Read a page from the write-ahead log, if it is present. */
36393 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
36395 /* If the WAL is not empty, return the size of the database. */
36396 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
36398 /* Obtain or release the WRITER lock. */
36399 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
36400 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
36402 /* Undo any frames written (but not committed) to the log */
36403 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
36405 /* Return an integer that records the current (uncommitted) write
36406 ** position in the WAL */
36407 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
36409 /* Move the write position of the WAL back to iFrame. Called in
36410 ** response to a ROLLBACK TO command. */
36411 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
36413 /* Write a frame or frames to the log. */
36414 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
36416 /* Copy pages from the log to the database file */
36417 SQLITE_PRIVATE int sqlite3WalCheckpoint(
36418 Wal *pWal, /* Write-ahead log connection */
36419 int eMode, /* One of PASSIVE, FULL and RESTART */
36420 int (*xBusy)(void*), /* Function to call when busy */
36421 void *pBusyArg, /* Context argument for xBusyHandler */
36422 int sync_flags, /* Flags to sync db file with (or 0) */
36423 int nBuf, /* Size of buffer nBuf */
36424 u8 *zBuf, /* Temporary buffer to use */
36425 int *pnLog, /* OUT: Number of frames in WAL */
36426 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
36429 /* Return the value to pass to a sqlite3_wal_hook callback, the
36430 ** number of frames in the WAL at the point of the last commit since
36431 ** sqlite3WalCallback() was called. If no commits have occurred since
36432 ** the last call, then return 0.
36434 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
36436 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
36437 ** by the pager layer on the database file.
36439 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
36441 /* Return true if the argument is non-NULL and the WAL module is using
36442 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
36443 ** WAL module is using shared-memory, return false.
36445 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
36447 #endif /* ifndef SQLITE_OMIT_WAL */
36448 #endif /* _WAL_H_ */
36450 /************** End of wal.h *************************************************/
36451 /************** Continuing where we left off in pager.c **********************/
36454 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
36456 ** This comment block describes invariants that hold when using a rollback
36457 ** journal. These invariants do not apply for journal_mode=WAL,
36458 ** journal_mode=MEMORY, or journal_mode=OFF.
36460 ** Within this comment block, a page is deemed to have been synced
36461 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
36462 ** Otherwise, the page is not synced until the xSync method of the VFS
36463 ** is called successfully on the file containing the page.
36465 ** Definition: A page of the database file is said to be "overwriteable" if
36466 ** one or more of the following are true about the page:
36468 ** (a) The original content of the page as it was at the beginning of
36469 ** the transaction has been written into the rollback journal and
36470 ** synced.
36472 ** (b) The page was a freelist leaf page at the start of the transaction.
36474 ** (c) The page number is greater than the largest page that existed in
36475 ** the database file at the start of the transaction.
36477 ** (1) A page of the database file is never overwritten unless one of the
36478 ** following are true:
36480 ** (a) The page and all other pages on the same sector are overwriteable.
36482 ** (b) The atomic page write optimization is enabled, and the entire
36483 ** transaction other than the update of the transaction sequence
36484 ** number consists of a single page change.
36486 ** (2) The content of a page written into the rollback journal exactly matches
36487 ** both the content in the database when the rollback journal was written
36488 ** and the content in the database at the beginning of the current
36489 ** transaction.
36491 ** (3) Writes to the database file are an integer multiple of the page size
36492 ** in length and are aligned on a page boundary.
36494 ** (4) Reads from the database file are either aligned on a page boundary and
36495 ** an integer multiple of the page size in length or are taken from the
36496 ** first 100 bytes of the database file.
36498 ** (5) All writes to the database file are synced prior to the rollback journal
36499 ** being deleted, truncated, or zeroed.
36501 ** (6) If a master journal file is used, then all writes to the database file
36502 ** are synced prior to the master journal being deleted.
36504 ** Definition: Two databases (or the same database at two points it time)
36505 ** are said to be "logically equivalent" if they give the same answer to
36506 ** all queries. Note in particular the the content of freelist leaf
36507 ** pages can be changed arbitarily without effecting the logical equivalence
36508 ** of the database.
36510 ** (7) At any time, if any subset, including the empty set and the total set,
36511 ** of the unsynced changes to a rollback journal are removed and the
36512 ** journal is rolled back, the resulting database file will be logical
36513 ** equivalent to the database file at the beginning of the transaction.
36515 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
36516 ** is called to restore the database file to the same size it was at
36517 ** the beginning of the transaction. (In some VFSes, the xTruncate
36518 ** method is a no-op, but that does not change the fact the SQLite will
36519 ** invoke it.)
36521 ** (9) Whenever the database file is modified, at least one bit in the range
36522 ** of bytes from 24 through 39 inclusive will be changed prior to releasing
36523 ** the EXCLUSIVE lock, thus signaling other connections on the same
36524 ** database to flush their caches.
36526 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
36527 ** than one billion transactions.
36529 ** (11) A database file is well-formed at the beginning and at the conclusion
36530 ** of every transaction.
36532 ** (12) An EXCLUSIVE lock is held on the database file when writing to
36533 ** the database file.
36535 ** (13) A SHARED lock is held on the database file while reading any
36536 ** content out of the database file.
36538 ******************************************************************************/
36541 ** Macros for troubleshooting. Normally turned off
36543 #if 0
36544 int sqlite3PagerTrace=1; /* True to enable tracing */
36545 #define sqlite3DebugPrintf printf
36546 #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
36547 #else
36548 #define PAGERTRACE(X)
36549 #endif
36552 ** The following two macros are used within the PAGERTRACE() macros above
36553 ** to print out file-descriptors.
36555 ** PAGERID() takes a pointer to a Pager struct as its argument. The
36556 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
36557 ** struct as its argument.
36559 #define PAGERID(p) ((int)(p->fd))
36560 #define FILEHANDLEID(fd) ((int)fd)
36563 ** The Pager.eState variable stores the current 'state' of a pager. A
36564 ** pager may be in any one of the seven states shown in the following
36565 ** state diagram.
36567 ** OPEN <------+------+
36568 ** | | |
36569 ** V | |
36570 ** +---------> READER-------+ |
36571 ** | | |
36572 ** | V |
36573 ** |<-------WRITER_LOCKED------> ERROR
36574 ** | | ^
36575 ** | V |
36576 ** |<------WRITER_CACHEMOD-------->|
36577 ** | | |
36578 ** | V |
36579 ** |<-------WRITER_DBMOD---------->|
36580 ** | | |
36581 ** | V |
36582 ** +<------WRITER_FINISHED-------->+
36585 ** List of state transitions and the C [function] that performs each:
36587 ** OPEN -> READER [sqlite3PagerSharedLock]
36588 ** READER -> OPEN [pager_unlock]
36590 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
36591 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
36592 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
36593 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
36594 ** WRITER_*** -> READER [pager_end_transaction]
36596 ** WRITER_*** -> ERROR [pager_error]
36597 ** ERROR -> OPEN [pager_unlock]
36600 ** OPEN:
36602 ** The pager starts up in this state. Nothing is guaranteed in this
36603 ** state - the file may or may not be locked and the database size is
36604 ** unknown. The database may not be read or written.
36606 ** * No read or write transaction is active.
36607 ** * Any lock, or no lock at all, may be held on the database file.
36608 ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
36610 ** READER:
36612 ** In this state all the requirements for reading the database in
36613 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
36614 ** was) in exclusive-locking mode, a user-level read transaction is
36615 ** open. The database size is known in this state.
36617 ** A connection running with locking_mode=normal enters this state when
36618 ** it opens a read-transaction on the database and returns to state
36619 ** OPEN after the read-transaction is completed. However a connection
36620 ** running in locking_mode=exclusive (including temp databases) remains in
36621 ** this state even after the read-transaction is closed. The only way
36622 ** a locking_mode=exclusive connection can transition from READER to OPEN
36623 ** is via the ERROR state (see below).
36625 ** * A read transaction may be active (but a write-transaction cannot).
36626 ** * A SHARED or greater lock is held on the database file.
36627 ** * The dbSize variable may be trusted (even if a user-level read
36628 ** transaction is not active). The dbOrigSize and dbFileSize variables
36629 ** may not be trusted at this point.
36630 ** * If the database is a WAL database, then the WAL connection is open.
36631 ** * Even if a read-transaction is not open, it is guaranteed that
36632 ** there is no hot-journal in the file-system.
36634 ** WRITER_LOCKED:
36636 ** The pager moves to this state from READER when a write-transaction
36637 ** is first opened on the database. In WRITER_LOCKED state, all locks
36638 ** required to start a write-transaction are held, but no actual
36639 ** modifications to the cache or database have taken place.
36641 ** In rollback mode, a RESERVED or (if the transaction was opened with
36642 ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
36643 ** moving to this state, but the journal file is not written to or opened
36644 ** to in this state. If the transaction is committed or rolled back while
36645 ** in WRITER_LOCKED state, all that is required is to unlock the database
36646 ** file.
36648 ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
36649 ** If the connection is running with locking_mode=exclusive, an attempt
36650 ** is made to obtain an EXCLUSIVE lock on the database file.
36652 ** * A write transaction is active.
36653 ** * If the connection is open in rollback-mode, a RESERVED or greater
36654 ** lock is held on the database file.
36655 ** * If the connection is open in WAL-mode, a WAL write transaction
36656 ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
36657 ** called).
36658 ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
36659 ** * The contents of the pager cache have not been modified.
36660 ** * The journal file may or may not be open.
36661 ** * Nothing (not even the first header) has been written to the journal.
36663 ** WRITER_CACHEMOD:
36665 ** A pager moves from WRITER_LOCKED state to this state when a page is
36666 ** first modified by the upper layer. In rollback mode the journal file
36667 ** is opened (if it is not already open) and a header written to the
36668 ** start of it. The database file on disk has not been modified.
36670 ** * A write transaction is active.
36671 ** * A RESERVED or greater lock is held on the database file.
36672 ** * The journal file is open and the first header has been written
36673 ** to it, but the header has not been synced to disk.
36674 ** * The contents of the page cache have been modified.
36676 ** WRITER_DBMOD:
36678 ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
36679 ** when it modifies the contents of the database file. WAL connections
36680 ** never enter this state (since they do not modify the database file,
36681 ** just the log file).
36683 ** * A write transaction is active.
36684 ** * An EXCLUSIVE or greater lock is held on the database file.
36685 ** * The journal file is open and the first header has been written
36686 ** and synced to disk.
36687 ** * The contents of the page cache have been modified (and possibly
36688 ** written to disk).
36690 ** WRITER_FINISHED:
36692 ** It is not possible for a WAL connection to enter this state.
36694 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
36695 ** state after the entire transaction has been successfully written into the
36696 ** database file. In this state the transaction may be committed simply
36697 ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
36698 ** not possible to modify the database further. At this point, the upper
36699 ** layer must either commit or rollback the transaction.
36701 ** * A write transaction is active.
36702 ** * An EXCLUSIVE or greater lock is held on the database file.
36703 ** * All writing and syncing of journal and database data has finished.
36704 ** If no error occured, all that remains is to finalize the journal to
36705 ** commit the transaction. If an error did occur, the caller will need
36706 ** to rollback the transaction.
36708 ** ERROR:
36710 ** The ERROR state is entered when an IO or disk-full error (including
36711 ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
36712 ** difficult to be sure that the in-memory pager state (cache contents,
36713 ** db size etc.) are consistent with the contents of the file-system.
36715 ** Temporary pager files may enter the ERROR state, but in-memory pagers
36716 ** cannot.
36718 ** For example, if an IO error occurs while performing a rollback,
36719 ** the contents of the page-cache may be left in an inconsistent state.
36720 ** At this point it would be dangerous to change back to READER state
36721 ** (as usually happens after a rollback). Any subsequent readers might
36722 ** report database corruption (due to the inconsistent cache), and if
36723 ** they upgrade to writers, they may inadvertently corrupt the database
36724 ** file. To avoid this hazard, the pager switches into the ERROR state
36725 ** instead of READER following such an error.
36727 ** Once it has entered the ERROR state, any attempt to use the pager
36728 ** to read or write data returns an error. Eventually, once all
36729 ** outstanding transactions have been abandoned, the pager is able to
36730 ** transition back to OPEN state, discarding the contents of the
36731 ** page-cache and any other in-memory state at the same time. Everything
36732 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
36733 ** when a read-transaction is next opened on the pager (transitioning
36734 ** the pager into READER state). At that point the system has recovered
36735 ** from the error.
36737 ** Specifically, the pager jumps into the ERROR state if:
36739 ** 1. An error occurs while attempting a rollback. This happens in
36740 ** function sqlite3PagerRollback().
36742 ** 2. An error occurs while attempting to finalize a journal file
36743 ** following a commit in function sqlite3PagerCommitPhaseTwo().
36745 ** 3. An error occurs while attempting to write to the journal or
36746 ** database file in function pagerStress() in order to free up
36747 ** memory.
36749 ** In other cases, the error is returned to the b-tree layer. The b-tree
36750 ** layer then attempts a rollback operation. If the error condition
36751 ** persists, the pager enters the ERROR state via condition (1) above.
36753 ** Condition (3) is necessary because it can be triggered by a read-only
36754 ** statement executed within a transaction. In this case, if the error
36755 ** code were simply returned to the user, the b-tree layer would not
36756 ** automatically attempt a rollback, as it assumes that an error in a
36757 ** read-only statement cannot leave the pager in an internally inconsistent
36758 ** state.
36760 ** * The Pager.errCode variable is set to something other than SQLITE_OK.
36761 ** * There are one or more outstanding references to pages (after the
36762 ** last reference is dropped the pager should move back to OPEN state).
36763 ** * The pager is not an in-memory pager.
36766 ** Notes:
36768 ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
36769 ** connection is open in WAL mode. A WAL connection is always in one
36770 ** of the first four states.
36772 ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
36773 ** state. There are two exceptions: immediately after exclusive-mode has
36774 ** been turned on (and before any read or write transactions are
36775 ** executed), and when the pager is leaving the "error state".
36777 ** * See also: assert_pager_state().
36779 #define PAGER_OPEN 0
36780 #define PAGER_READER 1
36781 #define PAGER_WRITER_LOCKED 2
36782 #define PAGER_WRITER_CACHEMOD 3
36783 #define PAGER_WRITER_DBMOD 4
36784 #define PAGER_WRITER_FINISHED 5
36785 #define PAGER_ERROR 6
36788 ** The Pager.eLock variable is almost always set to one of the
36789 ** following locking-states, according to the lock currently held on
36790 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
36791 ** This variable is kept up to date as locks are taken and released by
36792 ** the pagerLockDb() and pagerUnlockDb() wrappers.
36794 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
36795 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
36796 ** the operation was successful. In these circumstances pagerLockDb() and
36797 ** pagerUnlockDb() take a conservative approach - eLock is always updated
36798 ** when unlocking the file, and only updated when locking the file if the
36799 ** VFS call is successful. This way, the Pager.eLock variable may be set
36800 ** to a less exclusive (lower) value than the lock that is actually held
36801 ** at the system level, but it is never set to a more exclusive value.
36803 ** This is usually safe. If an xUnlock fails or appears to fail, there may
36804 ** be a few redundant xLock() calls or a lock may be held for longer than
36805 ** required, but nothing really goes wrong.
36807 ** The exception is when the database file is unlocked as the pager moves
36808 ** from ERROR to OPEN state. At this point there may be a hot-journal file
36809 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
36810 ** transition, by the same pager or any other). If the call to xUnlock()
36811 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
36812 ** can confuse the call to xCheckReservedLock() call made later as part
36813 ** of hot-journal detection.
36815 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
36816 ** lock held by this process or any others". So xCheckReservedLock may
36817 ** return true because the caller itself is holding an EXCLUSIVE lock (but
36818 ** doesn't know it because of a previous error in xUnlock). If this happens
36819 ** a hot-journal may be mistaken for a journal being created by an active
36820 ** transaction in another process, causing SQLite to read from the database
36821 ** without rolling it back.
36823 ** To work around this, if a call to xUnlock() fails when unlocking the
36824 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
36825 ** is only changed back to a real locking state after a successful call
36826 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
36827 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
36828 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
36829 ** lock on the database file before attempting to roll it back. See function
36830 ** PagerSharedLock() for more detail.
36832 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
36833 ** PAGER_OPEN state.
36835 #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
36838 ** A macro used for invoking the codec if there is one
36840 #ifdef SQLITE_HAS_CODEC
36841 # define CODEC1(P,D,N,X,E) \
36842 if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
36843 # define CODEC2(P,D,N,X,E,O) \
36844 if( P->xCodec==0 ){ O=(char*)D; }else \
36845 if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
36846 #else
36847 # define CODEC1(P,D,N,X,E) /* NO-OP */
36848 # define CODEC2(P,D,N,X,E,O) O=(char*)D
36849 #endif
36852 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
36853 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
36854 ** This could conceivably cause corruption following a power failure on
36855 ** such a system. This is currently an undocumented limit.
36857 #define MAX_SECTOR_SIZE 0x10000
36860 ** An instance of the following structure is allocated for each active
36861 ** savepoint and statement transaction in the system. All such structures
36862 ** are stored in the Pager.aSavepoint[] array, which is allocated and
36863 ** resized using sqlite3Realloc().
36865 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
36866 ** set to 0. If a journal-header is written into the main journal while
36867 ** the savepoint is active, then iHdrOffset is set to the byte offset
36868 ** immediately following the last journal record written into the main
36869 ** journal before the journal-header. This is required during savepoint
36870 ** rollback (see pagerPlaybackSavepoint()).
36872 typedef struct PagerSavepoint PagerSavepoint;
36873 struct PagerSavepoint {
36874 i64 iOffset; /* Starting offset in main journal */
36875 i64 iHdrOffset; /* See above */
36876 Bitvec *pInSavepoint; /* Set of pages in this savepoint */
36877 Pgno nOrig; /* Original number of pages in file */
36878 Pgno iSubRec; /* Index of first record in sub-journal */
36879 #ifndef SQLITE_OMIT_WAL
36880 u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
36881 #endif
36885 ** A open page cache is an instance of struct Pager. A description of
36886 ** some of the more important member variables follows:
36888 ** eState
36890 ** The current 'state' of the pager object. See the comment and state
36891 ** diagram above for a description of the pager state.
36893 ** eLock
36895 ** For a real on-disk database, the current lock held on the database file -
36896 ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
36898 ** For a temporary or in-memory database (neither of which require any
36899 ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
36900 ** databases always have Pager.exclusiveMode==1, this tricks the pager
36901 ** logic into thinking that it already has all the locks it will ever
36902 ** need (and no reason to release them).
36904 ** In some (obscure) circumstances, this variable may also be set to
36905 ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
36906 ** details.
36908 ** changeCountDone
36910 ** This boolean variable is used to make sure that the change-counter
36911 ** (the 4-byte header field at byte offset 24 of the database file) is
36912 ** not updated more often than necessary.
36914 ** It is set to true when the change-counter field is updated, which
36915 ** can only happen if an exclusive lock is held on the database file.
36916 ** It is cleared (set to false) whenever an exclusive lock is
36917 ** relinquished on the database file. Each time a transaction is committed,
36918 ** The changeCountDone flag is inspected. If it is true, the work of
36919 ** updating the change-counter is omitted for the current transaction.
36921 ** This mechanism means that when running in exclusive mode, a connection
36922 ** need only update the change-counter once, for the first transaction
36923 ** committed.
36925 ** setMaster
36927 ** When PagerCommitPhaseOne() is called to commit a transaction, it may
36928 ** (or may not) specify a master-journal name to be written into the
36929 ** journal file before it is synced to disk.
36931 ** Whether or not a journal file contains a master-journal pointer affects
36932 ** the way in which the journal file is finalized after the transaction is
36933 ** committed or rolled back when running in "journal_mode=PERSIST" mode.
36934 ** If a journal file does not contain a master-journal pointer, it is
36935 ** finalized by overwriting the first journal header with zeroes. If
36936 ** it does contain a master-journal pointer the journal file is finalized
36937 ** by truncating it to zero bytes, just as if the connection were
36938 ** running in "journal_mode=truncate" mode.
36940 ** Journal files that contain master journal pointers cannot be finalized
36941 ** simply by overwriting the first journal-header with zeroes, as the
36942 ** master journal pointer could interfere with hot-journal rollback of any
36943 ** subsequently interrupted transaction that reuses the journal file.
36945 ** The flag is cleared as soon as the journal file is finalized (either
36946 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
36947 ** journal file from being successfully finalized, the setMaster flag
36948 ** is cleared anyway (and the pager will move to ERROR state).
36950 ** doNotSpill, doNotSyncSpill
36952 ** These two boolean variables control the behaviour of cache-spills
36953 ** (calls made by the pcache module to the pagerStress() routine to
36954 ** write cached data to the file-system in order to free up memory).
36956 ** When doNotSpill is non-zero, writing to the database from pagerStress()
36957 ** is disabled altogether. This is done in a very obscure case that
36958 ** comes up during savepoint rollback that requires the pcache module
36959 ** to allocate a new page to prevent the journal file from being written
36960 ** while it is being traversed by code in pager_playback().
36962 ** If doNotSyncSpill is non-zero, writing to the database from pagerStress()
36963 ** is permitted, but syncing the journal file is not. This flag is set
36964 ** by sqlite3PagerWrite() when the file-system sector-size is larger than
36965 ** the database page-size in order to prevent a journal sync from happening
36966 ** in between the journalling of two pages on the same sector.
36968 ** subjInMemory
36970 ** This is a boolean variable. If true, then any required sub-journal
36971 ** is opened as an in-memory journal file. If false, then in-memory
36972 ** sub-journals are only used for in-memory pager files.
36974 ** This variable is updated by the upper layer each time a new
36975 ** write-transaction is opened.
36977 ** dbSize, dbOrigSize, dbFileSize
36979 ** Variable dbSize is set to the number of pages in the database file.
36980 ** It is valid in PAGER_READER and higher states (all states except for
36981 ** OPEN and ERROR).
36983 ** dbSize is set based on the size of the database file, which may be
36984 ** larger than the size of the database (the value stored at offset
36985 ** 28 of the database header by the btree). If the size of the file
36986 ** is not an integer multiple of the page-size, the value stored in
36987 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
36988 ** Except, any file that is greater than 0 bytes in size is considered
36989 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
36990 ** to dbSize==1).
36992 ** During a write-transaction, if pages with page-numbers greater than
36993 ** dbSize are modified in the cache, dbSize is updated accordingly.
36994 ** Similarly, if the database is truncated using PagerTruncateImage(),
36995 ** dbSize is updated.
36997 ** Variables dbOrigSize and dbFileSize are valid in states
36998 ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
36999 ** variable at the start of the transaction. It is used during rollback,
37000 ** and to determine whether or not pages need to be journalled before
37001 ** being modified.
37003 ** Throughout a write-transaction, dbFileSize contains the size of
37004 ** the file on disk in pages. It is set to a copy of dbSize when the
37005 ** write-transaction is first opened, and updated when VFS calls are made
37006 ** to write or truncate the database file on disk.
37008 ** The only reason the dbFileSize variable is required is to suppress
37009 ** unnecessary calls to xTruncate() after committing a transaction. If,
37010 ** when a transaction is committed, the dbFileSize variable indicates
37011 ** that the database file is larger than the database image (Pager.dbSize),
37012 ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
37013 ** to measure the database file on disk, and then truncates it if required.
37014 ** dbFileSize is not used when rolling back a transaction. In this case
37015 ** pager_truncate() is called unconditionally (which means there may be
37016 ** a call to xFilesize() that is not strictly required). In either case,
37017 ** pager_truncate() may cause the file to become smaller or larger.
37019 ** dbHintSize
37021 ** The dbHintSize variable is used to limit the number of calls made to
37022 ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
37024 ** dbHintSize is set to a copy of the dbSize variable when a
37025 ** write-transaction is opened (at the same time as dbFileSize and
37026 ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
37027 ** dbHintSize is increased to the number of pages that correspond to the
37028 ** size-hint passed to the method call. See pager_write_pagelist() for
37029 ** details.
37031 ** errCode
37033 ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
37034 ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
37035 ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
37036 ** sub-codes.
37038 struct Pager {
37039 sqlite3_vfs *pVfs; /* OS functions to use for IO */
37040 u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
37041 u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
37042 u8 useJournal; /* Use a rollback journal on this file */
37043 u8 noReadlock; /* Do not bother to obtain readlocks */
37044 u8 noSync; /* Do not sync the journal if true */
37045 u8 fullSync; /* Do extra syncs of the journal for robustness */
37046 u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
37047 u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
37048 u8 tempFile; /* zFilename is a temporary file */
37049 u8 readOnly; /* True for a read-only database */
37050 u8 memDb; /* True to inhibit all file I/O */
37052 /**************************************************************************
37053 ** The following block contains those class members that change during
37054 ** routine opertion. Class members not in this block are either fixed
37055 ** when the pager is first created or else only change when there is a
37056 ** significant mode change (such as changing the page_size, locking_mode,
37057 ** or the journal_mode). From another view, these class members describe
37058 ** the "state" of the pager, while other class members describe the
37059 ** "configuration" of the pager.
37061 u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
37062 u8 eLock; /* Current lock held on database file */
37063 u8 changeCountDone; /* Set after incrementing the change-counter */
37064 u8 setMaster; /* True if a m-j name has been written to jrnl */
37065 u8 doNotSpill; /* Do not spill the cache when non-zero */
37066 u8 doNotSyncSpill; /* Do not do a spill that requires jrnl sync */
37067 u8 subjInMemory; /* True to use in-memory sub-journals */
37068 Pgno dbSize; /* Number of pages in the database */
37069 Pgno dbOrigSize; /* dbSize before the current transaction */
37070 Pgno dbFileSize; /* Number of pages in the database file */
37071 Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
37072 int errCode; /* One of several kinds of errors */
37073 int nRec; /* Pages journalled since last j-header written */
37074 u32 cksumInit; /* Quasi-random value added to every checksum */
37075 u32 nSubRec; /* Number of records written to sub-journal */
37076 Bitvec *pInJournal; /* One bit for each page in the database file */
37077 sqlite3_file *fd; /* File descriptor for database */
37078 sqlite3_file *jfd; /* File descriptor for main journal */
37079 sqlite3_file *sjfd; /* File descriptor for sub-journal */
37080 i64 journalOff; /* Current write offset in the journal file */
37081 i64 journalHdr; /* Byte offset to previous journal header */
37082 sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
37083 PagerSavepoint *aSavepoint; /* Array of active savepoints */
37084 int nSavepoint; /* Number of elements in aSavepoint[] */
37085 char dbFileVers[16]; /* Changes whenever database file changes */
37087 ** End of the routinely-changing class members
37088 ***************************************************************************/
37090 u16 nExtra; /* Add this many bytes to each in-memory page */
37091 i16 nReserve; /* Number of unused bytes at end of each page */
37092 u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
37093 u32 sectorSize; /* Assumed sector size during rollback */
37094 int pageSize; /* Number of bytes in a page */
37095 Pgno mxPgno; /* Maximum allowed size of the database */
37096 i64 journalSizeLimit; /* Size limit for persistent journal files */
37097 char *zFilename; /* Name of the database file */
37098 char *zJournal; /* Name of the journal file */
37099 int (*xBusyHandler)(void*); /* Function to call when busy */
37100 void *pBusyHandlerArg; /* Context argument for xBusyHandler */
37101 #ifdef SQLITE_TEST
37102 int nHit, nMiss; /* Cache hits and missing */
37103 int nRead, nWrite; /* Database pages read/written */
37104 #endif
37105 void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
37106 #ifdef SQLITE_HAS_CODEC
37107 void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
37108 void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
37109 void (*xCodecFree)(void*); /* Destructor for the codec */
37110 void *pCodec; /* First argument to xCodec... methods */
37111 #endif
37112 char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
37113 PCache *pPCache; /* Pointer to page cache object */
37114 #ifndef SQLITE_OMIT_WAL
37115 Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
37116 char *zWal; /* File name for write-ahead log */
37117 #endif
37121 ** The following global variables hold counters used for
37122 ** testing purposes only. These variables do not exist in
37123 ** a non-testing build. These variables are not thread-safe.
37125 #ifdef SQLITE_TEST
37126 SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
37127 SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
37128 SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
37129 # define PAGER_INCR(v) v++
37130 #else
37131 # define PAGER_INCR(v)
37132 #endif
37137 ** Journal files begin with the following magic string. The data
37138 ** was obtained from /dev/random. It is used only as a sanity check.
37140 ** Since version 2.8.0, the journal format contains additional sanity
37141 ** checking information. If the power fails while the journal is being
37142 ** written, semi-random garbage data might appear in the journal
37143 ** file after power is restored. If an attempt is then made
37144 ** to roll the journal back, the database could be corrupted. The additional
37145 ** sanity checking data is an attempt to discover the garbage in the
37146 ** journal and ignore it.
37148 ** The sanity checking information for the new journal format consists
37149 ** of a 32-bit checksum on each page of data. The checksum covers both
37150 ** the page number and the pPager->pageSize bytes of data for the page.
37151 ** This cksum is initialized to a 32-bit random value that appears in the
37152 ** journal file right after the header. The random initializer is important,
37153 ** because garbage data that appears at the end of a journal is likely
37154 ** data that was once in other files that have now been deleted. If the
37155 ** garbage data came from an obsolete journal file, the checksums might
37156 ** be correct. But by initializing the checksum to random value which
37157 ** is different for every journal, we minimize that risk.
37159 static const unsigned char aJournalMagic[] = {
37160 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
37164 ** The size of the of each page record in the journal is given by
37165 ** the following macro.
37167 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
37170 ** The journal header size for this pager. This is usually the same
37171 ** size as a single disk sector. See also setSectorSize().
37173 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
37176 ** The macro MEMDB is true if we are dealing with an in-memory database.
37177 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
37178 ** the value of MEMDB will be a constant and the compiler will optimize
37179 ** out code that would never execute.
37181 #ifdef SQLITE_OMIT_MEMORYDB
37182 # define MEMDB 0
37183 #else
37184 # define MEMDB pPager->memDb
37185 #endif
37188 ** The maximum legal page number is (2^31 - 1).
37190 #define PAGER_MAX_PGNO 2147483647
37193 ** The argument to this macro is a file descriptor (type sqlite3_file*).
37194 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
37196 ** This is so that expressions can be written as:
37198 ** if( isOpen(pPager->jfd) ){ ...
37200 ** instead of
37202 ** if( pPager->jfd->pMethods ){ ...
37204 #define isOpen(pFd) ((pFd)->pMethods)
37207 ** Return true if this pager uses a write-ahead log instead of the usual
37208 ** rollback journal. Otherwise false.
37210 #ifndef SQLITE_OMIT_WAL
37211 static int pagerUseWal(Pager *pPager){
37212 return (pPager->pWal!=0);
37214 #else
37215 # define pagerUseWal(x) 0
37216 # define pagerRollbackWal(x) 0
37217 # define pagerWalFrames(v,w,x,y,z) 0
37218 # define pagerOpenWalIfPresent(z) SQLITE_OK
37219 # define pagerBeginReadTransaction(z) SQLITE_OK
37220 #endif
37222 /* Begin preload-cache.patch for Chromium */
37223 /* See comments above the definition. */
37224 SQLITE_PRIVATE int sqlite3PagerAcquire2(
37225 Pager *pPager,
37226 Pgno pgno,
37227 DbPage **ppPage,
37228 int noContent,
37229 unsigned char *pDataToFill);
37230 /* End preload-cache.patch for Chromium */
37232 #ifndef NDEBUG
37234 ** Usage:
37236 ** assert( assert_pager_state(pPager) );
37238 ** This function runs many asserts to try to find inconsistencies in
37239 ** the internal state of the Pager object.
37241 static int assert_pager_state(Pager *p){
37242 Pager *pPager = p;
37244 /* State must be valid. */
37245 assert( p->eState==PAGER_OPEN
37246 || p->eState==PAGER_READER
37247 || p->eState==PAGER_WRITER_LOCKED
37248 || p->eState==PAGER_WRITER_CACHEMOD
37249 || p->eState==PAGER_WRITER_DBMOD
37250 || p->eState==PAGER_WRITER_FINISHED
37251 || p->eState==PAGER_ERROR
37254 /* Regardless of the current state, a temp-file connection always behaves
37255 ** as if it has an exclusive lock on the database file. It never updates
37256 ** the change-counter field, so the changeCountDone flag is always set.
37258 assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
37259 assert( p->tempFile==0 || pPager->changeCountDone );
37261 /* If the useJournal flag is clear, the journal-mode must be "OFF".
37262 ** And if the journal-mode is "OFF", the journal file must not be open.
37264 assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
37265 assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
37267 /* Check that MEMDB implies noSync. And an in-memory journal. Since
37268 ** this means an in-memory pager performs no IO at all, it cannot encounter
37269 ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
37270 ** a journal file. (although the in-memory journal implementation may
37271 ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
37272 ** is therefore not possible for an in-memory pager to enter the ERROR
37273 ** state.
37275 if( MEMDB ){
37276 assert( p->noSync );
37277 assert( p->journalMode==PAGER_JOURNALMODE_OFF
37278 || p->journalMode==PAGER_JOURNALMODE_MEMORY
37280 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
37281 assert( pagerUseWal(p)==0 );
37284 /* If changeCountDone is set, a RESERVED lock or greater must be held
37285 ** on the file.
37287 assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
37288 assert( p->eLock!=PENDING_LOCK );
37290 switch( p->eState ){
37291 case PAGER_OPEN:
37292 assert( !MEMDB );
37293 assert( pPager->errCode==SQLITE_OK );
37294 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
37295 break;
37297 case PAGER_READER:
37298 assert( pPager->errCode==SQLITE_OK );
37299 assert( p->eLock!=UNKNOWN_LOCK );
37300 assert( p->eLock>=SHARED_LOCK || p->noReadlock );
37301 break;
37303 case PAGER_WRITER_LOCKED:
37304 assert( p->eLock!=UNKNOWN_LOCK );
37305 assert( pPager->errCode==SQLITE_OK );
37306 if( !pagerUseWal(pPager) ){
37307 assert( p->eLock>=RESERVED_LOCK );
37309 assert( pPager->dbSize==pPager->dbOrigSize );
37310 assert( pPager->dbOrigSize==pPager->dbFileSize );
37311 assert( pPager->dbOrigSize==pPager->dbHintSize );
37312 assert( pPager->setMaster==0 );
37313 break;
37315 case PAGER_WRITER_CACHEMOD:
37316 assert( p->eLock!=UNKNOWN_LOCK );
37317 assert( pPager->errCode==SQLITE_OK );
37318 if( !pagerUseWal(pPager) ){
37319 /* It is possible that if journal_mode=wal here that neither the
37320 ** journal file nor the WAL file are open. This happens during
37321 ** a rollback transaction that switches from journal_mode=off
37322 ** to journal_mode=wal.
37324 assert( p->eLock>=RESERVED_LOCK );
37325 assert( isOpen(p->jfd)
37326 || p->journalMode==PAGER_JOURNALMODE_OFF
37327 || p->journalMode==PAGER_JOURNALMODE_WAL
37330 assert( pPager->dbOrigSize==pPager->dbFileSize );
37331 assert( pPager->dbOrigSize==pPager->dbHintSize );
37332 break;
37334 case PAGER_WRITER_DBMOD:
37335 assert( p->eLock==EXCLUSIVE_LOCK );
37336 assert( pPager->errCode==SQLITE_OK );
37337 assert( !pagerUseWal(pPager) );
37338 assert( p->eLock>=EXCLUSIVE_LOCK );
37339 assert( isOpen(p->jfd)
37340 || p->journalMode==PAGER_JOURNALMODE_OFF
37341 || p->journalMode==PAGER_JOURNALMODE_WAL
37343 assert( pPager->dbOrigSize<=pPager->dbHintSize );
37344 break;
37346 case PAGER_WRITER_FINISHED:
37347 assert( p->eLock==EXCLUSIVE_LOCK );
37348 assert( pPager->errCode==SQLITE_OK );
37349 assert( !pagerUseWal(pPager) );
37350 assert( isOpen(p->jfd)
37351 || p->journalMode==PAGER_JOURNALMODE_OFF
37352 || p->journalMode==PAGER_JOURNALMODE_WAL
37354 break;
37356 case PAGER_ERROR:
37357 /* There must be at least one outstanding reference to the pager if
37358 ** in ERROR state. Otherwise the pager should have already dropped
37359 ** back to OPEN state.
37361 assert( pPager->errCode!=SQLITE_OK );
37362 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
37363 break;
37366 return 1;
37368 #endif /* ifndef NDEBUG */
37370 #ifdef SQLITE_DEBUG
37372 ** Return a pointer to a human readable string in a static buffer
37373 ** containing the state of the Pager object passed as an argument. This
37374 ** is intended to be used within debuggers. For example, as an alternative
37375 ** to "print *pPager" in gdb:
37377 ** (gdb) printf "%s", print_pager_state(pPager)
37379 static char *print_pager_state(Pager *p){
37380 static char zRet[1024];
37382 sqlite3_snprintf(1024, zRet,
37383 "Filename: %s\n"
37384 "State: %s errCode=%d\n"
37385 "Lock: %s\n"
37386 "Locking mode: locking_mode=%s\n"
37387 "Journal mode: journal_mode=%s\n"
37388 "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
37389 "Journal: journalOff=%lld journalHdr=%lld\n"
37390 "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
37391 , p->zFilename
37392 , p->eState==PAGER_OPEN ? "OPEN" :
37393 p->eState==PAGER_READER ? "READER" :
37394 p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
37395 p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
37396 p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
37397 p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
37398 p->eState==PAGER_ERROR ? "ERROR" : "?error?"
37399 , (int)p->errCode
37400 , p->eLock==NO_LOCK ? "NO_LOCK" :
37401 p->eLock==RESERVED_LOCK ? "RESERVED" :
37402 p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
37403 p->eLock==SHARED_LOCK ? "SHARED" :
37404 p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
37405 , p->exclusiveMode ? "exclusive" : "normal"
37406 , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
37407 p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
37408 p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
37409 p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
37410 p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
37411 p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
37412 , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
37413 , p->journalOff, p->journalHdr
37414 , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
37417 return zRet;
37419 #endif
37422 ** Return true if it is necessary to write page *pPg into the sub-journal.
37423 ** A page needs to be written into the sub-journal if there exists one
37424 ** or more open savepoints for which:
37426 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
37427 ** * The bit corresponding to the page-number is not set in
37428 ** PagerSavepoint.pInSavepoint.
37430 static int subjRequiresPage(PgHdr *pPg){
37431 Pgno pgno = pPg->pgno;
37432 Pager *pPager = pPg->pPager;
37433 int i;
37434 for(i=0; i<pPager->nSavepoint; i++){
37435 PagerSavepoint *p = &pPager->aSavepoint[i];
37436 if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
37437 return 1;
37440 return 0;
37444 ** Return true if the page is already in the journal file.
37446 static int pageInJournal(PgHdr *pPg){
37447 return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
37451 ** Read a 32-bit integer from the given file descriptor. Store the integer
37452 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
37453 ** error code is something goes wrong.
37455 ** All values are stored on disk as big-endian.
37457 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
37458 unsigned char ac[4];
37459 int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
37460 if( rc==SQLITE_OK ){
37461 *pRes = sqlite3Get4byte(ac);
37463 return rc;
37467 ** Write a 32-bit integer into a string buffer in big-endian byte order.
37469 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
37473 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
37474 ** on success or an error code is something goes wrong.
37476 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
37477 char ac[4];
37478 put32bits(ac, val);
37479 return sqlite3OsWrite(fd, ac, 4, offset);
37483 ** Unlock the database file to level eLock, which must be either NO_LOCK
37484 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
37485 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
37487 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
37488 ** called, do not modify it. See the comment above the #define of
37489 ** UNKNOWN_LOCK for an explanation of this.
37491 static int pagerUnlockDb(Pager *pPager, int eLock){
37492 int rc = SQLITE_OK;
37494 assert( !pPager->exclusiveMode || pPager->eLock==eLock );
37495 assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
37496 assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
37497 if( isOpen(pPager->fd) ){
37498 assert( pPager->eLock>=eLock );
37499 rc = sqlite3OsUnlock(pPager->fd, eLock);
37500 if( pPager->eLock!=UNKNOWN_LOCK ){
37501 pPager->eLock = (u8)eLock;
37503 IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
37505 return rc;
37509 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
37510 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
37511 ** Pager.eLock variable to the new locking state.
37513 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
37514 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
37515 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
37516 ** of this.
37518 static int pagerLockDb(Pager *pPager, int eLock){
37519 int rc = SQLITE_OK;
37521 assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
37522 if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
37523 rc = sqlite3OsLock(pPager->fd, eLock);
37524 if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
37525 pPager->eLock = (u8)eLock;
37526 IOTRACE(("LOCK %p %d\n", pPager, eLock))
37529 return rc;
37533 ** This function determines whether or not the atomic-write optimization
37534 ** can be used with this pager. The optimization can be used if:
37536 ** (a) the value returned by OsDeviceCharacteristics() indicates that
37537 ** a database page may be written atomically, and
37538 ** (b) the value returned by OsSectorSize() is less than or equal
37539 ** to the page size.
37541 ** The optimization is also always enabled for temporary files. It is
37542 ** an error to call this function if pPager is opened on an in-memory
37543 ** database.
37545 ** If the optimization cannot be used, 0 is returned. If it can be used,
37546 ** then the value returned is the size of the journal file when it
37547 ** contains rollback data for exactly one page.
37549 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
37550 static int jrnlBufferSize(Pager *pPager){
37551 assert( !MEMDB );
37552 if( !pPager->tempFile ){
37553 int dc; /* Device characteristics */
37554 int nSector; /* Sector size */
37555 int szPage; /* Page size */
37557 assert( isOpen(pPager->fd) );
37558 dc = sqlite3OsDeviceCharacteristics(pPager->fd);
37559 nSector = pPager->sectorSize;
37560 szPage = pPager->pageSize;
37562 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
37563 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
37564 if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
37565 return 0;
37569 return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
37571 #endif
37574 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
37575 ** on the cache using a hash function. This is used for testing
37576 ** and debugging only.
37578 #ifdef SQLITE_CHECK_PAGES
37580 ** Return a 32-bit hash of the page data for pPage.
37582 static u32 pager_datahash(int nByte, unsigned char *pData){
37583 u32 hash = 0;
37584 int i;
37585 for(i=0; i<nByte; i++){
37586 hash = (hash*1039) + pData[i];
37588 return hash;
37590 static u32 pager_pagehash(PgHdr *pPage){
37591 return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
37593 static void pager_set_pagehash(PgHdr *pPage){
37594 pPage->pageHash = pager_pagehash(pPage);
37598 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
37599 ** is defined, and NDEBUG is not defined, an assert() statement checks
37600 ** that the page is either dirty or still matches the calculated page-hash.
37602 #define CHECK_PAGE(x) checkPage(x)
37603 static void checkPage(PgHdr *pPg){
37604 Pager *pPager = pPg->pPager;
37605 assert( pPager->eState!=PAGER_ERROR );
37606 assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
37609 #else
37610 #define pager_datahash(X,Y) 0
37611 #define pager_pagehash(X) 0
37612 #define pager_set_pagehash(X)
37613 #define CHECK_PAGE(x)
37614 #endif /* SQLITE_CHECK_PAGES */
37617 ** When this is called the journal file for pager pPager must be open.
37618 ** This function attempts to read a master journal file name from the
37619 ** end of the file and, if successful, copies it into memory supplied
37620 ** by the caller. See comments above writeMasterJournal() for the format
37621 ** used to store a master journal file name at the end of a journal file.
37623 ** zMaster must point to a buffer of at least nMaster bytes allocated by
37624 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
37625 ** enough space to write the master journal name). If the master journal
37626 ** name in the journal is longer than nMaster bytes (including a
37627 ** nul-terminator), then this is handled as if no master journal name
37628 ** were present in the journal.
37630 ** If a master journal file name is present at the end of the journal
37631 ** file, then it is copied into the buffer pointed to by zMaster. A
37632 ** nul-terminator byte is appended to the buffer following the master
37633 ** journal file name.
37635 ** If it is determined that no master journal file name is present
37636 ** zMaster[0] is set to 0 and SQLITE_OK returned.
37638 ** If an error occurs while reading from the journal file, an SQLite
37639 ** error code is returned.
37641 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
37642 int rc; /* Return code */
37643 u32 len; /* Length in bytes of master journal name */
37644 i64 szJ; /* Total size in bytes of journal file pJrnl */
37645 u32 cksum; /* MJ checksum value read from journal */
37646 u32 u; /* Unsigned loop counter */
37647 unsigned char aMagic[8]; /* A buffer to hold the magic header */
37648 zMaster[0] = '\0';
37650 if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
37651 || szJ<16
37652 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
37653 || len>=nMaster
37654 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
37655 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
37656 || memcmp(aMagic, aJournalMagic, 8)
37657 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
37659 return rc;
37662 /* See if the checksum matches the master journal name */
37663 for(u=0; u<len; u++){
37664 cksum -= zMaster[u];
37666 if( cksum ){
37667 /* If the checksum doesn't add up, then one or more of the disk sectors
37668 ** containing the master journal filename is corrupted. This means
37669 ** definitely roll back, so just return SQLITE_OK and report a (nul)
37670 ** master-journal filename.
37672 len = 0;
37674 zMaster[len] = '\0';
37676 return SQLITE_OK;
37680 ** Return the offset of the sector boundary at or immediately
37681 ** following the value in pPager->journalOff, assuming a sector
37682 ** size of pPager->sectorSize bytes.
37684 ** i.e for a sector size of 512:
37686 ** Pager.journalOff Return value
37687 ** ---------------------------------------
37688 ** 0 0
37689 ** 512 512
37690 ** 100 512
37691 ** 2000 2048
37694 static i64 journalHdrOffset(Pager *pPager){
37695 i64 offset = 0;
37696 i64 c = pPager->journalOff;
37697 if( c ){
37698 offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
37700 assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
37701 assert( offset>=c );
37702 assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
37703 return offset;
37707 ** The journal file must be open when this function is called.
37709 ** This function is a no-op if the journal file has not been written to
37710 ** within the current transaction (i.e. if Pager.journalOff==0).
37712 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
37713 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
37714 ** zero the 28-byte header at the start of the journal file. In either case,
37715 ** if the pager is not in no-sync mode, sync the journal file immediately
37716 ** after writing or truncating it.
37718 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
37719 ** following the truncation or zeroing described above the size of the
37720 ** journal file in bytes is larger than this value, then truncate the
37721 ** journal file to Pager.journalSizeLimit bytes. The journal file does
37722 ** not need to be synced following this operation.
37724 ** If an IO error occurs, abandon processing and return the IO error code.
37725 ** Otherwise, return SQLITE_OK.
37727 static int zeroJournalHdr(Pager *pPager, int doTruncate){
37728 int rc = SQLITE_OK; /* Return code */
37729 assert( isOpen(pPager->jfd) );
37730 if( pPager->journalOff ){
37731 const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
37733 IOTRACE(("JZEROHDR %p\n", pPager))
37734 if( doTruncate || iLimit==0 ){
37735 rc = sqlite3OsTruncate(pPager->jfd, 0);
37736 }else{
37737 static const char zeroHdr[28] = {0};
37738 rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
37740 if( rc==SQLITE_OK && !pPager->noSync ){
37741 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
37744 /* At this point the transaction is committed but the write lock
37745 ** is still held on the file. If there is a size limit configured for
37746 ** the persistent journal and the journal file currently consumes more
37747 ** space than that limit allows for, truncate it now. There is no need
37748 ** to sync the file following this operation.
37750 if( rc==SQLITE_OK && iLimit>0 ){
37751 i64 sz;
37752 rc = sqlite3OsFileSize(pPager->jfd, &sz);
37753 if( rc==SQLITE_OK && sz>iLimit ){
37754 rc = sqlite3OsTruncate(pPager->jfd, iLimit);
37758 return rc;
37762 ** The journal file must be open when this routine is called. A journal
37763 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
37764 ** current location.
37766 ** The format for the journal header is as follows:
37767 ** - 8 bytes: Magic identifying journal format.
37768 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
37769 ** - 4 bytes: Random number used for page hash.
37770 ** - 4 bytes: Initial database page count.
37771 ** - 4 bytes: Sector size used by the process that wrote this journal.
37772 ** - 4 bytes: Database page size.
37774 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
37776 static int writeJournalHdr(Pager *pPager){
37777 int rc = SQLITE_OK; /* Return code */
37778 char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
37779 u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
37780 u32 nWrite; /* Bytes of header sector written */
37781 int ii; /* Loop counter */
37783 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
37785 if( nHeader>JOURNAL_HDR_SZ(pPager) ){
37786 nHeader = JOURNAL_HDR_SZ(pPager);
37789 /* If there are active savepoints and any of them were created
37790 ** since the most recent journal header was written, update the
37791 ** PagerSavepoint.iHdrOffset fields now.
37793 for(ii=0; ii<pPager->nSavepoint; ii++){
37794 if( pPager->aSavepoint[ii].iHdrOffset==0 ){
37795 pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
37799 pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
37802 ** Write the nRec Field - the number of page records that follow this
37803 ** journal header. Normally, zero is written to this value at this time.
37804 ** After the records are added to the journal (and the journal synced,
37805 ** if in full-sync mode), the zero is overwritten with the true number
37806 ** of records (see syncJournal()).
37808 ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
37809 ** reading the journal this value tells SQLite to assume that the
37810 ** rest of the journal file contains valid page records. This assumption
37811 ** is dangerous, as if a failure occurred whilst writing to the journal
37812 ** file it may contain some garbage data. There are two scenarios
37813 ** where this risk can be ignored:
37815 ** * When the pager is in no-sync mode. Corruption can follow a
37816 ** power failure in this case anyway.
37818 ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
37819 ** that garbage data is never appended to the journal file.
37821 assert( isOpen(pPager->fd) || pPager->noSync );
37822 if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
37823 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
37825 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
37826 put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
37827 }else{
37828 memset(zHeader, 0, sizeof(aJournalMagic)+4);
37831 /* The random check-hash initialiser */
37832 sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
37833 put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
37834 /* The initial database size */
37835 put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
37836 /* The assumed sector size for this process */
37837 put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
37839 /* The page size */
37840 put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
37842 /* Initializing the tail of the buffer is not necessary. Everything
37843 ** works find if the following memset() is omitted. But initializing
37844 ** the memory prevents valgrind from complaining, so we are willing to
37845 ** take the performance hit.
37847 memset(&zHeader[sizeof(aJournalMagic)+20], 0,
37848 nHeader-(sizeof(aJournalMagic)+20));
37850 /* In theory, it is only necessary to write the 28 bytes that the
37851 ** journal header consumes to the journal file here. Then increment the
37852 ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
37853 ** record is written to the following sector (leaving a gap in the file
37854 ** that will be implicitly filled in by the OS).
37856 ** However it has been discovered that on some systems this pattern can
37857 ** be significantly slower than contiguously writing data to the file,
37858 ** even if that means explicitly writing data to the block of
37859 ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
37860 ** is done.
37862 ** The loop is required here in case the sector-size is larger than the
37863 ** database page size. Since the zHeader buffer is only Pager.pageSize
37864 ** bytes in size, more than one call to sqlite3OsWrite() may be required
37865 ** to populate the entire journal header sector.
37867 for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
37868 IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
37869 rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
37870 assert( pPager->journalHdr <= pPager->journalOff );
37871 pPager->journalOff += nHeader;
37874 return rc;
37878 ** The journal file must be open when this is called. A journal header file
37879 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
37880 ** file. The current location in the journal file is given by
37881 ** pPager->journalOff. See comments above function writeJournalHdr() for
37882 ** a description of the journal header format.
37884 ** If the header is read successfully, *pNRec is set to the number of
37885 ** page records following this header and *pDbSize is set to the size of the
37886 ** database before the transaction began, in pages. Also, pPager->cksumInit
37887 ** is set to the value read from the journal header. SQLITE_OK is returned
37888 ** in this case.
37890 ** If the journal header file appears to be corrupted, SQLITE_DONE is
37891 ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
37892 ** cannot be read from the journal file an error code is returned.
37894 static int readJournalHdr(
37895 Pager *pPager, /* Pager object */
37896 int isHot,
37897 i64 journalSize, /* Size of the open journal file in bytes */
37898 u32 *pNRec, /* OUT: Value read from the nRec field */
37899 u32 *pDbSize /* OUT: Value of original database size field */
37901 int rc; /* Return code */
37902 unsigned char aMagic[8]; /* A buffer to hold the magic header */
37903 i64 iHdrOff; /* Offset of journal header being read */
37905 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
37907 /* Advance Pager.journalOff to the start of the next sector. If the
37908 ** journal file is too small for there to be a header stored at this
37909 ** point, return SQLITE_DONE.
37911 pPager->journalOff = journalHdrOffset(pPager);
37912 if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
37913 return SQLITE_DONE;
37915 iHdrOff = pPager->journalOff;
37917 /* Read in the first 8 bytes of the journal header. If they do not match
37918 ** the magic string found at the start of each journal header, return
37919 ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
37920 ** proceed.
37922 if( isHot || iHdrOff!=pPager->journalHdr ){
37923 rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
37924 if( rc ){
37925 return rc;
37927 if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
37928 return SQLITE_DONE;
37932 /* Read the first three 32-bit fields of the journal header: The nRec
37933 ** field, the checksum-initializer and the database size at the start
37934 ** of the transaction. Return an error code if anything goes wrong.
37936 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
37937 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
37938 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
37940 return rc;
37943 if( pPager->journalOff==0 ){
37944 u32 iPageSize; /* Page-size field of journal header */
37945 u32 iSectorSize; /* Sector-size field of journal header */
37947 /* Read the page-size and sector-size journal header fields. */
37948 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
37949 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
37951 return rc;
37954 /* Versions of SQLite prior to 3.5.8 set the page-size field of the
37955 ** journal header to zero. In this case, assume that the Pager.pageSize
37956 ** variable is already set to the correct page size.
37958 if( iPageSize==0 ){
37959 iPageSize = pPager->pageSize;
37962 /* Check that the values read from the page-size and sector-size fields
37963 ** are within range. To be 'in range', both values need to be a power
37964 ** of two greater than or equal to 512 or 32, and not greater than their
37965 ** respective compile time maximum limits.
37967 if( iPageSize<512 || iSectorSize<32
37968 || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
37969 || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
37971 /* If the either the page-size or sector-size in the journal-header is
37972 ** invalid, then the process that wrote the journal-header must have
37973 ** crashed before the header was synced. In this case stop reading
37974 ** the journal file here.
37976 return SQLITE_DONE;
37979 /* Update the page-size to match the value read from the journal.
37980 ** Use a testcase() macro to make sure that malloc failure within
37981 ** PagerSetPagesize() is tested.
37983 rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
37984 testcase( rc!=SQLITE_OK );
37986 /* Update the assumed sector-size to match the value used by
37987 ** the process that created this journal. If this journal was
37988 ** created by a process other than this one, then this routine
37989 ** is being called from within pager_playback(). The local value
37990 ** of Pager.sectorSize is restored at the end of that routine.
37992 pPager->sectorSize = iSectorSize;
37995 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
37996 return rc;
38001 ** Write the supplied master journal name into the journal file for pager
38002 ** pPager at the current location. The master journal name must be the last
38003 ** thing written to a journal file. If the pager is in full-sync mode, the
38004 ** journal file descriptor is advanced to the next sector boundary before
38005 ** anything is written. The format is:
38007 ** + 4 bytes: PAGER_MJ_PGNO.
38008 ** + N bytes: Master journal filename in utf-8.
38009 ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
38010 ** + 4 bytes: Master journal name checksum.
38011 ** + 8 bytes: aJournalMagic[].
38013 ** The master journal page checksum is the sum of the bytes in the master
38014 ** journal name, where each byte is interpreted as a signed 8-bit integer.
38016 ** If zMaster is a NULL pointer (occurs for a single database transaction),
38017 ** this call is a no-op.
38019 static int writeMasterJournal(Pager *pPager, const char *zMaster){
38020 int rc; /* Return code */
38021 int nMaster; /* Length of string zMaster */
38022 i64 iHdrOff; /* Offset of header in journal file */
38023 i64 jrnlSize; /* Size of journal file on disk */
38024 u32 cksum = 0; /* Checksum of string zMaster */
38026 assert( pPager->setMaster==0 );
38027 assert( !pagerUseWal(pPager) );
38029 if( !zMaster
38030 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
38031 || pPager->journalMode==PAGER_JOURNALMODE_OFF
38033 return SQLITE_OK;
38035 pPager->setMaster = 1;
38036 assert( isOpen(pPager->jfd) );
38037 assert( pPager->journalHdr <= pPager->journalOff );
38039 /* Calculate the length in bytes and the checksum of zMaster */
38040 for(nMaster=0; zMaster[nMaster]; nMaster++){
38041 cksum += zMaster[nMaster];
38044 /* If in full-sync mode, advance to the next disk sector before writing
38045 ** the master journal name. This is in case the previous page written to
38046 ** the journal has already been synced.
38048 if( pPager->fullSync ){
38049 pPager->journalOff = journalHdrOffset(pPager);
38051 iHdrOff = pPager->journalOff;
38053 /* Write the master journal data to the end of the journal file. If
38054 ** an error occurs, return the error code to the caller.
38056 if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
38057 || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
38058 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
38059 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
38060 || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
38062 return rc;
38064 pPager->journalOff += (nMaster+20);
38066 /* If the pager is in peristent-journal mode, then the physical
38067 ** journal-file may extend past the end of the master-journal name
38068 ** and 8 bytes of magic data just written to the file. This is
38069 ** dangerous because the code to rollback a hot-journal file
38070 ** will not be able to find the master-journal name to determine
38071 ** whether or not the journal is hot.
38073 ** Easiest thing to do in this scenario is to truncate the journal
38074 ** file to the required size.
38076 if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
38077 && jrnlSize>pPager->journalOff
38079 rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
38081 return rc;
38085 ** Find a page in the hash table given its page number. Return
38086 ** a pointer to the page or NULL if the requested page is not
38087 ** already in memory.
38089 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
38090 PgHdr *p; /* Return value */
38092 /* It is not possible for a call to PcacheFetch() with createFlag==0 to
38093 ** fail, since no attempt to allocate dynamic memory will be made.
38095 (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
38096 return p;
38100 ** Discard the entire contents of the in-memory page-cache.
38102 static void pager_reset(Pager *pPager){
38103 sqlite3BackupRestart(pPager->pBackup);
38104 sqlite3PcacheClear(pPager->pPCache);
38108 ** Free all structures in the Pager.aSavepoint[] array and set both
38109 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
38110 ** if it is open and the pager is not in exclusive mode.
38112 static void releaseAllSavepoints(Pager *pPager){
38113 int ii; /* Iterator for looping through Pager.aSavepoint */
38114 for(ii=0; ii<pPager->nSavepoint; ii++){
38115 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
38117 if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
38118 sqlite3OsClose(pPager->sjfd);
38120 sqlite3_free(pPager->aSavepoint);
38121 pPager->aSavepoint = 0;
38122 pPager->nSavepoint = 0;
38123 pPager->nSubRec = 0;
38127 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
38128 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
38129 ** or SQLITE_NOMEM if a malloc failure occurs.
38131 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
38132 int ii; /* Loop counter */
38133 int rc = SQLITE_OK; /* Result code */
38135 for(ii=0; ii<pPager->nSavepoint; ii++){
38136 PagerSavepoint *p = &pPager->aSavepoint[ii];
38137 if( pgno<=p->nOrig ){
38138 rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
38139 testcase( rc==SQLITE_NOMEM );
38140 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
38143 return rc;
38147 ** This function is a no-op if the pager is in exclusive mode and not
38148 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
38149 ** state.
38151 ** If the pager is not in exclusive-access mode, the database file is
38152 ** completely unlocked. If the file is unlocked and the file-system does
38153 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
38154 ** closed (if it is open).
38156 ** If the pager is in ERROR state when this function is called, the
38157 ** contents of the pager cache are discarded before switching back to
38158 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
38159 ** or not, any journal file left in the file-system will be treated
38160 ** as a hot-journal and rolled back the next time a read-transaction
38161 ** is opened (by this or by any other connection).
38163 static void pager_unlock(Pager *pPager){
38165 assert( pPager->eState==PAGER_READER
38166 || pPager->eState==PAGER_OPEN
38167 || pPager->eState==PAGER_ERROR
38170 sqlite3BitvecDestroy(pPager->pInJournal);
38171 pPager->pInJournal = 0;
38172 releaseAllSavepoints(pPager);
38174 if( pagerUseWal(pPager) ){
38175 assert( !isOpen(pPager->jfd) );
38176 sqlite3WalEndReadTransaction(pPager->pWal);
38177 pPager->eState = PAGER_OPEN;
38178 }else if( !pPager->exclusiveMode ){
38179 int rc; /* Error code returned by pagerUnlockDb() */
38180 int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
38182 /* If the operating system support deletion of open files, then
38183 ** close the journal file when dropping the database lock. Otherwise
38184 ** another connection with journal_mode=delete might delete the file
38185 ** out from under us.
38187 assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
38188 assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
38189 assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
38190 assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
38191 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
38192 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
38193 if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
38194 || 1!=(pPager->journalMode & 5)
38196 sqlite3OsClose(pPager->jfd);
38199 /* If the pager is in the ERROR state and the call to unlock the database
38200 ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
38201 ** above the #define for UNKNOWN_LOCK for an explanation of why this
38202 ** is necessary.
38204 rc = pagerUnlockDb(pPager, NO_LOCK);
38205 if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
38206 pPager->eLock = UNKNOWN_LOCK;
38209 /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
38210 ** without clearing the error code. This is intentional - the error
38211 ** code is cleared and the cache reset in the block below.
38213 assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
38214 pPager->changeCountDone = 0;
38215 pPager->eState = PAGER_OPEN;
38218 /* If Pager.errCode is set, the contents of the pager cache cannot be
38219 ** trusted. Now that there are no outstanding references to the pager,
38220 ** it can safely move back to PAGER_OPEN state. This happens in both
38221 ** normal and exclusive-locking mode.
38223 if( pPager->errCode ){
38224 assert( !MEMDB );
38225 pager_reset(pPager);
38226 pPager->changeCountDone = pPager->tempFile;
38227 pPager->eState = PAGER_OPEN;
38228 pPager->errCode = SQLITE_OK;
38231 pPager->journalOff = 0;
38232 pPager->journalHdr = 0;
38233 pPager->setMaster = 0;
38237 ** This function is called whenever an IOERR or FULL error that requires
38238 ** the pager to transition into the ERROR state may ahve occurred.
38239 ** The first argument is a pointer to the pager structure, the second
38240 ** the error-code about to be returned by a pager API function. The
38241 ** value returned is a copy of the second argument to this function.
38243 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
38244 ** IOERR sub-codes, the pager enters the ERROR state and the error code
38245 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
38246 ** all major API calls on the Pager will immediately return Pager.errCode.
38248 ** The ERROR state indicates that the contents of the pager-cache
38249 ** cannot be trusted. This state can be cleared by completely discarding
38250 ** the contents of the pager-cache. If a transaction was active when
38251 ** the persistent error occurred, then the rollback journal may need
38252 ** to be replayed to restore the contents of the database file (as if
38253 ** it were a hot-journal).
38255 static int pager_error(Pager *pPager, int rc){
38256 int rc2 = rc & 0xff;
38257 assert( rc==SQLITE_OK || !MEMDB );
38258 assert(
38259 pPager->errCode==SQLITE_FULL ||
38260 pPager->errCode==SQLITE_OK ||
38261 (pPager->errCode & 0xff)==SQLITE_IOERR
38263 if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
38264 pPager->errCode = rc;
38265 pPager->eState = PAGER_ERROR;
38267 return rc;
38271 ** This routine ends a transaction. A transaction is usually ended by
38272 ** either a COMMIT or a ROLLBACK operation. This routine may be called
38273 ** after rollback of a hot-journal, or if an error occurs while opening
38274 ** the journal file or writing the very first journal-header of a
38275 ** database transaction.
38277 ** This routine is never called in PAGER_ERROR state. If it is called
38278 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
38279 ** exclusive than a RESERVED lock, it is a no-op.
38281 ** Otherwise, any active savepoints are released.
38283 ** If the journal file is open, then it is "finalized". Once a journal
38284 ** file has been finalized it is not possible to use it to roll back a
38285 ** transaction. Nor will it be considered to be a hot-journal by this
38286 ** or any other database connection. Exactly how a journal is finalized
38287 ** depends on whether or not the pager is running in exclusive mode and
38288 ** the current journal-mode (Pager.journalMode value), as follows:
38290 ** journalMode==MEMORY
38291 ** Journal file descriptor is simply closed. This destroys an
38292 ** in-memory journal.
38294 ** journalMode==TRUNCATE
38295 ** Journal file is truncated to zero bytes in size.
38297 ** journalMode==PERSIST
38298 ** The first 28 bytes of the journal file are zeroed. This invalidates
38299 ** the first journal header in the file, and hence the entire journal
38300 ** file. An invalid journal file cannot be rolled back.
38302 ** journalMode==DELETE
38303 ** The journal file is closed and deleted using sqlite3OsDelete().
38305 ** If the pager is running in exclusive mode, this method of finalizing
38306 ** the journal file is never used. Instead, if the journalMode is
38307 ** DELETE and the pager is in exclusive mode, the method described under
38308 ** journalMode==PERSIST is used instead.
38310 ** After the journal is finalized, the pager moves to PAGER_READER state.
38311 ** If running in non-exclusive rollback mode, the lock on the file is
38312 ** downgraded to a SHARED_LOCK.
38314 ** SQLITE_OK is returned if no error occurs. If an error occurs during
38315 ** any of the IO operations to finalize the journal file or unlock the
38316 ** database then the IO error code is returned to the user. If the
38317 ** operation to finalize the journal file fails, then the code still
38318 ** tries to unlock the database file if not in exclusive mode. If the
38319 ** unlock operation fails as well, then the first error code related
38320 ** to the first error encountered (the journal finalization one) is
38321 ** returned.
38323 static int pager_end_transaction(Pager *pPager, int hasMaster){
38324 int rc = SQLITE_OK; /* Error code from journal finalization operation */
38325 int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
38327 /* Do nothing if the pager does not have an open write transaction
38328 ** or at least a RESERVED lock. This function may be called when there
38329 ** is no write-transaction active but a RESERVED or greater lock is
38330 ** held under two circumstances:
38332 ** 1. After a successful hot-journal rollback, it is called with
38333 ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
38335 ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
38336 ** lock switches back to locking_mode=normal and then executes a
38337 ** read-transaction, this function is called with eState==PAGER_READER
38338 ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
38340 assert( assert_pager_state(pPager) );
38341 assert( pPager->eState!=PAGER_ERROR );
38342 if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
38343 return SQLITE_OK;
38346 releaseAllSavepoints(pPager);
38347 assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
38348 if( isOpen(pPager->jfd) ){
38349 assert( !pagerUseWal(pPager) );
38351 /* Finalize the journal file. */
38352 if( sqlite3IsMemJournal(pPager->jfd) ){
38353 assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
38354 sqlite3OsClose(pPager->jfd);
38355 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
38356 if( pPager->journalOff==0 ){
38357 rc = SQLITE_OK;
38358 }else{
38359 rc = sqlite3OsTruncate(pPager->jfd, 0);
38361 pPager->journalOff = 0;
38362 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
38363 || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
38365 rc = zeroJournalHdr(pPager, hasMaster);
38366 pPager->journalOff = 0;
38367 }else{
38368 /* This branch may be executed with Pager.journalMode==MEMORY if
38369 ** a hot-journal was just rolled back. In this case the journal
38370 ** file should be closed and deleted. If this connection writes to
38371 ** the database file, it will do so using an in-memory journal.
38373 assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
38374 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
38375 || pPager->journalMode==PAGER_JOURNALMODE_WAL
38377 sqlite3OsClose(pPager->jfd);
38378 if( !pPager->tempFile ){
38379 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
38384 #ifdef SQLITE_CHECK_PAGES
38385 sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
38386 if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
38387 PgHdr *p = pager_lookup(pPager, 1);
38388 if( p ){
38389 p->pageHash = 0;
38390 sqlite3PagerUnref(p);
38393 #endif
38395 sqlite3BitvecDestroy(pPager->pInJournal);
38396 pPager->pInJournal = 0;
38397 pPager->nRec = 0;
38398 sqlite3PcacheCleanAll(pPager->pPCache);
38399 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
38401 if( pagerUseWal(pPager) ){
38402 /* Drop the WAL write-lock, if any. Also, if the connection was in
38403 ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
38404 ** lock held on the database file.
38406 rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
38407 assert( rc2==SQLITE_OK );
38409 if( !pPager->exclusiveMode
38410 && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
38412 rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
38413 pPager->changeCountDone = 0;
38415 pPager->eState = PAGER_READER;
38416 pPager->setMaster = 0;
38418 return (rc==SQLITE_OK?rc2:rc);
38422 ** Execute a rollback if a transaction is active and unlock the
38423 ** database file.
38425 ** If the pager has already entered the ERROR state, do not attempt
38426 ** the rollback at this time. Instead, pager_unlock() is called. The
38427 ** call to pager_unlock() will discard all in-memory pages, unlock
38428 ** the database file and move the pager back to OPEN state. If this
38429 ** means that there is a hot-journal left in the file-system, the next
38430 ** connection to obtain a shared lock on the pager (which may be this one)
38431 ** will roll it back.
38433 ** If the pager has not already entered the ERROR state, but an IO or
38434 ** malloc error occurs during a rollback, then this will itself cause
38435 ** the pager to enter the ERROR state. Which will be cleared by the
38436 ** call to pager_unlock(), as described above.
38438 static void pagerUnlockAndRollback(Pager *pPager){
38439 if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
38440 assert( assert_pager_state(pPager) );
38441 if( pPager->eState>=PAGER_WRITER_LOCKED ){
38442 sqlite3BeginBenignMalloc();
38443 sqlite3PagerRollback(pPager);
38444 sqlite3EndBenignMalloc();
38445 }else if( !pPager->exclusiveMode ){
38446 assert( pPager->eState==PAGER_READER );
38447 pager_end_transaction(pPager, 0);
38450 pager_unlock(pPager);
38454 ** Parameter aData must point to a buffer of pPager->pageSize bytes
38455 ** of data. Compute and return a checksum based ont the contents of the
38456 ** page of data and the current value of pPager->cksumInit.
38458 ** This is not a real checksum. It is really just the sum of the
38459 ** random initial value (pPager->cksumInit) and every 200th byte
38460 ** of the page data, starting with byte offset (pPager->pageSize%200).
38461 ** Each byte is interpreted as an 8-bit unsigned integer.
38463 ** Changing the formula used to compute this checksum results in an
38464 ** incompatible journal file format.
38466 ** If journal corruption occurs due to a power failure, the most likely
38467 ** scenario is that one end or the other of the record will be changed.
38468 ** It is much less likely that the two ends of the journal record will be
38469 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
38470 ** though fast and simple, catches the mostly likely kind of corruption.
38472 static u32 pager_cksum(Pager *pPager, const u8 *aData){
38473 u32 cksum = pPager->cksumInit; /* Checksum value to return */
38474 int i = pPager->pageSize-200; /* Loop counter */
38475 while( i>0 ){
38476 cksum += aData[i];
38477 i -= 200;
38479 return cksum;
38483 ** Report the current page size and number of reserved bytes back
38484 ** to the codec.
38486 #ifdef SQLITE_HAS_CODEC
38487 static void pagerReportSize(Pager *pPager){
38488 if( pPager->xCodecSizeChng ){
38489 pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
38490 (int)pPager->nReserve);
38493 #else
38494 # define pagerReportSize(X) /* No-op if we do not support a codec */
38495 #endif
38498 ** Read a single page from either the journal file (if isMainJrnl==1) or
38499 ** from the sub-journal (if isMainJrnl==0) and playback that page.
38500 ** The page begins at offset *pOffset into the file. The *pOffset
38501 ** value is increased to the start of the next page in the journal.
38503 ** The main rollback journal uses checksums - the statement journal does
38504 ** not.
38506 ** If the page number of the page record read from the (sub-)journal file
38507 ** is greater than the current value of Pager.dbSize, then playback is
38508 ** skipped and SQLITE_OK is returned.
38510 ** If pDone is not NULL, then it is a record of pages that have already
38511 ** been played back. If the page at *pOffset has already been played back
38512 ** (if the corresponding pDone bit is set) then skip the playback.
38513 ** Make sure the pDone bit corresponding to the *pOffset page is set
38514 ** prior to returning.
38516 ** If the page record is successfully read from the (sub-)journal file
38517 ** and played back, then SQLITE_OK is returned. If an IO error occurs
38518 ** while reading the record from the (sub-)journal file or while writing
38519 ** to the database file, then the IO error code is returned. If data
38520 ** is successfully read from the (sub-)journal file but appears to be
38521 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
38522 ** two circumstances:
38524 ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
38525 ** * If the record is being rolled back from the main journal file
38526 ** and the checksum field does not match the record content.
38528 ** Neither of these two scenarios are possible during a savepoint rollback.
38530 ** If this is a savepoint rollback, then memory may have to be dynamically
38531 ** allocated by this function. If this is the case and an allocation fails,
38532 ** SQLITE_NOMEM is returned.
38534 static int pager_playback_one_page(
38535 Pager *pPager, /* The pager being played back */
38536 i64 *pOffset, /* Offset of record to playback */
38537 Bitvec *pDone, /* Bitvec of pages already played back */
38538 int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
38539 int isSavepnt /* True for a savepoint rollback */
38541 int rc;
38542 PgHdr *pPg; /* An existing page in the cache */
38543 Pgno pgno; /* The page number of a page in journal */
38544 u32 cksum; /* Checksum used for sanity checking */
38545 char *aData; /* Temporary storage for the page */
38546 sqlite3_file *jfd; /* The file descriptor for the journal file */
38547 int isSynced; /* True if journal page is synced */
38549 assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
38550 assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
38551 assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
38552 assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
38554 aData = pPager->pTmpSpace;
38555 assert( aData ); /* Temp storage must have already been allocated */
38556 assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
38558 /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
38559 ** or savepoint rollback done at the request of the caller) or this is
38560 ** a hot-journal rollback. If it is a hot-journal rollback, the pager
38561 ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
38562 ** only reads from the main journal, not the sub-journal.
38564 assert( pPager->eState>=PAGER_WRITER_CACHEMOD
38565 || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
38567 assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
38569 /* Read the page number and page data from the journal or sub-journal
38570 ** file. Return an error code to the caller if an IO error occurs.
38572 jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
38573 rc = read32bits(jfd, *pOffset, &pgno);
38574 if( rc!=SQLITE_OK ) return rc;
38575 rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
38576 if( rc!=SQLITE_OK ) return rc;
38577 *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
38579 /* Sanity checking on the page. This is more important that I originally
38580 ** thought. If a power failure occurs while the journal is being written,
38581 ** it could cause invalid data to be written into the journal. We need to
38582 ** detect this invalid data (with high probability) and ignore it.
38584 if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
38585 assert( !isSavepnt );
38586 return SQLITE_DONE;
38588 if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
38589 return SQLITE_OK;
38591 if( isMainJrnl ){
38592 rc = read32bits(jfd, (*pOffset)-4, &cksum);
38593 if( rc ) return rc;
38594 if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
38595 return SQLITE_DONE;
38599 /* If this page has already been played by before during the current
38600 ** rollback, then don't bother to play it back again.
38602 if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
38603 return rc;
38606 /* When playing back page 1, restore the nReserve setting
38608 if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
38609 pPager->nReserve = ((u8*)aData)[20];
38610 pagerReportSize(pPager);
38613 /* If the pager is in CACHEMOD state, then there must be a copy of this
38614 ** page in the pager cache. In this case just update the pager cache,
38615 ** not the database file. The page is left marked dirty in this case.
38617 ** An exception to the above rule: If the database is in no-sync mode
38618 ** and a page is moved during an incremental vacuum then the page may
38619 ** not be in the pager cache. Later: if a malloc() or IO error occurs
38620 ** during a Movepage() call, then the page may not be in the cache
38621 ** either. So the condition described in the above paragraph is not
38622 ** assert()able.
38624 ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
38625 ** pager cache if it exists and the main file. The page is then marked
38626 ** not dirty. Since this code is only executed in PAGER_OPEN state for
38627 ** a hot-journal rollback, it is guaranteed that the page-cache is empty
38628 ** if the pager is in OPEN state.
38630 ** Ticket #1171: The statement journal might contain page content that is
38631 ** different from the page content at the start of the transaction.
38632 ** This occurs when a page is changed prior to the start of a statement
38633 ** then changed again within the statement. When rolling back such a
38634 ** statement we must not write to the original database unless we know
38635 ** for certain that original page contents are synced into the main rollback
38636 ** journal. Otherwise, a power loss might leave modified data in the
38637 ** database file without an entry in the rollback journal that can
38638 ** restore the database to its original form. Two conditions must be
38639 ** met before writing to the database files. (1) the database must be
38640 ** locked. (2) we know that the original page content is fully synced
38641 ** in the main journal either because the page is not in cache or else
38642 ** the page is marked as needSync==0.
38644 ** 2008-04-14: When attempting to vacuum a corrupt database file, it
38645 ** is possible to fail a statement on a database that does not yet exist.
38646 ** Do not attempt to write if database file has never been opened.
38648 if( pagerUseWal(pPager) ){
38649 pPg = 0;
38650 }else{
38651 pPg = pager_lookup(pPager, pgno);
38653 assert( pPg || !MEMDB );
38654 assert( pPager->eState!=PAGER_OPEN || pPg==0 );
38655 PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
38656 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
38657 (isMainJrnl?"main-journal":"sub-journal")
38659 if( isMainJrnl ){
38660 isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
38661 }else{
38662 isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
38664 if( isOpen(pPager->fd)
38665 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
38666 && isSynced
38668 i64 ofst = (pgno-1)*(i64)pPager->pageSize;
38669 testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
38670 assert( !pagerUseWal(pPager) );
38671 rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
38672 if( pgno>pPager->dbFileSize ){
38673 pPager->dbFileSize = pgno;
38675 if( pPager->pBackup ){
38676 CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
38677 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
38678 CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
38680 }else if( !isMainJrnl && pPg==0 ){
38681 /* If this is a rollback of a savepoint and data was not written to
38682 ** the database and the page is not in-memory, there is a potential
38683 ** problem. When the page is next fetched by the b-tree layer, it
38684 ** will be read from the database file, which may or may not be
38685 ** current.
38687 ** There are a couple of different ways this can happen. All are quite
38688 ** obscure. When running in synchronous mode, this can only happen
38689 ** if the page is on the free-list at the start of the transaction, then
38690 ** populated, then moved using sqlite3PagerMovepage().
38692 ** The solution is to add an in-memory page to the cache containing
38693 ** the data just read from the sub-journal. Mark the page as dirty
38694 ** and if the pager requires a journal-sync, then mark the page as
38695 ** requiring a journal-sync before it is written.
38697 assert( isSavepnt );
38698 assert( pPager->doNotSpill==0 );
38699 pPager->doNotSpill++;
38700 rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
38701 assert( pPager->doNotSpill==1 );
38702 pPager->doNotSpill--;
38703 if( rc!=SQLITE_OK ) return rc;
38704 pPg->flags &= ~PGHDR_NEED_READ;
38705 sqlite3PcacheMakeDirty(pPg);
38707 if( pPg ){
38708 /* No page should ever be explicitly rolled back that is in use, except
38709 ** for page 1 which is held in use in order to keep the lock on the
38710 ** database active. However such a page may be rolled back as a result
38711 ** of an internal error resulting in an automatic call to
38712 ** sqlite3PagerRollback().
38714 void *pData;
38715 pData = pPg->pData;
38716 memcpy(pData, (u8*)aData, pPager->pageSize);
38717 pPager->xReiniter(pPg);
38718 if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
38719 /* If the contents of this page were just restored from the main
38720 ** journal file, then its content must be as they were when the
38721 ** transaction was first opened. In this case we can mark the page
38722 ** as clean, since there will be no need to write it out to the
38723 ** database.
38725 ** There is one exception to this rule. If the page is being rolled
38726 ** back as part of a savepoint (or statement) rollback from an
38727 ** unsynced portion of the main journal file, then it is not safe
38728 ** to mark the page as clean. This is because marking the page as
38729 ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
38730 ** already in the journal file (recorded in Pager.pInJournal) and
38731 ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
38732 ** again within this transaction, it will be marked as dirty but
38733 ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
38734 ** be written out into the database file before its journal file
38735 ** segment is synced. If a crash occurs during or following this,
38736 ** database corruption may ensue.
38738 assert( !pagerUseWal(pPager) );
38739 sqlite3PcacheMakeClean(pPg);
38741 pager_set_pagehash(pPg);
38743 /* If this was page 1, then restore the value of Pager.dbFileVers.
38744 ** Do this before any decoding. */
38745 if( pgno==1 ){
38746 memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
38749 /* Decode the page just read from disk */
38750 CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
38751 sqlite3PcacheRelease(pPg);
38753 return rc;
38757 ** Parameter zMaster is the name of a master journal file. A single journal
38758 ** file that referred to the master journal file has just been rolled back.
38759 ** This routine checks if it is possible to delete the master journal file,
38760 ** and does so if it is.
38762 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
38763 ** available for use within this function.
38765 ** When a master journal file is created, it is populated with the names
38766 ** of all of its child journals, one after another, formatted as utf-8
38767 ** encoded text. The end of each child journal file is marked with a
38768 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
38769 ** file for a transaction involving two databases might be:
38771 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
38773 ** A master journal file may only be deleted once all of its child
38774 ** journals have been rolled back.
38776 ** This function reads the contents of the master-journal file into
38777 ** memory and loops through each of the child journal names. For
38778 ** each child journal, it checks if:
38780 ** * if the child journal exists, and if so
38781 ** * if the child journal contains a reference to master journal
38782 ** file zMaster
38784 ** If a child journal can be found that matches both of the criteria
38785 ** above, this function returns without doing anything. Otherwise, if
38786 ** no such child journal can be found, file zMaster is deleted from
38787 ** the file-system using sqlite3OsDelete().
38789 ** If an IO error within this function, an error code is returned. This
38790 ** function allocates memory by calling sqlite3Malloc(). If an allocation
38791 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
38792 ** occur, SQLITE_OK is returned.
38794 ** TODO: This function allocates a single block of memory to load
38795 ** the entire contents of the master journal file. This could be
38796 ** a couple of kilobytes or so - potentially larger than the page
38797 ** size.
38799 static int pager_delmaster(Pager *pPager, const char *zMaster){
38800 sqlite3_vfs *pVfs = pPager->pVfs;
38801 int rc; /* Return code */
38802 sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
38803 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
38804 char *zMasterJournal = 0; /* Contents of master journal file */
38805 i64 nMasterJournal; /* Size of master journal file */
38806 char *zJournal; /* Pointer to one journal within MJ file */
38807 char *zMasterPtr; /* Space to hold MJ filename from a journal file */
38808 int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
38810 /* Allocate space for both the pJournal and pMaster file descriptors.
38811 ** If successful, open the master journal file for reading.
38813 pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
38814 pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
38815 if( !pMaster ){
38816 rc = SQLITE_NOMEM;
38817 }else{
38818 const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
38819 rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
38821 if( rc!=SQLITE_OK ) goto delmaster_out;
38823 /* Load the entire master journal file into space obtained from
38824 ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
38825 ** sufficient space (in zMasterPtr) to hold the names of master
38826 ** journal files extracted from regular rollback-journals.
38828 rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
38829 if( rc!=SQLITE_OK ) goto delmaster_out;
38830 nMasterPtr = pVfs->mxPathname+1;
38831 zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
38832 if( !zMasterJournal ){
38833 rc = SQLITE_NOMEM;
38834 goto delmaster_out;
38836 zMasterPtr = &zMasterJournal[nMasterJournal+1];
38837 rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
38838 if( rc!=SQLITE_OK ) goto delmaster_out;
38839 zMasterJournal[nMasterJournal] = 0;
38841 zJournal = zMasterJournal;
38842 while( (zJournal-zMasterJournal)<nMasterJournal ){
38843 int exists;
38844 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
38845 if( rc!=SQLITE_OK ){
38846 goto delmaster_out;
38848 if( exists ){
38849 /* One of the journals pointed to by the master journal exists.
38850 ** Open it and check if it points at the master journal. If
38851 ** so, return without deleting the master journal file.
38853 int c;
38854 int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
38855 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
38856 if( rc!=SQLITE_OK ){
38857 goto delmaster_out;
38860 rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
38861 sqlite3OsClose(pJournal);
38862 if( rc!=SQLITE_OK ){
38863 goto delmaster_out;
38866 c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
38867 if( c ){
38868 /* We have a match. Do not delete the master journal file. */
38869 goto delmaster_out;
38872 zJournal += (sqlite3Strlen30(zJournal)+1);
38875 sqlite3OsClose(pMaster);
38876 rc = sqlite3OsDelete(pVfs, zMaster, 0);
38878 delmaster_out:
38879 sqlite3_free(zMasterJournal);
38880 if( pMaster ){
38881 sqlite3OsClose(pMaster);
38882 assert( !isOpen(pJournal) );
38883 sqlite3_free(pMaster);
38885 return rc;
38890 ** This function is used to change the actual size of the database
38891 ** file in the file-system. This only happens when committing a transaction,
38892 ** or rolling back a transaction (including rolling back a hot-journal).
38894 ** If the main database file is not open, or the pager is not in either
38895 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
38896 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
38897 ** If the file on disk is currently larger than nPage pages, then use the VFS
38898 ** xTruncate() method to truncate it.
38900 ** Or, it might might be the case that the file on disk is smaller than
38901 ** nPage pages. Some operating system implementations can get confused if
38902 ** you try to truncate a file to some size that is larger than it
38903 ** currently is, so detect this case and write a single zero byte to
38904 ** the end of the new file instead.
38906 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
38907 ** the database file, return the error code to the caller.
38909 static int pager_truncate(Pager *pPager, Pgno nPage){
38910 int rc = SQLITE_OK;
38911 assert( pPager->eState!=PAGER_ERROR );
38912 assert( pPager->eState!=PAGER_READER );
38914 if( isOpen(pPager->fd)
38915 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
38917 i64 currentSize, newSize;
38918 int szPage = pPager->pageSize;
38919 assert( pPager->eLock==EXCLUSIVE_LOCK );
38920 /* TODO: Is it safe to use Pager.dbFileSize here? */
38921 rc = sqlite3OsFileSize(pPager->fd, &currentSize);
38922 newSize = szPage*(i64)nPage;
38923 if( rc==SQLITE_OK && currentSize!=newSize ){
38924 if( currentSize>newSize ){
38925 rc = sqlite3OsTruncate(pPager->fd, newSize);
38926 }else{
38927 char *pTmp = pPager->pTmpSpace;
38928 memset(pTmp, 0, szPage);
38929 testcase( (newSize-szPage) < currentSize );
38930 testcase( (newSize-szPage) == currentSize );
38931 testcase( (newSize-szPage) > currentSize );
38932 rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
38934 if( rc==SQLITE_OK ){
38935 pPager->dbFileSize = nPage;
38939 return rc;
38943 ** Set the value of the Pager.sectorSize variable for the given
38944 ** pager based on the value returned by the xSectorSize method
38945 ** of the open database file. The sector size will be used used
38946 ** to determine the size and alignment of journal header and
38947 ** master journal pointers within created journal files.
38949 ** For temporary files the effective sector size is always 512 bytes.
38951 ** Otherwise, for non-temporary files, the effective sector size is
38952 ** the value returned by the xSectorSize() method rounded up to 32 if
38953 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
38954 ** is greater than MAX_SECTOR_SIZE.
38956 static void setSectorSize(Pager *pPager){
38957 assert( isOpen(pPager->fd) || pPager->tempFile );
38959 if( !pPager->tempFile ){
38960 /* Sector size doesn't matter for temporary files. Also, the file
38961 ** may not have been opened yet, in which case the OsSectorSize()
38962 ** call will segfault.
38964 pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
38966 if( pPager->sectorSize<32 ){
38967 pPager->sectorSize = 512;
38969 if( pPager->sectorSize>MAX_SECTOR_SIZE ){
38970 assert( MAX_SECTOR_SIZE>=512 );
38971 pPager->sectorSize = MAX_SECTOR_SIZE;
38976 ** Playback the journal and thus restore the database file to
38977 ** the state it was in before we started making changes.
38979 ** The journal file format is as follows:
38981 ** (1) 8 byte prefix. A copy of aJournalMagic[].
38982 ** (2) 4 byte big-endian integer which is the number of valid page records
38983 ** in the journal. If this value is 0xffffffff, then compute the
38984 ** number of page records from the journal size.
38985 ** (3) 4 byte big-endian integer which is the initial value for the
38986 ** sanity checksum.
38987 ** (4) 4 byte integer which is the number of pages to truncate the
38988 ** database to during a rollback.
38989 ** (5) 4 byte big-endian integer which is the sector size. The header
38990 ** is this many bytes in size.
38991 ** (6) 4 byte big-endian integer which is the page size.
38992 ** (7) zero padding out to the next sector size.
38993 ** (8) Zero or more pages instances, each as follows:
38994 ** + 4 byte page number.
38995 ** + pPager->pageSize bytes of data.
38996 ** + 4 byte checksum
38998 ** When we speak of the journal header, we mean the first 7 items above.
38999 ** Each entry in the journal is an instance of the 8th item.
39001 ** Call the value from the second bullet "nRec". nRec is the number of
39002 ** valid page entries in the journal. In most cases, you can compute the
39003 ** value of nRec from the size of the journal file. But if a power
39004 ** failure occurred while the journal was being written, it could be the
39005 ** case that the size of the journal file had already been increased but
39006 ** the extra entries had not yet made it safely to disk. In such a case,
39007 ** the value of nRec computed from the file size would be too large. For
39008 ** that reason, we always use the nRec value in the header.
39010 ** If the nRec value is 0xffffffff it means that nRec should be computed
39011 ** from the file size. This value is used when the user selects the
39012 ** no-sync option for the journal. A power failure could lead to corruption
39013 ** in this case. But for things like temporary table (which will be
39014 ** deleted when the power is restored) we don't care.
39016 ** If the file opened as the journal file is not a well-formed
39017 ** journal file then all pages up to the first corrupted page are rolled
39018 ** back (or no pages if the journal header is corrupted). The journal file
39019 ** is then deleted and SQLITE_OK returned, just as if no corruption had
39020 ** been encountered.
39022 ** If an I/O or malloc() error occurs, the journal-file is not deleted
39023 ** and an error code is returned.
39025 ** The isHot parameter indicates that we are trying to rollback a journal
39026 ** that might be a hot journal. Or, it could be that the journal is
39027 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
39028 ** If the journal really is hot, reset the pager cache prior rolling
39029 ** back any content. If the journal is merely persistent, no reset is
39030 ** needed.
39032 static int pager_playback(Pager *pPager, int isHot){
39033 sqlite3_vfs *pVfs = pPager->pVfs;
39034 i64 szJ; /* Size of the journal file in bytes */
39035 u32 nRec; /* Number of Records in the journal */
39036 u32 u; /* Unsigned loop counter */
39037 Pgno mxPg = 0; /* Size of the original file in pages */
39038 int rc; /* Result code of a subroutine */
39039 int res = 1; /* Value returned by sqlite3OsAccess() */
39040 char *zMaster = 0; /* Name of master journal file if any */
39041 int needPagerReset; /* True to reset page prior to first page rollback */
39043 /* Figure out how many records are in the journal. Abort early if
39044 ** the journal is empty.
39046 assert( isOpen(pPager->jfd) );
39047 rc = sqlite3OsFileSize(pPager->jfd, &szJ);
39048 if( rc!=SQLITE_OK ){
39049 goto end_playback;
39052 /* Read the master journal name from the journal, if it is present.
39053 ** If a master journal file name is specified, but the file is not
39054 ** present on disk, then the journal is not hot and does not need to be
39055 ** played back.
39057 ** TODO: Technically the following is an error because it assumes that
39058 ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
39059 ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
39060 ** mxPathname is 512, which is the same as the minimum allowable value
39061 ** for pageSize.
39063 zMaster = pPager->pTmpSpace;
39064 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39065 if( rc==SQLITE_OK && zMaster[0] ){
39066 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
39068 zMaster = 0;
39069 if( rc!=SQLITE_OK || !res ){
39070 goto end_playback;
39072 pPager->journalOff = 0;
39073 needPagerReset = isHot;
39075 /* This loop terminates either when a readJournalHdr() or
39076 ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
39077 ** occurs.
39079 while( 1 ){
39080 /* Read the next journal header from the journal file. If there are
39081 ** not enough bytes left in the journal file for a complete header, or
39082 ** it is corrupted, then a process must have failed while writing it.
39083 ** This indicates nothing more needs to be rolled back.
39085 rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
39086 if( rc!=SQLITE_OK ){
39087 if( rc==SQLITE_DONE ){
39088 rc = SQLITE_OK;
39090 goto end_playback;
39093 /* If nRec is 0xffffffff, then this journal was created by a process
39094 ** working in no-sync mode. This means that the rest of the journal
39095 ** file consists of pages, there are no more journal headers. Compute
39096 ** the value of nRec based on this assumption.
39098 if( nRec==0xffffffff ){
39099 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
39100 nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
39103 /* If nRec is 0 and this rollback is of a transaction created by this
39104 ** process and if this is the final header in the journal, then it means
39105 ** that this part of the journal was being filled but has not yet been
39106 ** synced to disk. Compute the number of pages based on the remaining
39107 ** size of the file.
39109 ** The third term of the test was added to fix ticket #2565.
39110 ** When rolling back a hot journal, nRec==0 always means that the next
39111 ** chunk of the journal contains zero pages to be rolled back. But
39112 ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
39113 ** the journal, it means that the journal might contain additional
39114 ** pages that need to be rolled back and that the number of pages
39115 ** should be computed based on the journal file size.
39117 if( nRec==0 && !isHot &&
39118 pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
39119 nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
39122 /* If this is the first header read from the journal, truncate the
39123 ** database file back to its original size.
39125 if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
39126 rc = pager_truncate(pPager, mxPg);
39127 if( rc!=SQLITE_OK ){
39128 goto end_playback;
39130 pPager->dbSize = mxPg;
39133 /* Copy original pages out of the journal and back into the
39134 ** database file and/or page cache.
39136 for(u=0; u<nRec; u++){
39137 if( needPagerReset ){
39138 pager_reset(pPager);
39139 needPagerReset = 0;
39141 rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
39142 if( rc!=SQLITE_OK ){
39143 if( rc==SQLITE_DONE ){
39144 rc = SQLITE_OK;
39145 pPager->journalOff = szJ;
39146 break;
39147 }else if( rc==SQLITE_IOERR_SHORT_READ ){
39148 /* If the journal has been truncated, simply stop reading and
39149 ** processing the journal. This might happen if the journal was
39150 ** not completely written and synced prior to a crash. In that
39151 ** case, the database should have never been written in the
39152 ** first place so it is OK to simply abandon the rollback. */
39153 rc = SQLITE_OK;
39154 goto end_playback;
39155 }else{
39156 /* If we are unable to rollback, quit and return the error
39157 ** code. This will cause the pager to enter the error state
39158 ** so that no further harm will be done. Perhaps the next
39159 ** process to come along will be able to rollback the database.
39161 goto end_playback;
39166 /*NOTREACHED*/
39167 assert( 0 );
39169 end_playback:
39170 /* Following a rollback, the database file should be back in its original
39171 ** state prior to the start of the transaction, so invoke the
39172 ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
39173 ** assertion that the transaction counter was modified.
39175 assert(
39176 pPager->fd->pMethods==0 ||
39177 sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
39180 /* If this playback is happening automatically as a result of an IO or
39181 ** malloc error that occurred after the change-counter was updated but
39182 ** before the transaction was committed, then the change-counter
39183 ** modification may just have been reverted. If this happens in exclusive
39184 ** mode, then subsequent transactions performed by the connection will not
39185 ** update the change-counter at all. This may lead to cache inconsistency
39186 ** problems for other processes at some point in the future. So, just
39187 ** in case this has happened, clear the changeCountDone flag now.
39189 pPager->changeCountDone = pPager->tempFile;
39191 if( rc==SQLITE_OK ){
39192 zMaster = pPager->pTmpSpace;
39193 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39194 testcase( rc!=SQLITE_OK );
39196 if( rc==SQLITE_OK
39197 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39199 rc = sqlite3PagerSync(pPager);
39201 if( rc==SQLITE_OK ){
39202 rc = pager_end_transaction(pPager, zMaster[0]!='\0');
39203 testcase( rc!=SQLITE_OK );
39205 if( rc==SQLITE_OK && zMaster[0] && res ){
39206 /* If there was a master journal and this routine will return success,
39207 ** see if it is possible to delete the master journal.
39209 rc = pager_delmaster(pPager, zMaster);
39210 testcase( rc!=SQLITE_OK );
39213 /* The Pager.sectorSize variable may have been updated while rolling
39214 ** back a journal created by a process with a different sector size
39215 ** value. Reset it to the correct value for this process.
39217 setSectorSize(pPager);
39218 return rc;
39223 ** Read the content for page pPg out of the database file and into
39224 ** pPg->pData. A shared lock or greater must be held on the database
39225 ** file before this function is called.
39227 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
39228 ** the value read from the database file.
39230 ** If an IO error occurs, then the IO error is returned to the caller.
39231 ** Otherwise, SQLITE_OK is returned.
39233 static int readDbPage(PgHdr *pPg){
39234 Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
39235 Pgno pgno = pPg->pgno; /* Page number to read */
39236 int rc = SQLITE_OK; /* Return code */
39237 int isInWal = 0; /* True if page is in log file */
39238 int pgsz = pPager->pageSize; /* Number of bytes to read */
39240 assert( pPager->eState>=PAGER_READER && !MEMDB );
39241 assert( isOpen(pPager->fd) );
39243 if( NEVER(!isOpen(pPager->fd)) ){
39244 assert( pPager->tempFile );
39245 memset(pPg->pData, 0, pPager->pageSize);
39246 return SQLITE_OK;
39249 if( pagerUseWal(pPager) ){
39250 /* Try to pull the page from the write-ahead log. */
39251 rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
39253 if( rc==SQLITE_OK && !isInWal ){
39254 i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
39255 rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
39256 if( rc==SQLITE_IOERR_SHORT_READ ){
39257 rc = SQLITE_OK;
39261 if( pgno==1 ){
39262 if( rc ){
39263 /* If the read is unsuccessful, set the dbFileVers[] to something
39264 ** that will never be a valid file version. dbFileVers[] is a copy
39265 ** of bytes 24..39 of the database. Bytes 28..31 should always be
39266 ** zero or the size of the database in page. Bytes 32..35 and 35..39
39267 ** should be page numbers which are never 0xffffffff. So filling
39268 ** pPager->dbFileVers[] with all 0xff bytes should suffice.
39270 ** For an encrypted database, the situation is more complex: bytes
39271 ** 24..39 of the database are white noise. But the probability of
39272 ** white noising equaling 16 bytes of 0xff is vanishingly small so
39273 ** we should still be ok.
39275 memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
39276 }else{
39277 u8 *dbFileVers = &((u8*)pPg->pData)[24];
39278 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
39281 CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
39283 PAGER_INCR(sqlite3_pager_readdb_count);
39284 PAGER_INCR(pPager->nRead);
39285 IOTRACE(("PGIN %p %d\n", pPager, pgno));
39286 PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
39287 PAGERID(pPager), pgno, pager_pagehash(pPg)));
39289 return rc;
39293 ** Update the value of the change-counter at offsets 24 and 92 in
39294 ** the header and the sqlite version number at offset 96.
39296 ** This is an unconditional update. See also the pager_incr_changecounter()
39297 ** routine which only updates the change-counter if the update is actually
39298 ** needed, as determined by the pPager->changeCountDone state variable.
39300 static void pager_write_changecounter(PgHdr *pPg){
39301 u32 change_counter;
39303 /* Increment the value just read and write it back to byte 24. */
39304 change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
39305 put32bits(((char*)pPg->pData)+24, change_counter);
39307 /* Also store the SQLite version number in bytes 96..99 and in
39308 ** bytes 92..95 store the change counter for which the version number
39309 ** is valid. */
39310 put32bits(((char*)pPg->pData)+92, change_counter);
39311 put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
39314 #ifndef SQLITE_OMIT_WAL
39316 ** This function is invoked once for each page that has already been
39317 ** written into the log file when a WAL transaction is rolled back.
39318 ** Parameter iPg is the page number of said page. The pCtx argument
39319 ** is actually a pointer to the Pager structure.
39321 ** If page iPg is present in the cache, and has no outstanding references,
39322 ** it is discarded. Otherwise, if there are one or more outstanding
39323 ** references, the page content is reloaded from the database. If the
39324 ** attempt to reload content from the database is required and fails,
39325 ** return an SQLite error code. Otherwise, SQLITE_OK.
39327 static int pagerUndoCallback(void *pCtx, Pgno iPg){
39328 int rc = SQLITE_OK;
39329 Pager *pPager = (Pager *)pCtx;
39330 PgHdr *pPg;
39332 pPg = sqlite3PagerLookup(pPager, iPg);
39333 if( pPg ){
39334 if( sqlite3PcachePageRefcount(pPg)==1 ){
39335 sqlite3PcacheDrop(pPg);
39336 }else{
39337 rc = readDbPage(pPg);
39338 if( rc==SQLITE_OK ){
39339 pPager->xReiniter(pPg);
39341 sqlite3PagerUnref(pPg);
39345 /* Normally, if a transaction is rolled back, any backup processes are
39346 ** updated as data is copied out of the rollback journal and into the
39347 ** database. This is not generally possible with a WAL database, as
39348 ** rollback involves simply truncating the log file. Therefore, if one
39349 ** or more frames have already been written to the log (and therefore
39350 ** also copied into the backup databases) as part of this transaction,
39351 ** the backups must be restarted.
39353 sqlite3BackupRestart(pPager->pBackup);
39355 return rc;
39359 ** This function is called to rollback a transaction on a WAL database.
39361 static int pagerRollbackWal(Pager *pPager){
39362 int rc; /* Return Code */
39363 PgHdr *pList; /* List of dirty pages to revert */
39365 /* For all pages in the cache that are currently dirty or have already
39366 ** been written (but not committed) to the log file, do one of the
39367 ** following:
39369 ** + Discard the cached page (if refcount==0), or
39370 ** + Reload page content from the database (if refcount>0).
39372 pPager->dbSize = pPager->dbOrigSize;
39373 rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
39374 pList = sqlite3PcacheDirtyList(pPager->pPCache);
39375 while( pList && rc==SQLITE_OK ){
39376 PgHdr *pNext = pList->pDirty;
39377 rc = pagerUndoCallback((void *)pPager, pList->pgno);
39378 pList = pNext;
39381 return rc;
39385 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
39386 ** the contents of the list of pages headed by pList (connected by pDirty),
39387 ** this function notifies any active backup processes that the pages have
39388 ** changed.
39390 ** The list of pages passed into this routine is always sorted by page number.
39391 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
39393 static int pagerWalFrames(
39394 Pager *pPager, /* Pager object */
39395 PgHdr *pList, /* List of frames to log */
39396 Pgno nTruncate, /* Database size after this commit */
39397 int isCommit, /* True if this is a commit */
39398 int syncFlags /* Flags to pass to OsSync() (or 0) */
39400 int rc; /* Return code */
39401 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
39402 PgHdr *p; /* For looping over pages */
39403 #endif
39405 assert( pPager->pWal );
39406 #ifdef SQLITE_DEBUG
39407 /* Verify that the page list is in accending order */
39408 for(p=pList; p && p->pDirty; p=p->pDirty){
39409 assert( p->pgno < p->pDirty->pgno );
39411 #endif
39413 if( isCommit ){
39414 /* If a WAL transaction is being committed, there is no point in writing
39415 ** any pages with page numbers greater than nTruncate into the WAL file.
39416 ** They will never be read by any client. So remove them from the pDirty
39417 ** list here. */
39418 PgHdr *p;
39419 PgHdr **ppNext = &pList;
39420 for(p=pList; (*ppNext = p); p=p->pDirty){
39421 if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
39423 assert( pList );
39426 if( pList->pgno==1 ) pager_write_changecounter(pList);
39427 rc = sqlite3WalFrames(pPager->pWal,
39428 pPager->pageSize, pList, nTruncate, isCommit, syncFlags
39430 if( rc==SQLITE_OK && pPager->pBackup ){
39431 PgHdr *p;
39432 for(p=pList; p; p=p->pDirty){
39433 sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
39437 #ifdef SQLITE_CHECK_PAGES
39438 pList = sqlite3PcacheDirtyList(pPager->pPCache);
39439 for(p=pList; p; p=p->pDirty){
39440 pager_set_pagehash(p);
39442 #endif
39444 return rc;
39448 ** Begin a read transaction on the WAL.
39450 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
39451 ** makes a snapshot of the database at the current point in time and preserves
39452 ** that snapshot for use by the reader in spite of concurrently changes by
39453 ** other writers or checkpointers.
39455 static int pagerBeginReadTransaction(Pager *pPager){
39456 int rc; /* Return code */
39457 int changed = 0; /* True if cache must be reset */
39459 assert( pagerUseWal(pPager) );
39460 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
39462 /* sqlite3WalEndReadTransaction() was not called for the previous
39463 ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
39464 ** are in locking_mode=NORMAL and EndRead() was previously called,
39465 ** the duplicate call is harmless.
39467 sqlite3WalEndReadTransaction(pPager->pWal);
39469 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
39470 if( rc!=SQLITE_OK || changed ){
39471 pager_reset(pPager);
39474 return rc;
39476 #endif
39479 ** This function is called as part of the transition from PAGER_OPEN
39480 ** to PAGER_READER state to determine the size of the database file
39481 ** in pages (assuming the page size currently stored in Pager.pageSize).
39483 ** If no error occurs, SQLITE_OK is returned and the size of the database
39484 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
39485 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
39487 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
39488 Pgno nPage; /* Value to return via *pnPage */
39490 /* Query the WAL sub-system for the database size. The WalDbsize()
39491 ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
39492 ** if the database size is not available. The database size is not
39493 ** available from the WAL sub-system if the log file is empty or
39494 ** contains no valid committed transactions.
39496 assert( pPager->eState==PAGER_OPEN );
39497 assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39498 nPage = sqlite3WalDbsize(pPager->pWal);
39500 /* If the database size was not available from the WAL sub-system,
39501 ** determine it based on the size of the database file. If the size
39502 ** of the database file is not an integer multiple of the page-size,
39503 ** round down to the nearest page. Except, any file larger than 0
39504 ** bytes in size is considered to contain at least one page.
39506 if( nPage==0 ){
39507 i64 n = 0; /* Size of db file in bytes */
39508 assert( isOpen(pPager->fd) || pPager->tempFile );
39509 if( isOpen(pPager->fd) ){
39510 int rc = sqlite3OsFileSize(pPager->fd, &n);
39511 if( rc!=SQLITE_OK ){
39512 return rc;
39515 nPage = (Pgno)(n / pPager->pageSize);
39516 if( nPage==0 && n>0 ){
39517 nPage = 1;
39521 /* If the current number of pages in the file is greater than the
39522 ** configured maximum pager number, increase the allowed limit so
39523 ** that the file can be read.
39525 if( nPage>pPager->mxPgno ){
39526 pPager->mxPgno = (Pgno)nPage;
39529 *pnPage = nPage;
39530 return SQLITE_OK;
39533 #ifndef SQLITE_OMIT_WAL
39535 ** Check if the *-wal file that corresponds to the database opened by pPager
39536 ** exists if the database is not empy, or verify that the *-wal file does
39537 ** not exist (by deleting it) if the database file is empty.
39539 ** If the database is not empty and the *-wal file exists, open the pager
39540 ** in WAL mode. If the database is empty or if no *-wal file exists and
39541 ** if no error occurs, make sure Pager.journalMode is not set to
39542 ** PAGER_JOURNALMODE_WAL.
39544 ** Return SQLITE_OK or an error code.
39546 ** The caller must hold a SHARED lock on the database file to call this
39547 ** function. Because an EXCLUSIVE lock on the db file is required to delete
39548 ** a WAL on a none-empty database, this ensures there is no race condition
39549 ** between the xAccess() below and an xDelete() being executed by some
39550 ** other connection.
39552 static int pagerOpenWalIfPresent(Pager *pPager){
39553 int rc = SQLITE_OK;
39554 assert( pPager->eState==PAGER_OPEN );
39555 assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39557 if( !pPager->tempFile ){
39558 int isWal; /* True if WAL file exists */
39559 Pgno nPage; /* Size of the database file */
39561 rc = pagerPagecount(pPager, &nPage);
39562 if( rc ) return rc;
39563 if( nPage==0 ){
39564 rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
39565 isWal = 0;
39566 }else{
39567 rc = sqlite3OsAccess(
39568 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
39571 if( rc==SQLITE_OK ){
39572 if( isWal ){
39573 testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
39574 rc = sqlite3PagerOpenWal(pPager, 0);
39575 }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
39576 pPager->journalMode = PAGER_JOURNALMODE_DELETE;
39580 return rc;
39582 #endif
39585 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
39586 ** the entire master journal file. The case pSavepoint==NULL occurs when
39587 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
39588 ** savepoint.
39590 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
39591 ** being rolled back), then the rollback consists of up to three stages,
39592 ** performed in the order specified:
39594 ** * Pages are played back from the main journal starting at byte
39595 ** offset PagerSavepoint.iOffset and continuing to
39596 ** PagerSavepoint.iHdrOffset, or to the end of the main journal
39597 ** file if PagerSavepoint.iHdrOffset is zero.
39599 ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
39600 ** back starting from the journal header immediately following
39601 ** PagerSavepoint.iHdrOffset to the end of the main journal file.
39603 ** * Pages are then played back from the sub-journal file, starting
39604 ** with the PagerSavepoint.iSubRec and continuing to the end of
39605 ** the journal file.
39607 ** Throughout the rollback process, each time a page is rolled back, the
39608 ** corresponding bit is set in a bitvec structure (variable pDone in the
39609 ** implementation below). This is used to ensure that a page is only
39610 ** rolled back the first time it is encountered in either journal.
39612 ** If pSavepoint is NULL, then pages are only played back from the main
39613 ** journal file. There is no need for a bitvec in this case.
39615 ** In either case, before playback commences the Pager.dbSize variable
39616 ** is reset to the value that it held at the start of the savepoint
39617 ** (or transaction). No page with a page-number greater than this value
39618 ** is played back. If one is encountered it is simply skipped.
39620 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
39621 i64 szJ; /* Effective size of the main journal */
39622 i64 iHdrOff; /* End of first segment of main-journal records */
39623 int rc = SQLITE_OK; /* Return code */
39624 Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
39626 assert( pPager->eState!=PAGER_ERROR );
39627 assert( pPager->eState>=PAGER_WRITER_LOCKED );
39629 /* Allocate a bitvec to use to store the set of pages rolled back */
39630 if( pSavepoint ){
39631 pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
39632 if( !pDone ){
39633 return SQLITE_NOMEM;
39637 /* Set the database size back to the value it was before the savepoint
39638 ** being reverted was opened.
39640 pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
39641 pPager->changeCountDone = pPager->tempFile;
39643 if( !pSavepoint && pagerUseWal(pPager) ){
39644 return pagerRollbackWal(pPager);
39647 /* Use pPager->journalOff as the effective size of the main rollback
39648 ** journal. The actual file might be larger than this in
39649 ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
39650 ** past pPager->journalOff is off-limits to us.
39652 szJ = pPager->journalOff;
39653 assert( pagerUseWal(pPager)==0 || szJ==0 );
39655 /* Begin by rolling back records from the main journal starting at
39656 ** PagerSavepoint.iOffset and continuing to the next journal header.
39657 ** There might be records in the main journal that have a page number
39658 ** greater than the current database size (pPager->dbSize) but those
39659 ** will be skipped automatically. Pages are added to pDone as they
39660 ** are played back.
39662 if( pSavepoint && !pagerUseWal(pPager) ){
39663 iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
39664 pPager->journalOff = pSavepoint->iOffset;
39665 while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
39666 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
39668 assert( rc!=SQLITE_DONE );
39669 }else{
39670 pPager->journalOff = 0;
39673 /* Continue rolling back records out of the main journal starting at
39674 ** the first journal header seen and continuing until the effective end
39675 ** of the main journal file. Continue to skip out-of-range pages and
39676 ** continue adding pages rolled back to pDone.
39678 while( rc==SQLITE_OK && pPager->journalOff<szJ ){
39679 u32 ii; /* Loop counter */
39680 u32 nJRec = 0; /* Number of Journal Records */
39681 u32 dummy;
39682 rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
39683 assert( rc!=SQLITE_DONE );
39686 ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
39687 ** test is related to ticket #2565. See the discussion in the
39688 ** pager_playback() function for additional information.
39690 if( nJRec==0
39691 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
39693 nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
39695 for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
39696 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
39698 assert( rc!=SQLITE_DONE );
39700 assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
39702 /* Finally, rollback pages from the sub-journal. Page that were
39703 ** previously rolled back out of the main journal (and are hence in pDone)
39704 ** will be skipped. Out-of-range pages are also skipped.
39706 if( pSavepoint ){
39707 u32 ii; /* Loop counter */
39708 i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
39710 if( pagerUseWal(pPager) ){
39711 rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
39713 for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
39714 assert( offset==ii*(4+pPager->pageSize) );
39715 rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
39717 assert( rc!=SQLITE_DONE );
39720 sqlite3BitvecDestroy(pDone);
39721 if( rc==SQLITE_OK ){
39722 pPager->journalOff = szJ;
39725 return rc;
39729 ** Change the maximum number of in-memory pages that are allowed.
39731 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
39732 sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
39736 ** Adjust the robustness of the database to damage due to OS crashes
39737 ** or power failures by changing the number of syncs()s when writing
39738 ** the rollback journal. There are three levels:
39740 ** OFF sqlite3OsSync() is never called. This is the default
39741 ** for temporary and transient files.
39743 ** NORMAL The journal is synced once before writes begin on the
39744 ** database. This is normally adequate protection, but
39745 ** it is theoretically possible, though very unlikely,
39746 ** that an inopertune power failure could leave the journal
39747 ** in a state which would cause damage to the database
39748 ** when it is rolled back.
39750 ** FULL The journal is synced twice before writes begin on the
39751 ** database (with some additional information - the nRec field
39752 ** of the journal header - being written in between the two
39753 ** syncs). If we assume that writing a
39754 ** single disk sector is atomic, then this mode provides
39755 ** assurance that the journal will not be corrupted to the
39756 ** point of causing damage to the database during rollback.
39758 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
39759 ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
39760 ** prior to the start of checkpoint and that the database file is synced
39761 ** at the conclusion of the checkpoint if the entire content of the WAL
39762 ** was written back into the database. But no sync operations occur for
39763 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
39764 ** file is synced following each commit operation, in addition to the
39765 ** syncs associated with NORMAL.
39767 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
39768 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
39769 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
39770 ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
39771 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
39772 ** synchronous=FULL versus synchronous=NORMAL setting determines when
39773 ** the xSync primitive is called and is relevant to all platforms.
39775 ** Numeric values associated with these states are OFF==1, NORMAL=2,
39776 ** and FULL=3.
39778 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
39779 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
39780 Pager *pPager, /* The pager to set safety level for */
39781 int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
39782 int bFullFsync, /* PRAGMA fullfsync */
39783 int bCkptFullFsync /* PRAGMA checkpoint_fullfsync */
39785 assert( level>=1 && level<=3 );
39786 pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
39787 pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
39788 if( pPager->noSync ){
39789 pPager->syncFlags = 0;
39790 pPager->ckptSyncFlags = 0;
39791 }else if( bFullFsync ){
39792 pPager->syncFlags = SQLITE_SYNC_FULL;
39793 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
39794 }else if( bCkptFullFsync ){
39795 pPager->syncFlags = SQLITE_SYNC_NORMAL;
39796 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
39797 }else{
39798 pPager->syncFlags = SQLITE_SYNC_NORMAL;
39799 pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
39802 #endif
39805 ** The following global variable is incremented whenever the library
39806 ** attempts to open a temporary file. This information is used for
39807 ** testing and analysis only.
39809 #ifdef SQLITE_TEST
39810 SQLITE_API int sqlite3_opentemp_count = 0;
39811 #endif
39814 ** Open a temporary file.
39816 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
39817 ** or some other error code if we fail. The OS will automatically
39818 ** delete the temporary file when it is closed.
39820 ** The flags passed to the VFS layer xOpen() call are those specified
39821 ** by parameter vfsFlags ORed with the following:
39823 ** SQLITE_OPEN_READWRITE
39824 ** SQLITE_OPEN_CREATE
39825 ** SQLITE_OPEN_EXCLUSIVE
39826 ** SQLITE_OPEN_DELETEONCLOSE
39828 static int pagerOpentemp(
39829 Pager *pPager, /* The pager object */
39830 sqlite3_file *pFile, /* Write the file descriptor here */
39831 int vfsFlags /* Flags passed through to the VFS */
39833 int rc; /* Return code */
39835 #ifdef SQLITE_TEST
39836 sqlite3_opentemp_count++; /* Used for testing and analysis only */
39837 #endif
39839 vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
39840 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
39841 rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
39842 assert( rc!=SQLITE_OK || isOpen(pFile) );
39843 return rc;
39847 ** Set the busy handler function.
39849 ** The pager invokes the busy-handler if sqlite3OsLock() returns
39850 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
39851 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
39852 ** lock. It does *not* invoke the busy handler when upgrading from
39853 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
39854 ** (which occurs during hot-journal rollback). Summary:
39856 ** Transition | Invokes xBusyHandler
39857 ** --------------------------------------------------------
39858 ** NO_LOCK -> SHARED_LOCK | Yes
39859 ** SHARED_LOCK -> RESERVED_LOCK | No
39860 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
39861 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
39863 ** If the busy-handler callback returns non-zero, the lock is
39864 ** retried. If it returns zero, then the SQLITE_BUSY error is
39865 ** returned to the caller of the pager API function.
39867 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
39868 Pager *pPager, /* Pager object */
39869 int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
39870 void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
39872 pPager->xBusyHandler = xBusyHandler;
39873 pPager->pBusyHandlerArg = pBusyHandlerArg;
39877 ** Change the page size used by the Pager object. The new page size
39878 ** is passed in *pPageSize.
39880 ** If the pager is in the error state when this function is called, it
39881 ** is a no-op. The value returned is the error state error code (i.e.
39882 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
39884 ** Otherwise, if all of the following are true:
39886 ** * the new page size (value of *pPageSize) is valid (a power
39887 ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
39889 ** * there are no outstanding page references, and
39891 ** * the database is either not an in-memory database or it is
39892 ** an in-memory database that currently consists of zero pages.
39894 ** then the pager object page size is set to *pPageSize.
39896 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
39897 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
39898 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
39899 ** In all other cases, SQLITE_OK is returned.
39901 ** If the page size is not changed, either because one of the enumerated
39902 ** conditions above is not true, the pager was in error state when this
39903 ** function was called, or because the memory allocation attempt failed,
39904 ** then *pPageSize is set to the old, retained page size before returning.
39906 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
39907 int rc = SQLITE_OK;
39909 /* It is not possible to do a full assert_pager_state() here, as this
39910 ** function may be called from within PagerOpen(), before the state
39911 ** of the Pager object is internally consistent.
39913 ** At one point this function returned an error if the pager was in
39914 ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
39915 ** there is at least one outstanding page reference, this function
39916 ** is a no-op for that case anyhow.
39919 u32 pageSize = *pPageSize;
39920 assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
39921 if( (pPager->memDb==0 || pPager->dbSize==0)
39922 && sqlite3PcacheRefCount(pPager->pPCache)==0
39923 && pageSize && pageSize!=(u32)pPager->pageSize
39925 char *pNew = NULL; /* New temp space */
39926 i64 nByte = 0;
39928 if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
39929 rc = sqlite3OsFileSize(pPager->fd, &nByte);
39931 if( rc==SQLITE_OK ){
39932 pNew = (char *)sqlite3PageMalloc(pageSize);
39933 if( !pNew ) rc = SQLITE_NOMEM;
39936 if( rc==SQLITE_OK ){
39937 pager_reset(pPager);
39938 pPager->dbSize = (Pgno)(nByte/pageSize);
39939 pPager->pageSize = pageSize;
39940 sqlite3PageFree(pPager->pTmpSpace);
39941 pPager->pTmpSpace = pNew;
39942 sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
39946 *pPageSize = pPager->pageSize;
39947 if( rc==SQLITE_OK ){
39948 if( nReserve<0 ) nReserve = pPager->nReserve;
39949 assert( nReserve>=0 && nReserve<1000 );
39950 pPager->nReserve = (i16)nReserve;
39951 pagerReportSize(pPager);
39953 return rc;
39957 ** Return a pointer to the "temporary page" buffer held internally
39958 ** by the pager. This is a buffer that is big enough to hold the
39959 ** entire content of a database page. This buffer is used internally
39960 ** during rollback and will be overwritten whenever a rollback
39961 ** occurs. But other modules are free to use it too, as long as
39962 ** no rollbacks are happening.
39964 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
39965 return pPager->pTmpSpace;
39969 ** Attempt to set the maximum database page count if mxPage is positive.
39970 ** Make no changes if mxPage is zero or negative. And never reduce the
39971 ** maximum page count below the current size of the database.
39973 ** Regardless of mxPage, return the current maximum page count.
39975 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
39976 if( mxPage>0 ){
39977 pPager->mxPgno = mxPage;
39979 assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
39980 assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
39981 return pPager->mxPgno;
39985 ** The following set of routines are used to disable the simulated
39986 ** I/O error mechanism. These routines are used to avoid simulated
39987 ** errors in places where we do not care about errors.
39989 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
39990 ** and generate no code.
39992 #ifdef SQLITE_TEST
39993 SQLITE_API extern int sqlite3_io_error_pending;
39994 SQLITE_API extern int sqlite3_io_error_hit;
39995 static int saved_cnt;
39996 void disable_simulated_io_errors(void){
39997 saved_cnt = sqlite3_io_error_pending;
39998 sqlite3_io_error_pending = -1;
40000 void enable_simulated_io_errors(void){
40001 sqlite3_io_error_pending = saved_cnt;
40003 #else
40004 # define disable_simulated_io_errors()
40005 # define enable_simulated_io_errors()
40006 #endif
40009 ** Read the first N bytes from the beginning of the file into memory
40010 ** that pDest points to.
40012 ** If the pager was opened on a transient file (zFilename==""), or
40013 ** opened on a file less than N bytes in size, the output buffer is
40014 ** zeroed and SQLITE_OK returned. The rationale for this is that this
40015 ** function is used to read database headers, and a new transient or
40016 ** zero sized database has a header than consists entirely of zeroes.
40018 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
40019 ** the error code is returned to the caller and the contents of the
40020 ** output buffer undefined.
40022 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
40023 int rc = SQLITE_OK;
40024 memset(pDest, 0, N);
40025 assert( isOpen(pPager->fd) || pPager->tempFile );
40027 /* This routine is only called by btree immediately after creating
40028 ** the Pager object. There has not been an opportunity to transition
40029 ** to WAL mode yet.
40031 assert( !pagerUseWal(pPager) );
40033 if( isOpen(pPager->fd) ){
40034 IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
40035 rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
40036 if( rc==SQLITE_IOERR_SHORT_READ ){
40037 rc = SQLITE_OK;
40040 return rc;
40044 ** This function may only be called when a read-transaction is open on
40045 ** the pager. It returns the total number of pages in the database.
40047 ** However, if the file is between 1 and <page-size> bytes in size, then
40048 ** this is considered a 1 page file.
40050 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
40051 assert( pPager->eState>=PAGER_READER );
40052 assert( pPager->eState!=PAGER_WRITER_FINISHED );
40053 *pnPage = (int)pPager->dbSize;
40058 ** Try to obtain a lock of type locktype on the database file. If
40059 ** a similar or greater lock is already held, this function is a no-op
40060 ** (returning SQLITE_OK immediately).
40062 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
40063 ** the busy callback if the lock is currently not available. Repeat
40064 ** until the busy callback returns false or until the attempt to
40065 ** obtain the lock succeeds.
40067 ** Return SQLITE_OK on success and an error code if we cannot obtain
40068 ** the lock. If the lock is obtained successfully, set the Pager.state
40069 ** variable to locktype before returning.
40071 static int pager_wait_on_lock(Pager *pPager, int locktype){
40072 int rc; /* Return code */
40074 /* Check that this is either a no-op (because the requested lock is
40075 ** already held, or one of the transistions that the busy-handler
40076 ** may be invoked during, according to the comment above
40077 ** sqlite3PagerSetBusyhandler().
40079 assert( (pPager->eLock>=locktype)
40080 || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
40081 || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
40084 do {
40085 rc = pagerLockDb(pPager, locktype);
40086 }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
40087 return rc;
40091 ** Function assertTruncateConstraint(pPager) checks that one of the
40092 ** following is true for all dirty pages currently in the page-cache:
40094 ** a) The page number is less than or equal to the size of the
40095 ** current database image, in pages, OR
40097 ** b) if the page content were written at this time, it would not
40098 ** be necessary to write the current content out to the sub-journal
40099 ** (as determined by function subjRequiresPage()).
40101 ** If the condition asserted by this function were not true, and the
40102 ** dirty page were to be discarded from the cache via the pagerStress()
40103 ** routine, pagerStress() would not write the current page content to
40104 ** the database file. If a savepoint transaction were rolled back after
40105 ** this happened, the correct behaviour would be to restore the current
40106 ** content of the page. However, since this content is not present in either
40107 ** the database file or the portion of the rollback journal and
40108 ** sub-journal rolled back the content could not be restored and the
40109 ** database image would become corrupt. It is therefore fortunate that
40110 ** this circumstance cannot arise.
40112 #if defined(SQLITE_DEBUG)
40113 static void assertTruncateConstraintCb(PgHdr *pPg){
40114 assert( pPg->flags&PGHDR_DIRTY );
40115 assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
40117 static void assertTruncateConstraint(Pager *pPager){
40118 sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
40120 #else
40121 # define assertTruncateConstraint(pPager)
40122 #endif
40125 ** Truncate the in-memory database file image to nPage pages. This
40126 ** function does not actually modify the database file on disk. It
40127 ** just sets the internal state of the pager object so that the
40128 ** truncation will be done when the current transaction is committed.
40130 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
40131 assert( pPager->dbSize>=nPage );
40132 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
40133 pPager->dbSize = nPage;
40134 assertTruncateConstraint(pPager);
40139 ** This function is called before attempting a hot-journal rollback. It
40140 ** syncs the journal file to disk, then sets pPager->journalHdr to the
40141 ** size of the journal file so that the pager_playback() routine knows
40142 ** that the entire journal file has been synced.
40144 ** Syncing a hot-journal to disk before attempting to roll it back ensures
40145 ** that if a power-failure occurs during the rollback, the process that
40146 ** attempts rollback following system recovery sees the same journal
40147 ** content as this process.
40149 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
40150 ** an SQLite error code.
40152 static int pagerSyncHotJournal(Pager *pPager){
40153 int rc = SQLITE_OK;
40154 if( !pPager->noSync ){
40155 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
40157 if( rc==SQLITE_OK ){
40158 rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
40160 return rc;
40164 ** Shutdown the page cache. Free all memory and close all files.
40166 ** If a transaction was in progress when this routine is called, that
40167 ** transaction is rolled back. All outstanding pages are invalidated
40168 ** and their memory is freed. Any attempt to use a page associated
40169 ** with this page cache after this function returns will likely
40170 ** result in a coredump.
40172 ** This function always succeeds. If a transaction is active an attempt
40173 ** is made to roll it back. If an error occurs during the rollback
40174 ** a hot journal may be left in the filesystem but no error is returned
40175 ** to the caller.
40177 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
40178 u8 *pTmp = (u8 *)pPager->pTmpSpace;
40180 disable_simulated_io_errors();
40181 sqlite3BeginBenignMalloc();
40182 /* pPager->errCode = 0; */
40183 pPager->exclusiveMode = 0;
40184 #ifndef SQLITE_OMIT_WAL
40185 sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
40186 pPager->pWal = 0;
40187 #endif
40188 pager_reset(pPager);
40189 if( MEMDB ){
40190 pager_unlock(pPager);
40191 }else{
40192 /* If it is open, sync the journal file before calling UnlockAndRollback.
40193 ** If this is not done, then an unsynced portion of the open journal
40194 ** file may be played back into the database. If a power failure occurs
40195 ** while this is happening, the database could become corrupt.
40197 ** If an error occurs while trying to sync the journal, shift the pager
40198 ** into the ERROR state. This causes UnlockAndRollback to unlock the
40199 ** database and close the journal file without attempting to roll it
40200 ** back or finalize it. The next database user will have to do hot-journal
40201 ** rollback before accessing the database file.
40203 if( isOpen(pPager->jfd) ){
40204 pager_error(pPager, pagerSyncHotJournal(pPager));
40206 pagerUnlockAndRollback(pPager);
40208 sqlite3EndBenignMalloc();
40209 enable_simulated_io_errors();
40210 PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
40211 IOTRACE(("CLOSE %p\n", pPager))
40212 sqlite3OsClose(pPager->jfd);
40213 sqlite3OsClose(pPager->fd);
40214 sqlite3PageFree(pTmp);
40215 sqlite3PcacheClose(pPager->pPCache);
40217 #ifdef SQLITE_HAS_CODEC
40218 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
40219 #endif
40221 assert( !pPager->aSavepoint && !pPager->pInJournal );
40222 assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
40224 sqlite3_free(pPager);
40225 return SQLITE_OK;
40228 #if !defined(NDEBUG) || defined(SQLITE_TEST)
40230 ** Return the page number for page pPg.
40232 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
40233 return pPg->pgno;
40235 #endif
40238 ** Increment the reference count for page pPg.
40240 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
40241 sqlite3PcacheRef(pPg);
40245 ** Sync the journal. In other words, make sure all the pages that have
40246 ** been written to the journal have actually reached the surface of the
40247 ** disk and can be restored in the event of a hot-journal rollback.
40249 ** If the Pager.noSync flag is set, then this function is a no-op.
40250 ** Otherwise, the actions required depend on the journal-mode and the
40251 ** device characteristics of the the file-system, as follows:
40253 ** * If the journal file is an in-memory journal file, no action need
40254 ** be taken.
40256 ** * Otherwise, if the device does not support the SAFE_APPEND property,
40257 ** then the nRec field of the most recently written journal header
40258 ** is updated to contain the number of journal records that have
40259 ** been written following it. If the pager is operating in full-sync
40260 ** mode, then the journal file is synced before this field is updated.
40262 ** * If the device does not support the SEQUENTIAL property, then
40263 ** journal file is synced.
40265 ** Or, in pseudo-code:
40267 ** if( NOT <in-memory journal> ){
40268 ** if( NOT SAFE_APPEND ){
40269 ** if( <full-sync mode> ) xSync(<journal file>);
40270 ** <update nRec field>
40271 ** }
40272 ** if( NOT SEQUENTIAL ) xSync(<journal file>);
40273 ** }
40275 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
40276 ** page currently held in memory before returning SQLITE_OK. If an IO
40277 ** error is encountered, then the IO error code is returned to the caller.
40279 static int syncJournal(Pager *pPager, int newHdr){
40280 int rc; /* Return code */
40282 assert( pPager->eState==PAGER_WRITER_CACHEMOD
40283 || pPager->eState==PAGER_WRITER_DBMOD
40285 assert( assert_pager_state(pPager) );
40286 assert( !pagerUseWal(pPager) );
40288 rc = sqlite3PagerExclusiveLock(pPager);
40289 if( rc!=SQLITE_OK ) return rc;
40291 if( !pPager->noSync ){
40292 assert( !pPager->tempFile );
40293 if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
40294 const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40295 assert( isOpen(pPager->jfd) );
40297 if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40298 /* This block deals with an obscure problem. If the last connection
40299 ** that wrote to this database was operating in persistent-journal
40300 ** mode, then the journal file may at this point actually be larger
40301 ** than Pager.journalOff bytes. If the next thing in the journal
40302 ** file happens to be a journal-header (written as part of the
40303 ** previous connection's transaction), and a crash or power-failure
40304 ** occurs after nRec is updated but before this connection writes
40305 ** anything else to the journal file (or commits/rolls back its
40306 ** transaction), then SQLite may become confused when doing the
40307 ** hot-journal rollback following recovery. It may roll back all
40308 ** of this connections data, then proceed to rolling back the old,
40309 ** out-of-date data that follows it. Database corruption.
40311 ** To work around this, if the journal file does appear to contain
40312 ** a valid header following Pager.journalOff, then write a 0x00
40313 ** byte to the start of it to prevent it from being recognized.
40315 ** Variable iNextHdrOffset is set to the offset at which this
40316 ** problematic header will occur, if it exists. aMagic is used
40317 ** as a temporary buffer to inspect the first couple of bytes of
40318 ** the potential journal header.
40320 i64 iNextHdrOffset;
40321 u8 aMagic[8];
40322 u8 zHeader[sizeof(aJournalMagic)+4];
40324 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40325 put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
40327 iNextHdrOffset = journalHdrOffset(pPager);
40328 rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
40329 if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
40330 static const u8 zerobyte = 0;
40331 rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
40333 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
40334 return rc;
40337 /* Write the nRec value into the journal file header. If in
40338 ** full-synchronous mode, sync the journal first. This ensures that
40339 ** all data has really hit the disk before nRec is updated to mark
40340 ** it as a candidate for rollback.
40342 ** This is not required if the persistent media supports the
40343 ** SAFE_APPEND property. Because in this case it is not possible
40344 ** for garbage data to be appended to the file, the nRec field
40345 ** is populated with 0xFFFFFFFF when the journal header is written
40346 ** and never needs to be updated.
40348 if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40349 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40350 IOTRACE(("JSYNC %p\n", pPager))
40351 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
40352 if( rc!=SQLITE_OK ) return rc;
40354 IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
40355 rc = sqlite3OsWrite(
40356 pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
40358 if( rc!=SQLITE_OK ) return rc;
40360 if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40361 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40362 IOTRACE(("JSYNC %p\n", pPager))
40363 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
40364 (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
40366 if( rc!=SQLITE_OK ) return rc;
40369 pPager->journalHdr = pPager->journalOff;
40370 if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40371 pPager->nRec = 0;
40372 rc = writeJournalHdr(pPager);
40373 if( rc!=SQLITE_OK ) return rc;
40375 }else{
40376 pPager->journalHdr = pPager->journalOff;
40380 /* Unless the pager is in noSync mode, the journal file was just
40381 ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
40382 ** all pages.
40384 sqlite3PcacheClearSyncFlags(pPager->pPCache);
40385 pPager->eState = PAGER_WRITER_DBMOD;
40386 assert( assert_pager_state(pPager) );
40387 return SQLITE_OK;
40391 ** The argument is the first in a linked list of dirty pages connected
40392 ** by the PgHdr.pDirty pointer. This function writes each one of the
40393 ** in-memory pages in the list to the database file. The argument may
40394 ** be NULL, representing an empty list. In this case this function is
40395 ** a no-op.
40397 ** The pager must hold at least a RESERVED lock when this function
40398 ** is called. Before writing anything to the database file, this lock
40399 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
40400 ** SQLITE_BUSY is returned and no data is written to the database file.
40402 ** If the pager is a temp-file pager and the actual file-system file
40403 ** is not yet open, it is created and opened before any data is
40404 ** written out.
40406 ** Once the lock has been upgraded and, if necessary, the file opened,
40407 ** the pages are written out to the database file in list order. Writing
40408 ** a page is skipped if it meets either of the following criteria:
40410 ** * The page number is greater than Pager.dbSize, or
40411 ** * The PGHDR_DONT_WRITE flag is set on the page.
40413 ** If writing out a page causes the database file to grow, Pager.dbFileSize
40414 ** is updated accordingly. If page 1 is written out, then the value cached
40415 ** in Pager.dbFileVers[] is updated to match the new value stored in
40416 ** the database file.
40418 ** If everything is successful, SQLITE_OK is returned. If an IO error
40419 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
40420 ** be obtained, SQLITE_BUSY is returned.
40422 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
40423 int rc = SQLITE_OK; /* Return code */
40425 /* This function is only called for rollback pagers in WRITER_DBMOD state. */
40426 assert( !pagerUseWal(pPager) );
40427 assert( pPager->eState==PAGER_WRITER_DBMOD );
40428 assert( pPager->eLock==EXCLUSIVE_LOCK );
40430 /* If the file is a temp-file has not yet been opened, open it now. It
40431 ** is not possible for rc to be other than SQLITE_OK if this branch
40432 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
40434 if( !isOpen(pPager->fd) ){
40435 assert( pPager->tempFile && rc==SQLITE_OK );
40436 rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
40439 /* Before the first write, give the VFS a hint of what the final
40440 ** file size will be.
40442 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
40443 if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
40444 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
40445 sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
40446 pPager->dbHintSize = pPager->dbSize;
40449 while( rc==SQLITE_OK && pList ){
40450 Pgno pgno = pList->pgno;
40452 /* If there are dirty pages in the page cache with page numbers greater
40453 ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
40454 ** make the file smaller (presumably by auto-vacuum code). Do not write
40455 ** any such pages to the file.
40457 ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
40458 ** set (set by sqlite3PagerDontWrite()).
40460 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
40461 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
40462 char *pData; /* Data to write */
40464 assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
40465 if( pList->pgno==1 ) pager_write_changecounter(pList);
40467 /* Encode the database */
40468 CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
40470 /* Write out the page data. */
40471 rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
40473 /* If page 1 was just written, update Pager.dbFileVers to match
40474 ** the value now stored in the database file. If writing this
40475 ** page caused the database file to grow, update dbFileSize.
40477 if( pgno==1 ){
40478 memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
40480 if( pgno>pPager->dbFileSize ){
40481 pPager->dbFileSize = pgno;
40484 /* Update any backup objects copying the contents of this pager. */
40485 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
40487 PAGERTRACE(("STORE %d page %d hash(%08x)\n",
40488 PAGERID(pPager), pgno, pager_pagehash(pList)));
40489 IOTRACE(("PGOUT %p %d\n", pPager, pgno));
40490 PAGER_INCR(sqlite3_pager_writedb_count);
40491 PAGER_INCR(pPager->nWrite);
40492 }else{
40493 PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
40495 pager_set_pagehash(pList);
40496 pList = pList->pDirty;
40499 return rc;
40503 ** Ensure that the sub-journal file is open. If it is already open, this
40504 ** function is a no-op.
40506 ** SQLITE_OK is returned if everything goes according to plan. An
40507 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
40508 ** fails.
40510 static int openSubJournal(Pager *pPager){
40511 int rc = SQLITE_OK;
40512 if( !isOpen(pPager->sjfd) ){
40513 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
40514 sqlite3MemJournalOpen(pPager->sjfd);
40515 }else{
40516 rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
40519 return rc;
40523 ** Append a record of the current state of page pPg to the sub-journal.
40524 ** It is the callers responsibility to use subjRequiresPage() to check
40525 ** that it is really required before calling this function.
40527 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
40528 ** for all open savepoints before returning.
40530 ** This function returns SQLITE_OK if everything is successful, an IO
40531 ** error code if the attempt to write to the sub-journal fails, or
40532 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
40533 ** bitvec.
40535 static int subjournalPage(PgHdr *pPg){
40536 int rc = SQLITE_OK;
40537 Pager *pPager = pPg->pPager;
40538 if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
40540 /* Open the sub-journal, if it has not already been opened */
40541 assert( pPager->useJournal );
40542 assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
40543 assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
40544 assert( pagerUseWal(pPager)
40545 || pageInJournal(pPg)
40546 || pPg->pgno>pPager->dbOrigSize
40548 rc = openSubJournal(pPager);
40550 /* If the sub-journal was opened successfully (or was already open),
40551 ** write the journal record into the file. */
40552 if( rc==SQLITE_OK ){
40553 void *pData = pPg->pData;
40554 i64 offset = pPager->nSubRec*(4+pPager->pageSize);
40555 char *pData2;
40557 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
40558 PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
40559 rc = write32bits(pPager->sjfd, offset, pPg->pgno);
40560 if( rc==SQLITE_OK ){
40561 rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
40565 if( rc==SQLITE_OK ){
40566 pPager->nSubRec++;
40567 assert( pPager->nSavepoint>0 );
40568 rc = addToSavepointBitvecs(pPager, pPg->pgno);
40570 return rc;
40574 ** This function is called by the pcache layer when it has reached some
40575 ** soft memory limit. The first argument is a pointer to a Pager object
40576 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
40577 ** database). The second argument is a reference to a page that is
40578 ** currently dirty but has no outstanding references. The page
40579 ** is always associated with the Pager object passed as the first
40580 ** argument.
40582 ** The job of this function is to make pPg clean by writing its contents
40583 ** out to the database file, if possible. This may involve syncing the
40584 ** journal file.
40586 ** If successful, sqlite3PcacheMakeClean() is called on the page and
40587 ** SQLITE_OK returned. If an IO error occurs while trying to make the
40588 ** page clean, the IO error code is returned. If the page cannot be
40589 ** made clean for some other reason, but no error occurs, then SQLITE_OK
40590 ** is returned by sqlite3PcacheMakeClean() is not called.
40592 static int pagerStress(void *p, PgHdr *pPg){
40593 Pager *pPager = (Pager *)p;
40594 int rc = SQLITE_OK;
40596 assert( pPg->pPager==pPager );
40597 assert( pPg->flags&PGHDR_DIRTY );
40599 /* The doNotSyncSpill flag is set during times when doing a sync of
40600 ** journal (and adding a new header) is not allowed. This occurs
40601 ** during calls to sqlite3PagerWrite() while trying to journal multiple
40602 ** pages belonging to the same sector.
40604 ** The doNotSpill flag inhibits all cache spilling regardless of whether
40605 ** or not a sync is required. This is set during a rollback.
40607 ** Spilling is also prohibited when in an error state since that could
40608 ** lead to database corruption. In the current implementaton it
40609 ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
40610 ** while in the error state, hence it is impossible for this routine to
40611 ** be called in the error state. Nevertheless, we include a NEVER()
40612 ** test for the error state as a safeguard against future changes.
40614 if( NEVER(pPager->errCode) ) return SQLITE_OK;
40615 if( pPager->doNotSpill ) return SQLITE_OK;
40616 if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
40617 return SQLITE_OK;
40620 pPg->pDirty = 0;
40621 if( pagerUseWal(pPager) ){
40622 /* Write a single frame for this page to the log. */
40623 if( subjRequiresPage(pPg) ){
40624 rc = subjournalPage(pPg);
40626 if( rc==SQLITE_OK ){
40627 rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
40629 }else{
40631 /* Sync the journal file if required. */
40632 if( pPg->flags&PGHDR_NEED_SYNC
40633 || pPager->eState==PAGER_WRITER_CACHEMOD
40635 rc = syncJournal(pPager, 1);
40638 /* If the page number of this page is larger than the current size of
40639 ** the database image, it may need to be written to the sub-journal.
40640 ** This is because the call to pager_write_pagelist() below will not
40641 ** actually write data to the file in this case.
40643 ** Consider the following sequence of events:
40645 ** BEGIN;
40646 ** <journal page X>
40647 ** <modify page X>
40648 ** SAVEPOINT sp;
40649 ** <shrink database file to Y pages>
40650 ** pagerStress(page X)
40651 ** ROLLBACK TO sp;
40653 ** If (X>Y), then when pagerStress is called page X will not be written
40654 ** out to the database file, but will be dropped from the cache. Then,
40655 ** following the "ROLLBACK TO sp" statement, reading page X will read
40656 ** data from the database file. This will be the copy of page X as it
40657 ** was when the transaction started, not as it was when "SAVEPOINT sp"
40658 ** was executed.
40660 ** The solution is to write the current data for page X into the
40661 ** sub-journal file now (if it is not already there), so that it will
40662 ** be restored to its current value when the "ROLLBACK TO sp" is
40663 ** executed.
40665 if( NEVER(
40666 rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
40667 ) ){
40668 rc = subjournalPage(pPg);
40671 /* Write the contents of the page out to the database file. */
40672 if( rc==SQLITE_OK ){
40673 assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
40674 rc = pager_write_pagelist(pPager, pPg);
40678 /* Mark the page as clean. */
40679 if( rc==SQLITE_OK ){
40680 PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
40681 sqlite3PcacheMakeClean(pPg);
40684 return pager_error(pPager, rc);
40689 ** Allocate and initialize a new Pager object and put a pointer to it
40690 ** in *ppPager. The pager should eventually be freed by passing it
40691 ** to sqlite3PagerClose().
40693 ** The zFilename argument is the path to the database file to open.
40694 ** If zFilename is NULL then a randomly-named temporary file is created
40695 ** and used as the file to be cached. Temporary files are be deleted
40696 ** automatically when they are closed. If zFilename is ":memory:" then
40697 ** all information is held in cache. It is never written to disk.
40698 ** This can be used to implement an in-memory database.
40700 ** The nExtra parameter specifies the number of bytes of space allocated
40701 ** along with each page reference. This space is available to the user
40702 ** via the sqlite3PagerGetExtra() API.
40704 ** The flags argument is used to specify properties that affect the
40705 ** operation of the pager. It should be passed some bitwise combination
40706 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
40708 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
40709 ** of the xOpen() method of the supplied VFS when opening files.
40711 ** If the pager object is allocated and the specified file opened
40712 ** successfully, SQLITE_OK is returned and *ppPager set to point to
40713 ** the new pager object. If an error occurs, *ppPager is set to NULL
40714 ** and error code returned. This function may return SQLITE_NOMEM
40715 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
40716 ** various SQLITE_IO_XXX errors.
40718 SQLITE_PRIVATE int sqlite3PagerOpen(
40719 sqlite3_vfs *pVfs, /* The virtual file system to use */
40720 Pager **ppPager, /* OUT: Return the Pager structure here */
40721 const char *zFilename, /* Name of the database file to open */
40722 int nExtra, /* Extra bytes append to each in-memory page */
40723 int flags, /* flags controlling this file */
40724 int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
40725 void (*xReinit)(DbPage*) /* Function to reinitialize pages */
40727 u8 *pPtr;
40728 Pager *pPager = 0; /* Pager object to allocate and return */
40729 int rc = SQLITE_OK; /* Return code */
40730 int tempFile = 0; /* True for temp files (incl. in-memory files) */
40731 int memDb = 0; /* True if this is an in-memory file */
40732 int readOnly = 0; /* True if this is a read-only file */
40733 int journalFileSize; /* Bytes to allocate for each journal fd */
40734 char *zPathname = 0; /* Full path to database file */
40735 int nPathname = 0; /* Number of bytes in zPathname */
40736 int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
40737 int noReadlock = (flags & PAGER_NO_READLOCK)!=0; /* True to omit read-lock */
40738 int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
40739 u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
40741 /* Figure out how much space is required for each journal file-handle
40742 ** (there are two of them, the main journal and the sub-journal). This
40743 ** is the maximum space required for an in-memory journal file handle
40744 ** and a regular journal file-handle. Note that a "regular journal-handle"
40745 ** may be a wrapper capable of caching the first portion of the journal
40746 ** file in memory to implement the atomic-write optimization (see
40747 ** source file journal.c).
40749 if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
40750 journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
40751 }else{
40752 journalFileSize = ROUND8(sqlite3MemJournalSize());
40755 /* Set the output variable to NULL in case an error occurs. */
40756 *ppPager = 0;
40758 #ifndef SQLITE_OMIT_MEMORYDB
40759 if( flags & PAGER_MEMORY ){
40760 memDb = 1;
40761 zFilename = 0;
40763 #endif
40765 /* Compute and store the full pathname in an allocated buffer pointed
40766 ** to by zPathname, length nPathname. Or, if this is a temporary file,
40767 ** leave both nPathname and zPathname set to 0.
40769 if( zFilename && zFilename[0] ){
40770 nPathname = pVfs->mxPathname+1;
40771 zPathname = sqlite3Malloc(nPathname*2);
40772 if( zPathname==0 ){
40773 return SQLITE_NOMEM;
40775 zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
40776 rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
40777 nPathname = sqlite3Strlen30(zPathname);
40778 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
40779 /* This branch is taken when the journal path required by
40780 ** the database being opened will be more than pVfs->mxPathname
40781 ** bytes in length. This means the database cannot be opened,
40782 ** as it will not be possible to open the journal file or even
40783 ** check for a hot-journal before reading.
40785 rc = SQLITE_CANTOPEN_BKPT;
40787 if( rc!=SQLITE_OK ){
40788 sqlite3_free(zPathname);
40789 return rc;
40793 /* Allocate memory for the Pager structure, PCache object, the
40794 ** three file descriptors, the database file name and the journal
40795 ** file name. The layout in memory is as follows:
40797 ** Pager object (sizeof(Pager) bytes)
40798 ** PCache object (sqlite3PcacheSize() bytes)
40799 ** Database file handle (pVfs->szOsFile bytes)
40800 ** Sub-journal file handle (journalFileSize bytes)
40801 ** Main journal file handle (journalFileSize bytes)
40802 ** Database file name (nPathname+1 bytes)
40803 ** Journal file name (nPathname+8+1 bytes)
40805 pPtr = (u8 *)sqlite3MallocZero(
40806 ROUND8(sizeof(*pPager)) + /* Pager structure */
40807 ROUND8(pcacheSize) + /* PCache object */
40808 ROUND8(pVfs->szOsFile) + /* The main db file */
40809 journalFileSize * 2 + /* The two journal files */
40810 nPathname + 1 + /* zFilename */
40811 nPathname + 8 + 1 /* zJournal */
40812 #ifndef SQLITE_OMIT_WAL
40813 + nPathname + 4 + 1 /* zWal */
40814 #endif
40816 assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
40817 if( !pPtr ){
40818 sqlite3_free(zPathname);
40819 return SQLITE_NOMEM;
40821 pPager = (Pager*)(pPtr);
40822 pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
40823 pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
40824 pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
40825 pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
40826 pPager->zFilename = (char*)(pPtr += journalFileSize);
40827 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
40829 /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
40830 if( zPathname ){
40831 assert( nPathname>0 );
40832 pPager->zJournal = (char*)(pPtr += nPathname + 1);
40833 memcpy(pPager->zFilename, zPathname, nPathname);
40834 memcpy(pPager->zJournal, zPathname, nPathname);
40835 memcpy(&pPager->zJournal[nPathname], "-journal", 8);
40836 #ifndef SQLITE_OMIT_WAL
40837 pPager->zWal = &pPager->zJournal[nPathname+8+1];
40838 memcpy(pPager->zWal, zPathname, nPathname);
40839 memcpy(&pPager->zWal[nPathname], "-wal", 4);
40840 #endif
40841 sqlite3_free(zPathname);
40843 pPager->pVfs = pVfs;
40844 pPager->vfsFlags = vfsFlags;
40846 /* Open the pager file.
40848 if( zFilename && zFilename[0] ){
40849 int fout = 0; /* VFS flags returned by xOpen() */
40850 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
40851 assert( !memDb );
40852 readOnly = (fout&SQLITE_OPEN_READONLY);
40854 /* If the file was successfully opened for read/write access,
40855 ** choose a default page size in case we have to create the
40856 ** database file. The default page size is the maximum of:
40858 ** + SQLITE_DEFAULT_PAGE_SIZE,
40859 ** + The value returned by sqlite3OsSectorSize()
40860 ** + The largest page size that can be written atomically.
40862 if( rc==SQLITE_OK && !readOnly ){
40863 setSectorSize(pPager);
40864 assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
40865 if( szPageDflt<pPager->sectorSize ){
40866 if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
40867 szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
40868 }else{
40869 szPageDflt = (u32)pPager->sectorSize;
40872 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40874 int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40875 int ii;
40876 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
40877 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
40878 assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
40879 for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
40880 if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
40881 szPageDflt = ii;
40885 #endif
40887 }else{
40888 /* If a temporary file is requested, it is not opened immediately.
40889 ** In this case we accept the default page size and delay actually
40890 ** opening the file until the first call to OsWrite().
40892 ** This branch is also run for an in-memory database. An in-memory
40893 ** database is the same as a temp-file that is never written out to
40894 ** disk and uses an in-memory rollback journal.
40896 tempFile = 1;
40897 pPager->eState = PAGER_READER;
40898 pPager->eLock = EXCLUSIVE_LOCK;
40899 readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
40902 /* The following call to PagerSetPagesize() serves to set the value of
40903 ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
40905 if( rc==SQLITE_OK ){
40906 assert( pPager->memDb==0 );
40907 rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
40908 testcase( rc!=SQLITE_OK );
40911 /* If an error occurred in either of the blocks above, free the
40912 ** Pager structure and close the file.
40914 if( rc!=SQLITE_OK ){
40915 assert( !pPager->pTmpSpace );
40916 sqlite3OsClose(pPager->fd);
40917 sqlite3_free(pPager);
40918 return rc;
40921 /* Initialize the PCache object. */
40922 assert( nExtra<1000 );
40923 nExtra = ROUND8(nExtra);
40924 sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
40925 !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
40927 PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
40928 IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
40930 pPager->useJournal = (u8)useJournal;
40931 pPager->noReadlock = (noReadlock && readOnly) ?1:0;
40932 /* pPager->stmtOpen = 0; */
40933 /* pPager->stmtInUse = 0; */
40934 /* pPager->nRef = 0; */
40935 /* pPager->stmtSize = 0; */
40936 /* pPager->stmtJSize = 0; */
40937 /* pPager->nPage = 0; */
40938 pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
40939 /* pPager->state = PAGER_UNLOCK; */
40940 #if 0
40941 assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
40942 #endif
40943 /* pPager->errMask = 0; */
40944 pPager->tempFile = (u8)tempFile;
40945 assert( tempFile==PAGER_LOCKINGMODE_NORMAL
40946 || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
40947 assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
40948 pPager->exclusiveMode = (u8)tempFile;
40949 pPager->changeCountDone = pPager->tempFile;
40950 pPager->memDb = (u8)memDb;
40951 pPager->readOnly = (u8)readOnly;
40952 assert( useJournal || pPager->tempFile );
40953 pPager->noSync = pPager->tempFile;
40954 pPager->fullSync = pPager->noSync ?0:1;
40955 pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
40956 pPager->ckptSyncFlags = pPager->syncFlags;
40957 /* pPager->pFirst = 0; */
40958 /* pPager->pFirstSynced = 0; */
40959 /* pPager->pLast = 0; */
40960 pPager->nExtra = (u16)nExtra;
40961 pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
40962 assert( isOpen(pPager->fd) || tempFile );
40963 setSectorSize(pPager);
40964 if( !useJournal ){
40965 pPager->journalMode = PAGER_JOURNALMODE_OFF;
40966 }else if( memDb ){
40967 pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
40969 /* pPager->xBusyHandler = 0; */
40970 /* pPager->pBusyHandlerArg = 0; */
40971 pPager->xReiniter = xReinit;
40972 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
40974 *ppPager = pPager;
40975 return SQLITE_OK;
40981 ** This function is called after transitioning from PAGER_UNLOCK to
40982 ** PAGER_SHARED state. It tests if there is a hot journal present in
40983 ** the file-system for the given pager. A hot journal is one that
40984 ** needs to be played back. According to this function, a hot-journal
40985 ** file exists if the following criteria are met:
40987 ** * The journal file exists in the file system, and
40988 ** * No process holds a RESERVED or greater lock on the database file, and
40989 ** * The database file itself is greater than 0 bytes in size, and
40990 ** * The first byte of the journal file exists and is not 0x00.
40992 ** If the current size of the database file is 0 but a journal file
40993 ** exists, that is probably an old journal left over from a prior
40994 ** database with the same name. In this case the journal file is
40995 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
40996 ** is returned.
40998 ** This routine does not check if there is a master journal filename
40999 ** at the end of the file. If there is, and that master journal file
41000 ** does not exist, then the journal file is not really hot. In this
41001 ** case this routine will return a false-positive. The pager_playback()
41002 ** routine will discover that the journal file is not really hot and
41003 ** will not roll it back.
41005 ** If a hot-journal file is found to exist, *pExists is set to 1 and
41006 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
41007 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
41008 ** to determine whether or not a hot-journal file exists, the IO error
41009 ** code is returned and the value of *pExists is undefined.
41011 static int hasHotJournal(Pager *pPager, int *pExists){
41012 sqlite3_vfs * const pVfs = pPager->pVfs;
41013 int rc = SQLITE_OK; /* Return code */
41014 int exists = 1; /* True if a journal file is present */
41015 int jrnlOpen = !!isOpen(pPager->jfd);
41017 assert( pPager->useJournal );
41018 assert( isOpen(pPager->fd) );
41019 assert( pPager->eState==PAGER_OPEN );
41021 assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
41022 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
41025 *pExists = 0;
41026 if( !jrnlOpen ){
41027 rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
41029 if( rc==SQLITE_OK && exists ){
41030 int locked = 0; /* True if some process holds a RESERVED lock */
41032 /* Race condition here: Another process might have been holding the
41033 ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
41034 ** call above, but then delete the journal and drop the lock before
41035 ** we get to the following sqlite3OsCheckReservedLock() call. If that
41036 ** is the case, this routine might think there is a hot journal when
41037 ** in fact there is none. This results in a false-positive which will
41038 ** be dealt with by the playback routine. Ticket #3883.
41040 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
41041 if( rc==SQLITE_OK && !locked ){
41042 Pgno nPage; /* Number of pages in database file */
41044 /* Check the size of the database file. If it consists of 0 pages,
41045 ** then delete the journal file. See the header comment above for
41046 ** the reasoning here. Delete the obsolete journal file under
41047 ** a RESERVED lock to avoid race conditions and to avoid violating
41048 ** [H33020].
41050 rc = pagerPagecount(pPager, &nPage);
41051 if( rc==SQLITE_OK ){
41052 if( nPage==0 ){
41053 sqlite3BeginBenignMalloc();
41054 if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
41055 sqlite3OsDelete(pVfs, pPager->zJournal, 0);
41056 if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
41058 sqlite3EndBenignMalloc();
41059 }else{
41060 /* The journal file exists and no other connection has a reserved
41061 ** or greater lock on the database file. Now check that there is
41062 ** at least one non-zero bytes at the start of the journal file.
41063 ** If there is, then we consider this journal to be hot. If not,
41064 ** it can be ignored.
41066 if( !jrnlOpen ){
41067 int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
41068 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
41070 if( rc==SQLITE_OK ){
41071 u8 first = 0;
41072 rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
41073 if( rc==SQLITE_IOERR_SHORT_READ ){
41074 rc = SQLITE_OK;
41076 if( !jrnlOpen ){
41077 sqlite3OsClose(pPager->jfd);
41079 *pExists = (first!=0);
41080 }else if( rc==SQLITE_CANTOPEN ){
41081 /* If we cannot open the rollback journal file in order to see if
41082 ** its has a zero header, that might be due to an I/O error, or
41083 ** it might be due to the race condition described above and in
41084 ** ticket #3883. Either way, assume that the journal is hot.
41085 ** This might be a false positive. But if it is, then the
41086 ** automatic journal playback and recovery mechanism will deal
41087 ** with it under an EXCLUSIVE lock where we do not need to
41088 ** worry so much with race conditions.
41090 *pExists = 1;
41091 rc = SQLITE_OK;
41098 return rc;
41102 ** This function is called to obtain a shared lock on the database file.
41103 ** It is illegal to call sqlite3PagerAcquire() until after this function
41104 ** has been successfully called. If a shared-lock is already held when
41105 ** this function is called, it is a no-op.
41107 ** The following operations are also performed by this function.
41109 ** 1) If the pager is currently in PAGER_OPEN state (no lock held
41110 ** on the database file), then an attempt is made to obtain a
41111 ** SHARED lock on the database file. Immediately after obtaining
41112 ** the SHARED lock, the file-system is checked for a hot-journal,
41113 ** which is played back if present. Following any hot-journal
41114 ** rollback, the contents of the cache are validated by checking
41115 ** the 'change-counter' field of the database file header and
41116 ** discarded if they are found to be invalid.
41118 ** 2) If the pager is running in exclusive-mode, and there are currently
41119 ** no outstanding references to any pages, and is in the error state,
41120 ** then an attempt is made to clear the error state by discarding
41121 ** the contents of the page cache and rolling back any open journal
41122 ** file.
41124 ** If everything is successful, SQLITE_OK is returned. If an IO error
41125 ** occurs while locking the database, checking for a hot-journal file or
41126 ** rolling back a journal file, the IO error code is returned.
41128 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
41129 int rc = SQLITE_OK; /* Return code */
41131 /* This routine is only called from b-tree and only when there are no
41132 ** outstanding pages. This implies that the pager state should either
41133 ** be OPEN or READER. READER is only possible if the pager is or was in
41134 ** exclusive access mode.
41136 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
41137 assert( assert_pager_state(pPager) );
41138 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41139 if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
41141 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
41142 int bHotJournal = 1; /* True if there exists a hot journal-file */
41144 assert( !MEMDB );
41145 assert( pPager->noReadlock==0 || pPager->readOnly );
41147 if( pPager->noReadlock==0 ){
41148 rc = pager_wait_on_lock(pPager, SHARED_LOCK);
41149 if( rc!=SQLITE_OK ){
41150 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
41151 goto failed;
41155 /* If a journal file exists, and there is no RESERVED lock on the
41156 ** database file, then it either needs to be played back or deleted.
41158 if( pPager->eLock<=SHARED_LOCK ){
41159 rc = hasHotJournal(pPager, &bHotJournal);
41161 if( rc!=SQLITE_OK ){
41162 goto failed;
41164 if( bHotJournal ){
41165 /* Get an EXCLUSIVE lock on the database file. At this point it is
41166 ** important that a RESERVED lock is not obtained on the way to the
41167 ** EXCLUSIVE lock. If it were, another process might open the
41168 ** database file, detect the RESERVED lock, and conclude that the
41169 ** database is safe to read while this process is still rolling the
41170 ** hot-journal back.
41172 ** Because the intermediate RESERVED lock is not requested, any
41173 ** other process attempting to access the database file will get to
41174 ** this point in the code and fail to obtain its own EXCLUSIVE lock
41175 ** on the database file.
41177 ** Unless the pager is in locking_mode=exclusive mode, the lock is
41178 ** downgraded to SHARED_LOCK before this function returns.
41180 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41181 if( rc!=SQLITE_OK ){
41182 goto failed;
41185 /* If it is not already open and the file exists on disk, open the
41186 ** journal for read/write access. Write access is required because
41187 ** in exclusive-access mode the file descriptor will be kept open
41188 ** and possibly used for a transaction later on. Also, write-access
41189 ** is usually required to finalize the journal in journal_mode=persist
41190 ** mode (and also for journal_mode=truncate on some systems).
41192 ** If the journal does not exist, it usually means that some
41193 ** other connection managed to get in and roll it back before
41194 ** this connection obtained the exclusive lock above. Or, it
41195 ** may mean that the pager was in the error-state when this
41196 ** function was called and the journal file does not exist.
41198 if( !isOpen(pPager->jfd) ){
41199 sqlite3_vfs * const pVfs = pPager->pVfs;
41200 int bExists; /* True if journal file exists */
41201 rc = sqlite3OsAccess(
41202 pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
41203 if( rc==SQLITE_OK && bExists ){
41204 int fout = 0;
41205 int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
41206 assert( !pPager->tempFile );
41207 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
41208 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41209 if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
41210 rc = SQLITE_CANTOPEN_BKPT;
41211 sqlite3OsClose(pPager->jfd);
41216 /* Playback and delete the journal. Drop the database write
41217 ** lock and reacquire the read lock. Purge the cache before
41218 ** playing back the hot-journal so that we don't end up with
41219 ** an inconsistent cache. Sync the hot journal before playing
41220 ** it back since the process that crashed and left the hot journal
41221 ** probably did not sync it and we are required to always sync
41222 ** the journal before playing it back.
41224 if( isOpen(pPager->jfd) ){
41225 assert( rc==SQLITE_OK );
41226 rc = pagerSyncHotJournal(pPager);
41227 if( rc==SQLITE_OK ){
41228 rc = pager_playback(pPager, 1);
41229 pPager->eState = PAGER_OPEN;
41231 }else if( !pPager->exclusiveMode ){
41232 pagerUnlockDb(pPager, SHARED_LOCK);
41235 if( rc!=SQLITE_OK ){
41236 /* This branch is taken if an error occurs while trying to open
41237 ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
41238 ** pager_unlock() routine will be called before returning to unlock
41239 ** the file. If the unlock attempt fails, then Pager.eLock must be
41240 ** set to UNKNOWN_LOCK (see the comment above the #define for
41241 ** UNKNOWN_LOCK above for an explanation).
41243 ** In order to get pager_unlock() to do this, set Pager.eState to
41244 ** PAGER_ERROR now. This is not actually counted as a transition
41245 ** to ERROR state in the state diagram at the top of this file,
41246 ** since we know that the same call to pager_unlock() will very
41247 ** shortly transition the pager object to the OPEN state. Calling
41248 ** assert_pager_state() would fail now, as it should not be possible
41249 ** to be in ERROR state when there are zero outstanding page
41250 ** references.
41252 pager_error(pPager, rc);
41253 goto failed;
41256 assert( pPager->eState==PAGER_OPEN );
41257 assert( (pPager->eLock==SHARED_LOCK)
41258 || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
41262 if( !pPager->tempFile
41263 && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
41265 /* The shared-lock has just been acquired on the database file
41266 ** and there are already pages in the cache (from a previous
41267 ** read or write transaction). Check to see if the database
41268 ** has been modified. If the database has changed, flush the
41269 ** cache.
41271 ** Database changes is detected by looking at 15 bytes beginning
41272 ** at offset 24 into the file. The first 4 of these 16 bytes are
41273 ** a 32-bit counter that is incremented with each change. The
41274 ** other bytes change randomly with each file change when
41275 ** a codec is in use.
41277 ** There is a vanishingly small chance that a change will not be
41278 ** detected. The chance of an undetected change is so small that
41279 ** it can be neglected.
41281 Pgno nPage = 0;
41282 char dbFileVers[sizeof(pPager->dbFileVers)];
41284 rc = pagerPagecount(pPager, &nPage);
41285 if( rc ) goto failed;
41287 if( nPage>0 ){
41288 IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
41289 rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
41290 if( rc!=SQLITE_OK ){
41291 goto failed;
41293 }else{
41294 memset(dbFileVers, 0, sizeof(dbFileVers));
41297 if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
41298 pager_reset(pPager);
41302 /* If there is a WAL file in the file-system, open this database in WAL
41303 ** mode. Otherwise, the following function call is a no-op.
41305 rc = pagerOpenWalIfPresent(pPager);
41306 #ifndef SQLITE_OMIT_WAL
41307 assert( pPager->pWal==0 || rc==SQLITE_OK );
41308 #endif
41311 if( pagerUseWal(pPager) ){
41312 assert( rc==SQLITE_OK );
41313 rc = pagerBeginReadTransaction(pPager);
41316 if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
41317 rc = pagerPagecount(pPager, &pPager->dbSize);
41320 failed:
41321 if( rc!=SQLITE_OK ){
41322 assert( !MEMDB );
41323 pager_unlock(pPager);
41324 assert( pPager->eState==PAGER_OPEN );
41325 }else{
41326 pPager->eState = PAGER_READER;
41328 return rc;
41332 ** If the reference count has reached zero, rollback any active
41333 ** transaction and unlock the pager.
41335 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
41336 ** the rollback journal, the unlock is not performed and there is
41337 ** nothing to rollback, so this routine is a no-op.
41339 static void pagerUnlockIfUnused(Pager *pPager){
41340 if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
41341 pagerUnlockAndRollback(pPager);
41346 ** Acquire a reference to page number pgno in pager pPager (a page
41347 ** reference has type DbPage*). If the requested reference is
41348 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
41350 ** If the requested page is already in the cache, it is returned.
41351 ** Otherwise, a new page object is allocated and populated with data
41352 ** read from the database file. In some cases, the pcache module may
41353 ** choose not to allocate a new page object and may reuse an existing
41354 ** object with no outstanding references.
41356 ** The extra data appended to a page is always initialized to zeros the
41357 ** first time a page is loaded into memory. If the page requested is
41358 ** already in the cache when this function is called, then the extra
41359 ** data is left as it was when the page object was last used.
41361 ** If the database image is smaller than the requested page or if a
41362 ** non-zero value is passed as the noContent parameter and the
41363 ** requested page is not already stored in the cache, then no
41364 ** actual disk read occurs. In this case the memory image of the
41365 ** page is initialized to all zeros.
41367 ** If noContent is true, it means that we do not care about the contents
41368 ** of the page. This occurs in two seperate scenarios:
41370 ** a) When reading a free-list leaf page from the database, and
41372 ** b) When a savepoint is being rolled back and we need to load
41373 ** a new page into the cache to be filled with the data read
41374 ** from the savepoint journal.
41376 ** If noContent is true, then the data returned is zeroed instead of
41377 ** being read from the database. Additionally, the bits corresponding
41378 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
41379 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
41380 ** savepoints are set. This means if the page is made writable at any
41381 ** point in the future, using a call to sqlite3PagerWrite(), its contents
41382 ** will not be journaled. This saves IO.
41384 ** The acquisition might fail for several reasons. In all cases,
41385 ** an appropriate error code is returned and *ppPage is set to NULL.
41387 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
41388 ** to find a page in the in-memory cache first. If the page is not already
41389 ** in memory, this routine goes to disk to read it in whereas Lookup()
41390 ** just returns 0. This routine acquires a read-lock the first time it
41391 ** has to go to disk, and could also playback an old journal if necessary.
41392 ** Since Lookup() never goes to disk, it never has to deal with locks
41393 ** or journal files.
41395 SQLITE_PRIVATE int sqlite3PagerAcquire(
41396 Pager *pPager, /* The pager open on the database file */
41397 Pgno pgno, /* Page number to fetch */
41398 DbPage **ppPage, /* Write a pointer to the page here */
41399 int noContent /* Do not bother reading content from disk if true */
41401 /* This just passes through to our modified version with NULL data. */
41402 return sqlite3PagerAcquire2(pPager, pgno, ppPage, noContent, 0);
41406 ** This is an internal version of sqlite3PagerAcquire that takes an extra
41407 ** parameter of data to use to fill the page with. This allows more efficient
41408 ** filling for preloaded data. If this extra parameter is NULL, we'll go to
41409 ** the file.
41411 ** See sqlite3PagerLoadall which uses this function.
41413 SQLITE_PRIVATE int sqlite3PagerAcquire2(
41414 Pager *pPager, /* The pager open on the database file */
41415 Pgno pgno, /* Page number to fetch */
41416 DbPage **ppPage, /* Write a pointer to the page here */
41417 int noContent, /* Do not bother reading content from disk if true */
41418 unsigned char* pDataToFill
41420 int rc;
41421 PgHdr *pPg;
41423 assert( pPager->eState>=PAGER_READER );
41424 assert( assert_pager_state(pPager) );
41426 if( pgno==0 ){
41427 return SQLITE_CORRUPT_BKPT;
41430 /* If the pager is in the error state, return an error immediately.
41431 ** Otherwise, request the page from the PCache layer. */
41432 if( pPager->errCode!=SQLITE_OK ){
41433 rc = pPager->errCode;
41434 }else{
41435 rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
41438 if( rc!=SQLITE_OK ){
41439 /* Either the call to sqlite3PcacheFetch() returned an error or the
41440 ** pager was already in the error-state when this function was called.
41441 ** Set pPg to 0 and jump to the exception handler. */
41442 pPg = 0;
41443 goto pager_acquire_err;
41445 assert( (*ppPage)->pgno==pgno );
41446 assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
41448 if( (*ppPage)->pPager && !noContent ){
41449 /* In this case the pcache already contains an initialized copy of
41450 ** the page. Return without further ado. */
41451 assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
41452 PAGER_INCR(pPager->nHit);
41453 return SQLITE_OK;
41455 }else{
41456 /* The pager cache has created a new page. Its content needs to
41457 ** be initialized. */
41459 PAGER_INCR(pPager->nMiss);
41460 pPg = *ppPage;
41461 pPg->pPager = pPager;
41463 /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
41464 ** number greater than this, or the unused locking-page, is requested. */
41465 if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
41466 rc = SQLITE_CORRUPT_BKPT;
41467 goto pager_acquire_err;
41470 if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
41471 if( pgno>pPager->mxPgno ){
41472 rc = SQLITE_FULL;
41473 goto pager_acquire_err;
41475 if( noContent ){
41476 /* Failure to set the bits in the InJournal bit-vectors is benign.
41477 ** It merely means that we might do some extra work to journal a
41478 ** page that does not need to be journaled. Nevertheless, be sure
41479 ** to test the case where a malloc error occurs while trying to set
41480 ** a bit in a bit vector.
41482 sqlite3BeginBenignMalloc();
41483 if( pgno<=pPager->dbOrigSize ){
41484 TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
41485 testcase( rc==SQLITE_NOMEM );
41487 TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
41488 testcase( rc==SQLITE_NOMEM );
41489 sqlite3EndBenignMalloc();
41491 memset(pPg->pData, 0, pPager->pageSize);
41492 IOTRACE(("ZERO %p %d\n", pPager, pgno));
41493 }else{
41494 assert( pPg->pPager==pPager );
41495 if( pDataToFill ){
41496 /* Just copy from the given memory */
41497 memcpy(pPg->pData, pDataToFill, pPager->pageSize);
41498 CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM;
41499 goto pager_acquire_err);
41500 }else{
41501 /* Load from disk (old regular sqlite code path) */
41502 rc = readDbPage(pPg);
41503 if( rc!=SQLITE_OK ){
41504 goto pager_acquire_err;
41508 pager_set_pagehash(pPg);
41511 return SQLITE_OK;
41513 pager_acquire_err:
41514 assert( rc!=SQLITE_OK );
41515 if( pPg ){
41516 sqlite3PcacheDrop(pPg);
41518 pagerUnlockIfUnused(pPager);
41520 *ppPage = 0;
41521 return rc;
41525 ** Acquire a page if it is already in the in-memory cache. Do
41526 ** not read the page from disk. Return a pointer to the page,
41527 ** or 0 if the page is not in cache.
41529 ** See also sqlite3PagerGet(). The difference between this routine
41530 ** and sqlite3PagerGet() is that _get() will go to the disk and read
41531 ** in the page if the page is not already in cache. This routine
41532 ** returns NULL if the page is not in cache or if a disk I/O error
41533 ** has ever happened.
41535 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
41536 PgHdr *pPg = 0;
41537 assert( pPager!=0 );
41538 assert( pgno!=0 );
41539 assert( pPager->pPCache!=0 );
41540 assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
41541 sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
41542 return pPg;
41546 ** Release a page reference.
41548 ** If the number of references to the page drop to zero, then the
41549 ** page is added to the LRU list. When all references to all pages
41550 ** are released, a rollback occurs and the lock on the database is
41551 ** removed.
41553 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
41554 if( pPg ){
41555 Pager *pPager = pPg->pPager;
41556 sqlite3PcacheRelease(pPg);
41557 pagerUnlockIfUnused(pPager);
41561 #if defined(__APPLE__)
41563 ** Create and return a CFURLRef given a cstring containing the path to a file.
41565 static CFURLRef create_cfurl_from_cstring(const char* filePath){
41566 CFStringRef urlString = CFStringCreateWithFileSystemRepresentation(
41567 kCFAllocatorDefault, filePath);
41568 CFURLRef urlRef = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
41569 urlString, kCFURLPOSIXPathStyle, FALSE);
41570 CFRelease(urlString);
41571 return urlRef;
41573 #endif
41576 ** This function is called at the start of every write transaction.
41577 ** There must already be a RESERVED or EXCLUSIVE lock on the database
41578 ** file when this routine is called.
41580 ** Open the journal file for pager pPager and write a journal header
41581 ** to the start of it. If there are active savepoints, open the sub-journal
41582 ** as well. This function is only used when the journal file is being
41583 ** opened to write a rollback log for a transaction. It is not used
41584 ** when opening a hot journal file to roll it back.
41586 ** If the journal file is already open (as it may be in exclusive mode),
41587 ** then this function just writes a journal header to the start of the
41588 ** already open file.
41590 ** Whether or not the journal file is opened by this function, the
41591 ** Pager.pInJournal bitvec structure is allocated.
41593 ** Return SQLITE_OK if everything is successful. Otherwise, return
41594 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
41595 ** an IO error code if opening or writing the journal file fails.
41597 static int pager_open_journal(Pager *pPager){
41598 int rc = SQLITE_OK; /* Return code */
41599 sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
41601 assert( pPager->eState==PAGER_WRITER_LOCKED );
41602 assert( assert_pager_state(pPager) );
41603 assert( pPager->pInJournal==0 );
41605 /* If already in the error state, this function is a no-op. But on
41606 ** the other hand, this routine is never called if we are already in
41607 ** an error state. */
41608 if( NEVER(pPager->errCode) ) return pPager->errCode;
41610 if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41611 pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
41612 if( pPager->pInJournal==0 ){
41613 return SQLITE_NOMEM;
41616 /* Open the journal file if it is not already open. */
41617 if( !isOpen(pPager->jfd) ){
41618 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
41619 sqlite3MemJournalOpen(pPager->jfd);
41620 }else{
41621 const int flags = /* VFS flags to open journal file */
41622 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
41623 (pPager->tempFile ?
41624 (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
41625 (SQLITE_OPEN_MAIN_JOURNAL)
41627 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41628 rc = sqlite3JournalOpen(
41629 pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
41631 #else
41632 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
41633 #endif
41634 #if defined(__APPLE__)
41635 /* Set the TimeMachine exclusion metadata for the journal if it has
41636 ** been set for the database. Only do this for unix-type vfs
41637 ** implementations. */
41638 if( rc==SQLITE_OK && pPager->zFilename!=NULL
41639 && strlen(pPager->zFilename)>0
41640 && memcmp(pVfs->zName, "unix", 4)==0
41641 && ( pVfs->zName[4]=='-' || pVfs->zName[4]=='\0' ) ){
41642 CFURLRef database = create_cfurl_from_cstring(pPager->zFilename);
41643 if( CSBackupIsItemExcluded(database, NULL) ){
41644 CFURLRef journal = create_cfurl_from_cstring(pPager->zJournal);
41645 /* Ignore errors from the following exclusion call. */
41646 CSBackupSetItemExcluded(journal, TRUE, FALSE);
41647 CFRelease(journal);
41649 CFRelease(database);
41651 #endif
41653 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41657 /* Write the first journal header to the journal file and open
41658 ** the sub-journal if necessary.
41660 if( rc==SQLITE_OK ){
41661 /* TODO: Check if all of these are really required. */
41662 pPager->nRec = 0;
41663 pPager->journalOff = 0;
41664 pPager->setMaster = 0;
41665 pPager->journalHdr = 0;
41666 rc = writeJournalHdr(pPager);
41670 if( rc!=SQLITE_OK ){
41671 sqlite3BitvecDestroy(pPager->pInJournal);
41672 pPager->pInJournal = 0;
41673 }else{
41674 assert( pPager->eState==PAGER_WRITER_LOCKED );
41675 pPager->eState = PAGER_WRITER_CACHEMOD;
41678 return rc;
41682 ** Begin a write-transaction on the specified pager object. If a
41683 ** write-transaction has already been opened, this function is a no-op.
41685 ** If the exFlag argument is false, then acquire at least a RESERVED
41686 ** lock on the database file. If exFlag is true, then acquire at least
41687 ** an EXCLUSIVE lock. If such a lock is already held, no locking
41688 ** functions need be called.
41690 ** If the subjInMemory argument is non-zero, then any sub-journal opened
41691 ** within this transaction will be opened as an in-memory file. This
41692 ** has no effect if the sub-journal is already opened (as it may be when
41693 ** running in exclusive mode) or if the transaction does not require a
41694 ** sub-journal. If the subjInMemory argument is zero, then any required
41695 ** sub-journal is implemented in-memory if pPager is an in-memory database,
41696 ** or using a temporary file otherwise.
41698 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
41699 int rc = SQLITE_OK;
41701 if( pPager->errCode ) return pPager->errCode;
41702 assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
41703 pPager->subjInMemory = (u8)subjInMemory;
41705 if( ALWAYS(pPager->eState==PAGER_READER) ){
41706 assert( pPager->pInJournal==0 );
41708 if( pagerUseWal(pPager) ){
41709 /* If the pager is configured to use locking_mode=exclusive, and an
41710 ** exclusive lock on the database is not already held, obtain it now.
41712 if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
41713 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41714 if( rc!=SQLITE_OK ){
41715 return rc;
41717 sqlite3WalExclusiveMode(pPager->pWal, 1);
41720 /* Grab the write lock on the log file. If successful, upgrade to
41721 ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
41722 ** The busy-handler is not invoked if another connection already
41723 ** holds the write-lock. If possible, the upper layer will call it.
41725 rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
41726 }else{
41727 /* Obtain a RESERVED lock on the database file. If the exFlag parameter
41728 ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
41729 ** busy-handler callback can be used when upgrading to the EXCLUSIVE
41730 ** lock, but not when obtaining the RESERVED lock.
41732 rc = pagerLockDb(pPager, RESERVED_LOCK);
41733 if( rc==SQLITE_OK && exFlag ){
41734 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
41738 if( rc==SQLITE_OK ){
41739 /* Change to WRITER_LOCKED state.
41741 ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
41742 ** when it has an open transaction, but never to DBMOD or FINISHED.
41743 ** This is because in those states the code to roll back savepoint
41744 ** transactions may copy data from the sub-journal into the database
41745 ** file as well as into the page cache. Which would be incorrect in
41746 ** WAL mode.
41748 pPager->eState = PAGER_WRITER_LOCKED;
41749 pPager->dbHintSize = pPager->dbSize;
41750 pPager->dbFileSize = pPager->dbSize;
41751 pPager->dbOrigSize = pPager->dbSize;
41752 pPager->journalOff = 0;
41755 assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
41756 assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
41757 assert( assert_pager_state(pPager) );
41760 PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
41761 return rc;
41765 ** Mark a single data page as writeable. The page is written into the
41766 ** main journal or sub-journal as required. If the page is written into
41767 ** one of the journals, the corresponding bit is set in the
41768 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
41769 ** of any open savepoints as appropriate.
41771 static int pager_write(PgHdr *pPg){
41772 void *pData = pPg->pData;
41773 Pager *pPager = pPg->pPager;
41774 int rc = SQLITE_OK;
41776 /* This routine is not called unless a write-transaction has already
41777 ** been started. The journal file may or may not be open at this point.
41778 ** It is never called in the ERROR state.
41780 assert( pPager->eState==PAGER_WRITER_LOCKED
41781 || pPager->eState==PAGER_WRITER_CACHEMOD
41782 || pPager->eState==PAGER_WRITER_DBMOD
41784 assert( assert_pager_state(pPager) );
41786 /* If an error has been previously detected, report the same error
41787 ** again. This should not happen, but the check provides robustness. */
41788 if( NEVER(pPager->errCode) ) return pPager->errCode;
41790 /* Higher-level routines never call this function if database is not
41791 ** writable. But check anyway, just for robustness. */
41792 if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
41794 CHECK_PAGE(pPg);
41796 /* The journal file needs to be opened. Higher level routines have already
41797 ** obtained the necessary locks to begin the write-transaction, but the
41798 ** rollback journal might not yet be open. Open it now if this is the case.
41800 ** This is done before calling sqlite3PcacheMakeDirty() on the page.
41801 ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
41802 ** an error might occur and the pager would end up in WRITER_LOCKED state
41803 ** with pages marked as dirty in the cache.
41805 if( pPager->eState==PAGER_WRITER_LOCKED ){
41806 rc = pager_open_journal(pPager);
41807 if( rc!=SQLITE_OK ) return rc;
41809 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
41810 assert( assert_pager_state(pPager) );
41812 /* Mark the page as dirty. If the page has already been written
41813 ** to the journal then we can return right away.
41815 sqlite3PcacheMakeDirty(pPg);
41816 if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
41817 assert( !pagerUseWal(pPager) );
41818 }else{
41820 /* The transaction journal now exists and we have a RESERVED or an
41821 ** EXCLUSIVE lock on the main database file. Write the current page to
41822 ** the transaction journal if it is not there already.
41824 if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
41825 assert( pagerUseWal(pPager)==0 );
41826 if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
41827 u32 cksum;
41828 char *pData2;
41829 i64 iOff = pPager->journalOff;
41831 /* We should never write to the journal file the page that
41832 ** contains the database locks. The following assert verifies
41833 ** that we do not. */
41834 assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
41836 assert( pPager->journalHdr<=pPager->journalOff );
41837 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
41838 cksum = pager_cksum(pPager, (u8*)pData2);
41840 /* Even if an IO or diskfull error occurs while journalling the
41841 ** page in the block above, set the need-sync flag for the page.
41842 ** Otherwise, when the transaction is rolled back, the logic in
41843 ** playback_one_page() will think that the page needs to be restored
41844 ** in the database file. And if an IO error occurs while doing so,
41845 ** then corruption may follow.
41847 pPg->flags |= PGHDR_NEED_SYNC;
41849 rc = write32bits(pPager->jfd, iOff, pPg->pgno);
41850 if( rc!=SQLITE_OK ) return rc;
41851 rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
41852 if( rc!=SQLITE_OK ) return rc;
41853 rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
41854 if( rc!=SQLITE_OK ) return rc;
41856 IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
41857 pPager->journalOff, pPager->pageSize));
41858 PAGER_INCR(sqlite3_pager_writej_count);
41859 PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
41860 PAGERID(pPager), pPg->pgno,
41861 ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
41863 pPager->journalOff += 8 + pPager->pageSize;
41864 pPager->nRec++;
41865 assert( pPager->pInJournal!=0 );
41866 rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
41867 testcase( rc==SQLITE_NOMEM );
41868 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
41869 rc |= addToSavepointBitvecs(pPager, pPg->pgno);
41870 if( rc!=SQLITE_OK ){
41871 assert( rc==SQLITE_NOMEM );
41872 return rc;
41874 }else{
41875 if( pPager->eState!=PAGER_WRITER_DBMOD ){
41876 pPg->flags |= PGHDR_NEED_SYNC;
41878 PAGERTRACE(("APPEND %d page %d needSync=%d\n",
41879 PAGERID(pPager), pPg->pgno,
41880 ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
41884 /* If the statement journal is open and the page is not in it,
41885 ** then write the current page to the statement journal. Note that
41886 ** the statement journal format differs from the standard journal format
41887 ** in that it omits the checksums and the header.
41889 if( subjRequiresPage(pPg) ){
41890 rc = subjournalPage(pPg);
41894 /* Update the database size and return.
41896 if( pPager->dbSize<pPg->pgno ){
41897 pPager->dbSize = pPg->pgno;
41899 return rc;
41903 ** Mark a data page as writeable. This routine must be called before
41904 ** making changes to a page. The caller must check the return value
41905 ** of this function and be careful not to change any page data unless
41906 ** this routine returns SQLITE_OK.
41908 ** The difference between this function and pager_write() is that this
41909 ** function also deals with the special case where 2 or more pages
41910 ** fit on a single disk sector. In this case all co-resident pages
41911 ** must have been written to the journal file before returning.
41913 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
41914 ** as appropriate. Otherwise, SQLITE_OK.
41916 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
41917 int rc = SQLITE_OK;
41919 PgHdr *pPg = pDbPage;
41920 Pager *pPager = pPg->pPager;
41921 Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
41923 assert( pPager->eState>=PAGER_WRITER_LOCKED );
41924 assert( pPager->eState!=PAGER_ERROR );
41925 assert( assert_pager_state(pPager) );
41927 if( nPagePerSector>1 ){
41928 Pgno nPageCount; /* Total number of pages in database file */
41929 Pgno pg1; /* First page of the sector pPg is located on. */
41930 int nPage = 0; /* Number of pages starting at pg1 to journal */
41931 int ii; /* Loop counter */
41932 int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
41934 /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
41935 ** a journal header to be written between the pages journaled by
41936 ** this function.
41938 assert( !MEMDB );
41939 assert( pPager->doNotSyncSpill==0 );
41940 pPager->doNotSyncSpill++;
41942 /* This trick assumes that both the page-size and sector-size are
41943 ** an integer power of 2. It sets variable pg1 to the identifier
41944 ** of the first page of the sector pPg is located on.
41946 pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
41948 nPageCount = pPager->dbSize;
41949 if( pPg->pgno>nPageCount ){
41950 nPage = (pPg->pgno - pg1)+1;
41951 }else if( (pg1+nPagePerSector-1)>nPageCount ){
41952 nPage = nPageCount+1-pg1;
41953 }else{
41954 nPage = nPagePerSector;
41956 assert(nPage>0);
41957 assert(pg1<=pPg->pgno);
41958 assert((pg1+nPage)>pPg->pgno);
41960 for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
41961 Pgno pg = pg1+ii;
41962 PgHdr *pPage;
41963 if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
41964 if( pg!=PAGER_MJ_PGNO(pPager) ){
41965 rc = sqlite3PagerGet(pPager, pg, &pPage);
41966 if( rc==SQLITE_OK ){
41967 rc = pager_write(pPage);
41968 if( pPage->flags&PGHDR_NEED_SYNC ){
41969 needSync = 1;
41971 sqlite3PagerUnref(pPage);
41974 }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
41975 if( pPage->flags&PGHDR_NEED_SYNC ){
41976 needSync = 1;
41978 sqlite3PagerUnref(pPage);
41982 /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
41983 ** starting at pg1, then it needs to be set for all of them. Because
41984 ** writing to any of these nPage pages may damage the others, the
41985 ** journal file must contain sync()ed copies of all of them
41986 ** before any of them can be written out to the database file.
41988 if( rc==SQLITE_OK && needSync ){
41989 assert( !MEMDB );
41990 for(ii=0; ii<nPage; ii++){
41991 PgHdr *pPage = pager_lookup(pPager, pg1+ii);
41992 if( pPage ){
41993 pPage->flags |= PGHDR_NEED_SYNC;
41994 sqlite3PagerUnref(pPage);
41999 assert( pPager->doNotSyncSpill==1 );
42000 pPager->doNotSyncSpill--;
42001 }else{
42002 rc = pager_write(pDbPage);
42004 return rc;
42008 ** Return TRUE if the page given in the argument was previously passed
42009 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
42010 ** to change the content of the page.
42012 #ifndef NDEBUG
42013 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
42014 return pPg->flags&PGHDR_DIRTY;
42016 #endif
42019 ** A call to this routine tells the pager that it is not necessary to
42020 ** write the information on page pPg back to the disk, even though
42021 ** that page might be marked as dirty. This happens, for example, when
42022 ** the page has been added as a leaf of the freelist and so its
42023 ** content no longer matters.
42025 ** The overlying software layer calls this routine when all of the data
42026 ** on the given page is unused. The pager marks the page as clean so
42027 ** that it does not get written to disk.
42029 ** Tests show that this optimization can quadruple the speed of large
42030 ** DELETE operations.
42032 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
42033 Pager *pPager = pPg->pPager;
42034 if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
42035 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
42036 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
42037 pPg->flags |= PGHDR_DONT_WRITE;
42038 pager_set_pagehash(pPg);
42043 ** This routine is called to increment the value of the database file
42044 ** change-counter, stored as a 4-byte big-endian integer starting at
42045 ** byte offset 24 of the pager file. The secondary change counter at
42046 ** 92 is also updated, as is the SQLite version number at offset 96.
42048 ** But this only happens if the pPager->changeCountDone flag is false.
42049 ** To avoid excess churning of page 1, the update only happens once.
42050 ** See also the pager_write_changecounter() routine that does an
42051 ** unconditional update of the change counters.
42053 ** If the isDirectMode flag is zero, then this is done by calling
42054 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
42055 ** page data. In this case the file will be updated when the current
42056 ** transaction is committed.
42058 ** The isDirectMode flag may only be non-zero if the library was compiled
42059 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
42060 ** if isDirect is non-zero, then the database file is updated directly
42061 ** by writing an updated version of page 1 using a call to the
42062 ** sqlite3OsWrite() function.
42064 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
42065 int rc = SQLITE_OK;
42067 assert( pPager->eState==PAGER_WRITER_CACHEMOD
42068 || pPager->eState==PAGER_WRITER_DBMOD
42070 assert( assert_pager_state(pPager) );
42072 /* Declare and initialize constant integer 'isDirect'. If the
42073 ** atomic-write optimization is enabled in this build, then isDirect
42074 ** is initialized to the value passed as the isDirectMode parameter
42075 ** to this function. Otherwise, it is always set to zero.
42077 ** The idea is that if the atomic-write optimization is not
42078 ** enabled at compile time, the compiler can omit the tests of
42079 ** 'isDirect' below, as well as the block enclosed in the
42080 ** "if( isDirect )" condition.
42082 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
42083 # define DIRECT_MODE 0
42084 assert( isDirectMode==0 );
42085 UNUSED_PARAMETER(isDirectMode);
42086 #else
42087 # define DIRECT_MODE isDirectMode
42088 #endif
42090 if( !pPager->changeCountDone && pPager->dbSize>0 ){
42091 PgHdr *pPgHdr; /* Reference to page 1 */
42093 assert( !pPager->tempFile && isOpen(pPager->fd) );
42095 /* Open page 1 of the file for writing. */
42096 rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
42097 assert( pPgHdr==0 || rc==SQLITE_OK );
42099 /* If page one was fetched successfully, and this function is not
42100 ** operating in direct-mode, make page 1 writable. When not in
42101 ** direct mode, page 1 is always held in cache and hence the PagerGet()
42102 ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
42104 if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
42105 rc = sqlite3PagerWrite(pPgHdr);
42108 if( rc==SQLITE_OK ){
42109 /* Actually do the update of the change counter */
42110 pager_write_changecounter(pPgHdr);
42112 /* If running in direct mode, write the contents of page 1 to the file. */
42113 if( DIRECT_MODE ){
42114 const void *zBuf;
42115 assert( pPager->dbFileSize>0 );
42116 CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
42117 if( rc==SQLITE_OK ){
42118 rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
42120 if( rc==SQLITE_OK ){
42121 pPager->changeCountDone = 1;
42123 }else{
42124 pPager->changeCountDone = 1;
42128 /* Release the page reference. */
42129 sqlite3PagerUnref(pPgHdr);
42131 return rc;
42135 ** Sync the database file to disk. This is a no-op for in-memory databases
42136 ** or pages with the Pager.noSync flag set.
42138 ** If successful, or if called on a pager for which it is a no-op, this
42139 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
42141 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
42142 int rc = SQLITE_OK;
42143 if( !pPager->noSync ){
42144 assert( !MEMDB );
42145 rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
42146 }else if( isOpen(pPager->fd) ){
42147 assert( !MEMDB );
42148 sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, (void *)&rc);
42150 return rc;
42154 ** This function may only be called while a write-transaction is active in
42155 ** rollback. If the connection is in WAL mode, this call is a no-op.
42156 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
42157 ** the database file, an attempt is made to obtain one.
42159 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
42160 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
42161 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
42162 ** returned.
42164 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
42165 int rc = SQLITE_OK;
42166 assert( pPager->eState==PAGER_WRITER_CACHEMOD
42167 || pPager->eState==PAGER_WRITER_DBMOD
42168 || pPager->eState==PAGER_WRITER_LOCKED
42170 assert( assert_pager_state(pPager) );
42171 if( 0==pagerUseWal(pPager) ){
42172 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42174 return rc;
42178 ** Sync the database file for the pager pPager. zMaster points to the name
42179 ** of a master journal file that should be written into the individual
42180 ** journal file. zMaster may be NULL, which is interpreted as no master
42181 ** journal (a single database transaction).
42183 ** This routine ensures that:
42185 ** * The database file change-counter is updated,
42186 ** * the journal is synced (unless the atomic-write optimization is used),
42187 ** * all dirty pages are written to the database file,
42188 ** * the database file is truncated (if required), and
42189 ** * the database file synced.
42191 ** The only thing that remains to commit the transaction is to finalize
42192 ** (delete, truncate or zero the first part of) the journal file (or
42193 ** delete the master journal file if specified).
42195 ** Note that if zMaster==NULL, this does not overwrite a previous value
42196 ** passed to an sqlite3PagerCommitPhaseOne() call.
42198 ** If the final parameter - noSync - is true, then the database file itself
42199 ** is not synced. The caller must call sqlite3PagerSync() directly to
42200 ** sync the database file before calling CommitPhaseTwo() to delete the
42201 ** journal file in this case.
42203 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
42204 Pager *pPager, /* Pager object */
42205 const char *zMaster, /* If not NULL, the master journal name */
42206 int noSync /* True to omit the xSync on the db file */
42208 int rc = SQLITE_OK; /* Return code */
42210 assert( pPager->eState==PAGER_WRITER_LOCKED
42211 || pPager->eState==PAGER_WRITER_CACHEMOD
42212 || pPager->eState==PAGER_WRITER_DBMOD
42213 || pPager->eState==PAGER_ERROR
42215 assert( assert_pager_state(pPager) );
42217 /* If a prior error occurred, report that error again. */
42218 if( NEVER(pPager->errCode) ) return pPager->errCode;
42220 PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
42221 pPager->zFilename, zMaster, pPager->dbSize));
42223 /* If no database changes have been made, return early. */
42224 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
42226 if( MEMDB ){
42227 /* If this is an in-memory db, or no pages have been written to, or this
42228 ** function has already been called, it is mostly a no-op. However, any
42229 ** backup in progress needs to be restarted.
42231 sqlite3BackupRestart(pPager->pBackup);
42232 }else{
42233 if( pagerUseWal(pPager) ){
42234 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
42235 PgHdr *pPageOne = 0;
42236 if( pList==0 ){
42237 /* Must have at least one page for the WAL commit flag.
42238 ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
42239 rc = sqlite3PagerGet(pPager, 1, &pPageOne);
42240 pList = pPageOne;
42241 pList->pDirty = 0;
42243 assert( pList!=0 || rc!=SQLITE_OK );
42244 if( pList ){
42245 rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1,
42246 (pPager->fullSync ? pPager->syncFlags : 0)
42249 sqlite3PagerUnref(pPageOne);
42250 if( rc==SQLITE_OK ){
42251 sqlite3PcacheCleanAll(pPager->pPCache);
42253 }else{
42254 /* The following block updates the change-counter. Exactly how it
42255 ** does this depends on whether or not the atomic-update optimization
42256 ** was enabled at compile time, and if this transaction meets the
42257 ** runtime criteria to use the operation:
42259 ** * The file-system supports the atomic-write property for
42260 ** blocks of size page-size, and
42261 ** * This commit is not part of a multi-file transaction, and
42262 ** * Exactly one page has been modified and store in the journal file.
42264 ** If the optimization was not enabled at compile time, then the
42265 ** pager_incr_changecounter() function is called to update the change
42266 ** counter in 'indirect-mode'. If the optimization is compiled in but
42267 ** is not applicable to this transaction, call sqlite3JournalCreate()
42268 ** to make sure the journal file has actually been created, then call
42269 ** pager_incr_changecounter() to update the change-counter in indirect
42270 ** mode.
42272 ** Otherwise, if the optimization is both enabled and applicable,
42273 ** then call pager_incr_changecounter() to update the change-counter
42274 ** in 'direct' mode. In this case the journal file will never be
42275 ** created for this transaction.
42277 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42278 PgHdr *pPg;
42279 assert( isOpen(pPager->jfd)
42280 || pPager->journalMode==PAGER_JOURNALMODE_OFF
42281 || pPager->journalMode==PAGER_JOURNALMODE_WAL
42283 if( !zMaster && isOpen(pPager->jfd)
42284 && pPager->journalOff==jrnlBufferSize(pPager)
42285 && pPager->dbSize>=pPager->dbOrigSize
42286 && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
42288 /* Update the db file change counter via the direct-write method. The
42289 ** following call will modify the in-memory representation of page 1
42290 ** to include the updated change counter and then write page 1
42291 ** directly to the database file. Because of the atomic-write
42292 ** property of the host file-system, this is safe.
42294 rc = pager_incr_changecounter(pPager, 1);
42295 }else{
42296 rc = sqlite3JournalCreate(pPager->jfd);
42297 if( rc==SQLITE_OK ){
42298 rc = pager_incr_changecounter(pPager, 0);
42301 #else
42302 rc = pager_incr_changecounter(pPager, 0);
42303 #endif
42304 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42306 /* If this transaction has made the database smaller, then all pages
42307 ** being discarded by the truncation must be written to the journal
42308 ** file. This can only happen in auto-vacuum mode.
42310 ** Before reading the pages with page numbers larger than the
42311 ** current value of Pager.dbSize, set dbSize back to the value
42312 ** that it took at the start of the transaction. Otherwise, the
42313 ** calls to sqlite3PagerGet() return zeroed pages instead of
42314 ** reading data from the database file.
42316 #ifndef SQLITE_OMIT_AUTOVACUUM
42317 if( pPager->dbSize<pPager->dbOrigSize
42318 && pPager->journalMode!=PAGER_JOURNALMODE_OFF
42320 Pgno i; /* Iterator variable */
42321 const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
42322 const Pgno dbSize = pPager->dbSize; /* Database image size */
42323 pPager->dbSize = pPager->dbOrigSize;
42324 for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
42325 if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
42326 PgHdr *pPage; /* Page to journal */
42327 rc = sqlite3PagerGet(pPager, i, &pPage);
42328 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42329 rc = sqlite3PagerWrite(pPage);
42330 sqlite3PagerUnref(pPage);
42331 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42334 pPager->dbSize = dbSize;
42336 #endif
42338 /* Write the master journal name into the journal file. If a master
42339 ** journal file name has already been written to the journal file,
42340 ** or if zMaster is NULL (no master journal), then this call is a no-op.
42342 rc = writeMasterJournal(pPager, zMaster);
42343 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42345 /* Sync the journal file and write all dirty pages to the database.
42346 ** If the atomic-update optimization is being used, this sync will not
42347 ** create the journal file or perform any real IO.
42349 ** Because the change-counter page was just modified, unless the
42350 ** atomic-update optimization is used it is almost certain that the
42351 ** journal requires a sync here. However, in locking_mode=exclusive
42352 ** on a system under memory pressure it is just possible that this is
42353 ** not the case. In this case it is likely enough that the redundant
42354 ** xSync() call will be changed to a no-op by the OS anyhow.
42356 rc = syncJournal(pPager, 0);
42357 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42359 rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
42360 if( rc!=SQLITE_OK ){
42361 assert( rc!=SQLITE_IOERR_BLOCKED );
42362 goto commit_phase_one_exit;
42364 sqlite3PcacheCleanAll(pPager->pPCache);
42366 /* If the file on disk is not the same size as the database image,
42367 ** then use pager_truncate to grow or shrink the file here.
42369 if( pPager->dbSize!=pPager->dbFileSize ){
42370 Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
42371 assert( pPager->eState==PAGER_WRITER_DBMOD );
42372 rc = pager_truncate(pPager, nNew);
42373 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42376 /* Finally, sync the database file. */
42377 if( !noSync ){
42378 rc = sqlite3PagerSync(pPager);
42380 IOTRACE(("DBSYNC %p\n", pPager))
42384 commit_phase_one_exit:
42385 if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
42386 pPager->eState = PAGER_WRITER_FINISHED;
42388 return rc;
42393 ** When this function is called, the database file has been completely
42394 ** updated to reflect the changes made by the current transaction and
42395 ** synced to disk. The journal file still exists in the file-system
42396 ** though, and if a failure occurs at this point it will eventually
42397 ** be used as a hot-journal and the current transaction rolled back.
42399 ** This function finalizes the journal file, either by deleting,
42400 ** truncating or partially zeroing it, so that it cannot be used
42401 ** for hot-journal rollback. Once this is done the transaction is
42402 ** irrevocably committed.
42404 ** If an error occurs, an IO error code is returned and the pager
42405 ** moves into the error state. Otherwise, SQLITE_OK is returned.
42407 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
42408 int rc = SQLITE_OK; /* Return code */
42410 /* This routine should not be called if a prior error has occurred.
42411 ** But if (due to a coding error elsewhere in the system) it does get
42412 ** called, just return the same error code without doing anything. */
42413 if( NEVER(pPager->errCode) ) return pPager->errCode;
42415 assert( pPager->eState==PAGER_WRITER_LOCKED
42416 || pPager->eState==PAGER_WRITER_FINISHED
42417 || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
42419 assert( assert_pager_state(pPager) );
42421 /* An optimization. If the database was not actually modified during
42422 ** this transaction, the pager is running in exclusive-mode and is
42423 ** using persistent journals, then this function is a no-op.
42425 ** The start of the journal file currently contains a single journal
42426 ** header with the nRec field set to 0. If such a journal is used as
42427 ** a hot-journal during hot-journal rollback, 0 changes will be made
42428 ** to the database file. So there is no need to zero the journal
42429 ** header. Since the pager is in exclusive mode, there is no need
42430 ** to drop any locks either.
42432 if( pPager->eState==PAGER_WRITER_LOCKED
42433 && pPager->exclusiveMode
42434 && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
42436 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
42437 pPager->eState = PAGER_READER;
42438 return SQLITE_OK;
42441 PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
42442 rc = pager_end_transaction(pPager, pPager->setMaster);
42443 return pager_error(pPager, rc);
42447 ** If a write transaction is open, then all changes made within the
42448 ** transaction are reverted and the current write-transaction is closed.
42449 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
42450 ** state if an error occurs.
42452 ** If the pager is already in PAGER_ERROR state when this function is called,
42453 ** it returns Pager.errCode immediately. No work is performed in this case.
42455 ** Otherwise, in rollback mode, this function performs two functions:
42457 ** 1) It rolls back the journal file, restoring all database file and
42458 ** in-memory cache pages to the state they were in when the transaction
42459 ** was opened, and
42461 ** 2) It finalizes the journal file, so that it is not used for hot
42462 ** rollback at any point in the future.
42464 ** Finalization of the journal file (task 2) is only performed if the
42465 ** rollback is successful.
42467 ** In WAL mode, all cache-entries containing data modified within the
42468 ** current transaction are either expelled from the cache or reverted to
42469 ** their pre-transaction state by re-reading data from the database or
42470 ** WAL files. The WAL transaction is then closed.
42472 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
42473 int rc = SQLITE_OK; /* Return code */
42474 PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
42476 /* PagerRollback() is a no-op if called in READER or OPEN state. If
42477 ** the pager is already in the ERROR state, the rollback is not
42478 ** attempted here. Instead, the error code is returned to the caller.
42480 assert( assert_pager_state(pPager) );
42481 if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
42482 if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
42484 if( pagerUseWal(pPager) ){
42485 int rc2;
42486 rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
42487 rc2 = pager_end_transaction(pPager, pPager->setMaster);
42488 if( rc==SQLITE_OK ) rc = rc2;
42489 }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
42490 int eState = pPager->eState;
42491 rc = pager_end_transaction(pPager, 0);
42492 if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
42493 /* This can happen using journal_mode=off. Move the pager to the error
42494 ** state to indicate that the contents of the cache may not be trusted.
42495 ** Any active readers will get SQLITE_ABORT.
42497 pPager->errCode = SQLITE_ABORT;
42498 pPager->eState = PAGER_ERROR;
42499 return rc;
42501 }else{
42502 rc = pager_playback(pPager, 0);
42505 assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
42506 assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
42508 /* If an error occurs during a ROLLBACK, we can no longer trust the pager
42509 ** cache. So call pager_error() on the way out to make any error persistent.
42511 return pager_error(pPager, rc);
42515 ** Return TRUE if the database file is opened read-only. Return FALSE
42516 ** if the database is (in theory) writable.
42518 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
42519 return pPager->readOnly;
42523 ** Return the number of references to the pager.
42525 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
42526 return sqlite3PcacheRefCount(pPager->pPCache);
42530 ** Return the approximate number of bytes of memory currently
42531 ** used by the pager and its associated cache.
42533 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
42534 int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
42535 + 5*sizeof(void*);
42536 return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
42537 + sqlite3MallocSize(pPager)
42538 + pPager->pageSize;
42542 ** Return the number of references to the specified page.
42544 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
42545 return sqlite3PcachePageRefcount(pPage);
42548 #ifdef SQLITE_TEST
42550 ** This routine is used for testing and analysis only.
42552 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
42553 static int a[11];
42554 a[0] = sqlite3PcacheRefCount(pPager->pPCache);
42555 a[1] = sqlite3PcachePagecount(pPager->pPCache);
42556 a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
42557 a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
42558 a[4] = pPager->eState;
42559 a[5] = pPager->errCode;
42560 a[6] = pPager->nHit;
42561 a[7] = pPager->nMiss;
42562 a[8] = 0; /* Used to be pPager->nOvfl */
42563 a[9] = pPager->nRead;
42564 a[10] = pPager->nWrite;
42565 return a;
42567 #endif
42570 ** Return true if this is an in-memory pager.
42572 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
42573 return MEMDB;
42577 ** Check that there are at least nSavepoint savepoints open. If there are
42578 ** currently less than nSavepoints open, then open one or more savepoints
42579 ** to make up the difference. If the number of savepoints is already
42580 ** equal to nSavepoint, then this function is a no-op.
42582 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
42583 ** occurs while opening the sub-journal file, then an IO error code is
42584 ** returned. Otherwise, SQLITE_OK.
42586 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
42587 int rc = SQLITE_OK; /* Return code */
42588 int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
42590 assert( pPager->eState>=PAGER_WRITER_LOCKED );
42591 assert( assert_pager_state(pPager) );
42593 if( nSavepoint>nCurrent && pPager->useJournal ){
42594 int ii; /* Iterator variable */
42595 PagerSavepoint *aNew; /* New Pager.aSavepoint array */
42597 /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
42598 ** if the allocation fails. Otherwise, zero the new portion in case a
42599 ** malloc failure occurs while populating it in the for(...) loop below.
42601 aNew = (PagerSavepoint *)sqlite3Realloc(
42602 pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
42604 if( !aNew ){
42605 return SQLITE_NOMEM;
42607 memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
42608 pPager->aSavepoint = aNew;
42610 /* Populate the PagerSavepoint structures just allocated. */
42611 for(ii=nCurrent; ii<nSavepoint; ii++){
42612 aNew[ii].nOrig = pPager->dbSize;
42613 if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
42614 aNew[ii].iOffset = pPager->journalOff;
42615 }else{
42616 aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
42618 aNew[ii].iSubRec = pPager->nSubRec;
42619 aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
42620 if( !aNew[ii].pInSavepoint ){
42621 return SQLITE_NOMEM;
42623 if( pagerUseWal(pPager) ){
42624 sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
42626 pPager->nSavepoint = ii+1;
42628 assert( pPager->nSavepoint==nSavepoint );
42629 assertTruncateConstraint(pPager);
42632 return rc;
42636 ** This function is called to rollback or release (commit) a savepoint.
42637 ** The savepoint to release or rollback need not be the most recently
42638 ** created savepoint.
42640 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
42641 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
42642 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
42643 ** that have occurred since the specified savepoint was created.
42645 ** The savepoint to rollback or release is identified by parameter
42646 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
42647 ** (the first created). A value of (Pager.nSavepoint-1) means operate
42648 ** on the most recently created savepoint. If iSavepoint is greater than
42649 ** (Pager.nSavepoint-1), then this function is a no-op.
42651 ** If a negative value is passed to this function, then the current
42652 ** transaction is rolled back. This is different to calling
42653 ** sqlite3PagerRollback() because this function does not terminate
42654 ** the transaction or unlock the database, it just restores the
42655 ** contents of the database to its original state.
42657 ** In any case, all savepoints with an index greater than iSavepoint
42658 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
42659 ** then savepoint iSavepoint is also destroyed.
42661 ** This function may return SQLITE_NOMEM if a memory allocation fails,
42662 ** or an IO error code if an IO error occurs while rolling back a
42663 ** savepoint. If no errors occur, SQLITE_OK is returned.
42665 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
42666 int rc = pPager->errCode; /* Return code */
42668 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
42669 assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
42671 if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
42672 int ii; /* Iterator variable */
42673 int nNew; /* Number of remaining savepoints after this op. */
42675 /* Figure out how many savepoints will still be active after this
42676 ** operation. Store this value in nNew. Then free resources associated
42677 ** with any savepoints that are destroyed by this operation.
42679 nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
42680 for(ii=nNew; ii<pPager->nSavepoint; ii++){
42681 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
42683 pPager->nSavepoint = nNew;
42685 /* If this is a release of the outermost savepoint, truncate
42686 ** the sub-journal to zero bytes in size. */
42687 if( op==SAVEPOINT_RELEASE ){
42688 if( nNew==0 && isOpen(pPager->sjfd) ){
42689 /* Only truncate if it is an in-memory sub-journal. */
42690 if( sqlite3IsMemJournal(pPager->sjfd) ){
42691 rc = sqlite3OsTruncate(pPager->sjfd, 0);
42692 assert( rc==SQLITE_OK );
42694 pPager->nSubRec = 0;
42697 /* Else this is a rollback operation, playback the specified savepoint.
42698 ** If this is a temp-file, it is possible that the journal file has
42699 ** not yet been opened. In this case there have been no changes to
42700 ** the database file, so the playback operation can be skipped.
42702 else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
42703 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
42704 rc = pagerPlaybackSavepoint(pPager, pSavepoint);
42705 assert(rc!=SQLITE_DONE);
42709 return rc;
42713 ** Return the full pathname of the database file.
42715 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
42716 return pPager->zFilename;
42720 ** Return the VFS structure for the pager.
42722 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
42723 return pPager->pVfs;
42727 ** Return the file handle for the database file associated
42728 ** with the pager. This might return NULL if the file has
42729 ** not yet been opened.
42731 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
42732 return pPager->fd;
42736 ** Return the full pathname of the journal file.
42738 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
42739 return pPager->zJournal;
42743 ** Return true if fsync() calls are disabled for this pager. Return FALSE
42744 ** if fsync()s are executed normally.
42746 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
42747 return pPager->noSync;
42750 #ifdef SQLITE_HAS_CODEC
42752 ** Set or retrieve the codec for this pager
42754 SQLITE_PRIVATE void sqlite3PagerSetCodec(
42755 Pager *pPager,
42756 void *(*xCodec)(void*,void*,Pgno,int),
42757 void (*xCodecSizeChng)(void*,int,int),
42758 void (*xCodecFree)(void*),
42759 void *pCodec
42761 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
42762 pPager->xCodec = pPager->memDb ? 0 : xCodec;
42763 pPager->xCodecSizeChng = xCodecSizeChng;
42764 pPager->xCodecFree = xCodecFree;
42765 pPager->pCodec = pCodec;
42766 pagerReportSize(pPager);
42768 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
42769 return pPager->pCodec;
42771 #endif
42773 #ifndef SQLITE_OMIT_AUTOVACUUM
42775 ** Move the page pPg to location pgno in the file.
42777 ** There must be no references to the page previously located at
42778 ** pgno (which we call pPgOld) though that page is allowed to be
42779 ** in cache. If the page previously located at pgno is not already
42780 ** in the rollback journal, it is not put there by by this routine.
42782 ** References to the page pPg remain valid. Updating any
42783 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
42784 ** allocated along with the page) is the responsibility of the caller.
42786 ** A transaction must be active when this routine is called. It used to be
42787 ** required that a statement transaction was not active, but this restriction
42788 ** has been removed (CREATE INDEX needs to move a page when a statement
42789 ** transaction is active).
42791 ** If the fourth argument, isCommit, is non-zero, then this page is being
42792 ** moved as part of a database reorganization just before the transaction
42793 ** is being committed. In this case, it is guaranteed that the database page
42794 ** pPg refers to will not be written to again within this transaction.
42796 ** This function may return SQLITE_NOMEM or an IO error code if an error
42797 ** occurs. Otherwise, it returns SQLITE_OK.
42799 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
42800 PgHdr *pPgOld; /* The page being overwritten. */
42801 Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
42802 int rc; /* Return code */
42803 Pgno origPgno; /* The original page number */
42805 assert( pPg->nRef>0 );
42806 assert( pPager->eState==PAGER_WRITER_CACHEMOD
42807 || pPager->eState==PAGER_WRITER_DBMOD
42809 assert( assert_pager_state(pPager) );
42811 /* In order to be able to rollback, an in-memory database must journal
42812 ** the page we are moving from.
42814 if( MEMDB ){
42815 rc = sqlite3PagerWrite(pPg);
42816 if( rc ) return rc;
42819 /* If the page being moved is dirty and has not been saved by the latest
42820 ** savepoint, then save the current contents of the page into the
42821 ** sub-journal now. This is required to handle the following scenario:
42823 ** BEGIN;
42824 ** <journal page X, then modify it in memory>
42825 ** SAVEPOINT one;
42826 ** <Move page X to location Y>
42827 ** ROLLBACK TO one;
42829 ** If page X were not written to the sub-journal here, it would not
42830 ** be possible to restore its contents when the "ROLLBACK TO one"
42831 ** statement were is processed.
42833 ** subjournalPage() may need to allocate space to store pPg->pgno into
42834 ** one or more savepoint bitvecs. This is the reason this function
42835 ** may return SQLITE_NOMEM.
42837 if( pPg->flags&PGHDR_DIRTY
42838 && subjRequiresPage(pPg)
42839 && SQLITE_OK!=(rc = subjournalPage(pPg))
42841 return rc;
42844 PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
42845 PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
42846 IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
42848 /* If the journal needs to be sync()ed before page pPg->pgno can
42849 ** be written to, store pPg->pgno in local variable needSyncPgno.
42851 ** If the isCommit flag is set, there is no need to remember that
42852 ** the journal needs to be sync()ed before database page pPg->pgno
42853 ** can be written to. The caller has already promised not to write to it.
42855 if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
42856 needSyncPgno = pPg->pgno;
42857 assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
42858 assert( pPg->flags&PGHDR_DIRTY );
42861 /* If the cache contains a page with page-number pgno, remove it
42862 ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
42863 ** page pgno before the 'move' operation, it needs to be retained
42864 ** for the page moved there.
42866 pPg->flags &= ~PGHDR_NEED_SYNC;
42867 pPgOld = pager_lookup(pPager, pgno);
42868 assert( !pPgOld || pPgOld->nRef==1 );
42869 if( pPgOld ){
42870 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
42871 if( MEMDB ){
42872 /* Do not discard pages from an in-memory database since we might
42873 ** need to rollback later. Just move the page out of the way. */
42874 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
42875 }else{
42876 sqlite3PcacheDrop(pPgOld);
42880 origPgno = pPg->pgno;
42881 sqlite3PcacheMove(pPg, pgno);
42882 sqlite3PcacheMakeDirty(pPg);
42884 /* For an in-memory database, make sure the original page continues
42885 ** to exist, in case the transaction needs to roll back. Use pPgOld
42886 ** as the original page since it has already been allocated.
42888 if( MEMDB ){
42889 assert( pPgOld );
42890 sqlite3PcacheMove(pPgOld, origPgno);
42891 sqlite3PagerUnref(pPgOld);
42894 if( needSyncPgno ){
42895 /* If needSyncPgno is non-zero, then the journal file needs to be
42896 ** sync()ed before any data is written to database file page needSyncPgno.
42897 ** Currently, no such page exists in the page-cache and the
42898 ** "is journaled" bitvec flag has been set. This needs to be remedied by
42899 ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
42900 ** flag.
42902 ** If the attempt to load the page into the page-cache fails, (due
42903 ** to a malloc() or IO failure), clear the bit in the pInJournal[]
42904 ** array. Otherwise, if the page is loaded and written again in
42905 ** this transaction, it may be written to the database file before
42906 ** it is synced into the journal file. This way, it may end up in
42907 ** the journal file twice, but that is not a problem.
42909 PgHdr *pPgHdr;
42910 rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
42911 if( rc!=SQLITE_OK ){
42912 if( needSyncPgno<=pPager->dbOrigSize ){
42913 assert( pPager->pTmpSpace!=0 );
42914 sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
42916 return rc;
42918 pPgHdr->flags |= PGHDR_NEED_SYNC;
42919 sqlite3PcacheMakeDirty(pPgHdr);
42920 sqlite3PagerUnref(pPgHdr);
42923 return SQLITE_OK;
42925 #endif
42927 /* Begin preload-cache.patch for Chromium */
42929 ** When making large allocations, there is no need to stress the heap and
42930 ** potentially hold its lock while we allocate a bunch of memory. If we know
42931 ** the allocation will be large, go directly to the OS instead of the heap.
42933 static void* allocLarge(size_t size) {
42934 #if SQLITE_OS_WIN
42935 return VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
42936 #else
42937 return sqlite3Malloc(size);
42938 #endif
42941 static void freeLarge(void* ptr) {
42942 #if SQLITE_OS_WIN
42943 VirtualFree(ptr, 0, MEM_RELEASE);
42944 #else
42945 sqlite3_free(ptr);
42946 #endif
42950 ** Addition: This will attempt to populate the database cache with
42951 ** the first N bytes of the file, where N is the total size of the cache.
42952 ** Because we can load this as one chunk from the disk, this is much faster
42953 ** than loading a subset of the pages one at a time in random order.
42955 ** The pager must be initialized before this function is called. This means a
42956 * statement must be open that has initialized the pager and is keeping the
42957 ** cache in memory.
42959 SQLITE_PRIVATE int sqlite3PagerLoadall(Pager* pPager)
42961 int i;
42962 int rc;
42963 int nMax;
42964 int loadSize;
42965 int loadPages;
42966 unsigned char *fileData;
42968 if (pPager->dbSize < 0 || pPager->pageSize < 0) {
42969 /* pager not initialized, this means a statement is not open */
42970 return SQLITE_MISUSE;
42973 /* compute sizes */
42974 nMax = sqlite3PcacheGetCachesize(pPager->pPCache);
42975 if (nMax < pPager->dbSize)
42976 loadPages = nMax;
42977 else
42978 loadPages = pPager->dbSize;
42979 loadSize = loadPages * pPager->pageSize;
42981 /* load the file as one chunk */
42982 fileData = allocLarge(loadSize);
42983 if (! fileData)
42984 return SQLITE_NOMEM;
42985 rc = sqlite3OsRead(pPager->fd, fileData, loadSize, 0);
42986 if (rc != SQLITE_OK) {
42987 freeLarge(fileData);
42988 return rc;
42991 /* Copy the data to each page. Note that the page numbers we pass to _get
42992 * are one-based, 0 is a marker for no page. We also need to check that we
42993 * haven't loaded more pages than the cache can hold total. There may have
42994 * already been a few pages loaded before, so we may fill the cache before
42995 * loading all of the pages we want to.
42997 for(i=1;
42998 i <= loadPages && sqlite3PcachePagecount(pPager->pPCache) < nMax;
42999 i++) {
43000 DbPage *pPage = 0;
43001 rc = sqlite3PagerAcquire2(pPager, i, &pPage, 0,
43002 &fileData[(i-1)*(i64)pPager->pageSize]);
43003 if (rc != SQLITE_OK)
43004 break;
43005 sqlite3PagerUnref(pPage);
43007 freeLarge(fileData);
43008 return SQLITE_OK;
43010 /* End preload-cache.patch for Chromium */
43013 ** Return a pointer to the data for the specified page.
43015 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
43016 assert( pPg->nRef>0 || pPg->pPager->memDb );
43017 return pPg->pData;
43021 ** Return a pointer to the Pager.nExtra bytes of "extra" space
43022 ** allocated along with the specified page.
43024 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
43025 return pPg->pExtra;
43029 ** Get/set the locking-mode for this pager. Parameter eMode must be one
43030 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
43031 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
43032 ** the locking-mode is set to the value specified.
43034 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
43035 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
43036 ** locking-mode.
43038 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
43039 assert( eMode==PAGER_LOCKINGMODE_QUERY
43040 || eMode==PAGER_LOCKINGMODE_NORMAL
43041 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
43042 assert( PAGER_LOCKINGMODE_QUERY<0 );
43043 assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
43044 assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
43045 if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
43046 pPager->exclusiveMode = (u8)eMode;
43048 return (int)pPager->exclusiveMode;
43052 ** Set the journal-mode for this pager. Parameter eMode must be one of:
43054 ** PAGER_JOURNALMODE_DELETE
43055 ** PAGER_JOURNALMODE_TRUNCATE
43056 ** PAGER_JOURNALMODE_PERSIST
43057 ** PAGER_JOURNALMODE_OFF
43058 ** PAGER_JOURNALMODE_MEMORY
43059 ** PAGER_JOURNALMODE_WAL
43061 ** The journalmode is set to the value specified if the change is allowed.
43062 ** The change may be disallowed for the following reasons:
43064 ** * An in-memory database can only have its journal_mode set to _OFF
43065 ** or _MEMORY.
43067 ** * Temporary databases cannot have _WAL journalmode.
43069 ** The returned indicate the current (possibly updated) journal-mode.
43071 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
43072 u8 eOld = pPager->journalMode; /* Prior journalmode */
43074 #ifdef SQLITE_DEBUG
43075 /* The print_pager_state() routine is intended to be used by the debugger
43076 ** only. We invoke it once here to suppress a compiler warning. */
43077 print_pager_state(pPager);
43078 #endif
43081 /* The eMode parameter is always valid */
43082 assert( eMode==PAGER_JOURNALMODE_DELETE
43083 || eMode==PAGER_JOURNALMODE_TRUNCATE
43084 || eMode==PAGER_JOURNALMODE_PERSIST
43085 || eMode==PAGER_JOURNALMODE_OFF
43086 || eMode==PAGER_JOURNALMODE_WAL
43087 || eMode==PAGER_JOURNALMODE_MEMORY );
43089 /* This routine is only called from the OP_JournalMode opcode, and
43090 ** the logic there will never allow a temporary file to be changed
43091 ** to WAL mode.
43093 assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
43095 /* Do allow the journalmode of an in-memory database to be set to
43096 ** anything other than MEMORY or OFF
43098 if( MEMDB ){
43099 assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
43100 if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
43101 eMode = eOld;
43105 if( eMode!=eOld ){
43107 /* Change the journal mode. */
43108 assert( pPager->eState!=PAGER_ERROR );
43109 pPager->journalMode = (u8)eMode;
43111 /* When transistioning from TRUNCATE or PERSIST to any other journal
43112 ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
43113 ** delete the journal file.
43115 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
43116 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
43117 assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
43118 assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
43119 assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
43120 assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
43122 assert( isOpen(pPager->fd) || pPager->exclusiveMode );
43123 if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
43125 /* In this case we would like to delete the journal file. If it is
43126 ** not possible, then that is not a problem. Deleting the journal file
43127 ** here is an optimization only.
43129 ** Before deleting the journal file, obtain a RESERVED lock on the
43130 ** database file. This ensures that the journal file is not deleted
43131 ** while it is in use by some other client.
43133 sqlite3OsClose(pPager->jfd);
43134 if( pPager->eLock>=RESERVED_LOCK ){
43135 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43136 }else{
43137 int rc = SQLITE_OK;
43138 int state = pPager->eState;
43139 assert( state==PAGER_OPEN || state==PAGER_READER );
43140 if( state==PAGER_OPEN ){
43141 rc = sqlite3PagerSharedLock(pPager);
43143 if( pPager->eState==PAGER_READER ){
43144 assert( rc==SQLITE_OK );
43145 rc = pagerLockDb(pPager, RESERVED_LOCK);
43147 if( rc==SQLITE_OK ){
43148 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43150 if( rc==SQLITE_OK && state==PAGER_READER ){
43151 pagerUnlockDb(pPager, SHARED_LOCK);
43152 }else if( state==PAGER_OPEN ){
43153 pager_unlock(pPager);
43155 assert( state==pPager->eState );
43160 /* Return the new journal mode */
43161 return (int)pPager->journalMode;
43165 ** Return the current journal mode.
43167 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
43168 return (int)pPager->journalMode;
43172 ** Return TRUE if the pager is in a state where it is OK to change the
43173 ** journalmode. Journalmode changes can only happen when the database
43174 ** is unmodified.
43176 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
43177 assert( assert_pager_state(pPager) );
43178 if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
43179 if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
43180 return 1;
43184 ** Get/set the size-limit used for persistent journal files.
43186 ** Setting the size limit to -1 means no limit is enforced.
43187 ** An attempt to set a limit smaller than -1 is a no-op.
43189 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
43190 if( iLimit>=-1 ){
43191 pPager->journalSizeLimit = iLimit;
43193 return pPager->journalSizeLimit;
43197 ** Return a pointer to the pPager->pBackup variable. The backup module
43198 ** in backup.c maintains the content of this variable. This module
43199 ** uses it opaquely as an argument to sqlite3BackupRestart() and
43200 ** sqlite3BackupUpdate() only.
43202 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
43203 return &pPager->pBackup;
43206 #ifndef SQLITE_OMIT_WAL
43208 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
43209 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
43210 ** or wal_blocking_checkpoint() API functions.
43212 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
43214 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
43215 int rc = SQLITE_OK;
43216 if( pPager->pWal ){
43217 rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
43218 pPager->xBusyHandler, pPager->pBusyHandlerArg,
43219 pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
43220 pnLog, pnCkpt
43223 return rc;
43226 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
43227 return sqlite3WalCallback(pPager->pWal);
43231 ** Return true if the underlying VFS for the given pager supports the
43232 ** primitives necessary for write-ahead logging.
43234 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
43235 const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
43236 return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
43240 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
43241 ** is obtained instead, immediately release it.
43243 static int pagerExclusiveLock(Pager *pPager){
43244 int rc; /* Return code */
43246 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
43247 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43248 if( rc!=SQLITE_OK ){
43249 /* If the attempt to grab the exclusive lock failed, release the
43250 ** pending lock that may have been obtained instead. */
43251 pagerUnlockDb(pPager, SHARED_LOCK);
43254 return rc;
43258 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
43259 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
43260 ** lock on the database file and use heap-memory to store the wal-index
43261 ** in. Otherwise, use the normal shared-memory.
43263 static int pagerOpenWal(Pager *pPager){
43264 int rc = SQLITE_OK;
43266 assert( pPager->pWal==0 && pPager->tempFile==0 );
43267 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
43269 /* If the pager is already in exclusive-mode, the WAL module will use
43270 ** heap-memory for the wal-index instead of the VFS shared-memory
43271 ** implementation. Take the exclusive lock now, before opening the WAL
43272 ** file, to make sure this is safe.
43274 if( pPager->exclusiveMode ){
43275 rc = pagerExclusiveLock(pPager);
43278 /* Open the connection to the log file. If this operation fails,
43279 ** (e.g. due to malloc() failure), return an error code.
43281 if( rc==SQLITE_OK ){
43282 rc = sqlite3WalOpen(pPager->pVfs,
43283 pPager->fd, pPager->zWal, pPager->exclusiveMode, &pPager->pWal
43287 return rc;
43292 ** The caller must be holding a SHARED lock on the database file to call
43293 ** this function.
43295 ** If the pager passed as the first argument is open on a real database
43296 ** file (not a temp file or an in-memory database), and the WAL file
43297 ** is not already open, make an attempt to open it now. If successful,
43298 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
43299 ** not support the xShmXXX() methods, return an error code. *pbOpen is
43300 ** not modified in either case.
43302 ** If the pager is open on a temp-file (or in-memory database), or if
43303 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
43304 ** without doing anything.
43306 SQLITE_PRIVATE int sqlite3PagerOpenWal(
43307 Pager *pPager, /* Pager object */
43308 int *pbOpen /* OUT: Set to true if call is a no-op */
43310 int rc = SQLITE_OK; /* Return code */
43312 assert( assert_pager_state(pPager) );
43313 assert( pPager->eState==PAGER_OPEN || pbOpen );
43314 assert( pPager->eState==PAGER_READER || !pbOpen );
43315 assert( pbOpen==0 || *pbOpen==0 );
43316 assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
43318 if( !pPager->tempFile && !pPager->pWal ){
43319 if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
43321 /* Close any rollback journal previously open */
43322 sqlite3OsClose(pPager->jfd);
43324 rc = pagerOpenWal(pPager);
43325 if( rc==SQLITE_OK ){
43326 pPager->journalMode = PAGER_JOURNALMODE_WAL;
43327 pPager->eState = PAGER_OPEN;
43329 }else{
43330 *pbOpen = 1;
43333 return rc;
43337 ** This function is called to close the connection to the log file prior
43338 ** to switching from WAL to rollback mode.
43340 ** Before closing the log file, this function attempts to take an
43341 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
43342 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
43343 ** If successful, the EXCLUSIVE lock is not released before returning.
43345 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
43346 int rc = SQLITE_OK;
43348 assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
43350 /* If the log file is not already open, but does exist in the file-system,
43351 ** it may need to be checkpointed before the connection can switch to
43352 ** rollback mode. Open it now so this can happen.
43354 if( !pPager->pWal ){
43355 int logexists = 0;
43356 rc = pagerLockDb(pPager, SHARED_LOCK);
43357 if( rc==SQLITE_OK ){
43358 rc = sqlite3OsAccess(
43359 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
43362 if( rc==SQLITE_OK && logexists ){
43363 rc = pagerOpenWal(pPager);
43367 /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
43368 ** the database file, the log and log-summary files will be deleted.
43370 if( rc==SQLITE_OK && pPager->pWal ){
43371 rc = pagerExclusiveLock(pPager);
43372 if( rc==SQLITE_OK ){
43373 rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
43374 pPager->pageSize, (u8*)pPager->pTmpSpace);
43375 pPager->pWal = 0;
43378 return rc;
43381 #ifdef SQLITE_HAS_CODEC
43383 ** This function is called by the wal module when writing page content
43384 ** into the log file.
43386 ** This function returns a pointer to a buffer containing the encrypted
43387 ** page content. If a malloc fails, this function may return NULL.
43389 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
43390 void *aData = 0;
43391 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
43392 return aData;
43394 #endif /* SQLITE_HAS_CODEC */
43396 #endif /* !SQLITE_OMIT_WAL */
43398 #endif /* SQLITE_OMIT_DISKIO */
43400 /************** End of pager.c ***********************************************/
43401 /************** Begin file wal.c *********************************************/
43403 ** 2010 February 1
43405 ** The author disclaims copyright to this source code. In place of
43406 ** a legal notice, here is a blessing:
43408 ** May you do good and not evil.
43409 ** May you find forgiveness for yourself and forgive others.
43410 ** May you share freely, never taking more than you give.
43412 *************************************************************************
43414 ** This file contains the implementation of a write-ahead log (WAL) used in
43415 ** "journal_mode=WAL" mode.
43417 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
43419 ** A WAL file consists of a header followed by zero or more "frames".
43420 ** Each frame records the revised content of a single page from the
43421 ** database file. All changes to the database are recorded by writing
43422 ** frames into the WAL. Transactions commit when a frame is written that
43423 ** contains a commit marker. A single WAL can and usually does record
43424 ** multiple transactions. Periodically, the content of the WAL is
43425 ** transferred back into the database file in an operation called a
43426 ** "checkpoint".
43428 ** A single WAL file can be used multiple times. In other words, the
43429 ** WAL can fill up with frames and then be checkpointed and then new
43430 ** frames can overwrite the old ones. A WAL always grows from beginning
43431 ** toward the end. Checksums and counters attached to each frame are
43432 ** used to determine which frames within the WAL are valid and which
43433 ** are leftovers from prior checkpoints.
43435 ** The WAL header is 32 bytes in size and consists of the following eight
43436 ** big-endian 32-bit unsigned integer values:
43438 ** 0: Magic number. 0x377f0682 or 0x377f0683
43439 ** 4: File format version. Currently 3007000
43440 ** 8: Database page size. Example: 1024
43441 ** 12: Checkpoint sequence number
43442 ** 16: Salt-1, random integer incremented with each checkpoint
43443 ** 20: Salt-2, a different random integer changing with each ckpt
43444 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
43445 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
43447 ** Immediately following the wal-header are zero or more frames. Each
43448 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
43449 ** of page data. The frame-header is six big-endian 32-bit unsigned
43450 ** integer values, as follows:
43452 ** 0: Page number.
43453 ** 4: For commit records, the size of the database image in pages
43454 ** after the commit. For all other records, zero.
43455 ** 8: Salt-1 (copied from the header)
43456 ** 12: Salt-2 (copied from the header)
43457 ** 16: Checksum-1.
43458 ** 20: Checksum-2.
43460 ** A frame is considered valid if and only if the following conditions are
43461 ** true:
43463 ** (1) The salt-1 and salt-2 values in the frame-header match
43464 ** salt values in the wal-header
43466 ** (2) The checksum values in the final 8 bytes of the frame-header
43467 ** exactly match the checksum computed consecutively on the
43468 ** WAL header and the first 8 bytes and the content of all frames
43469 ** up to and including the current frame.
43471 ** The checksum is computed using 32-bit big-endian integers if the
43472 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
43473 ** is computed using little-endian if the magic number is 0x377f0682.
43474 ** The checksum values are always stored in the frame header in a
43475 ** big-endian format regardless of which byte order is used to compute
43476 ** the checksum. The checksum is computed by interpreting the input as
43477 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
43478 ** algorithm used for the checksum is as follows:
43480 ** for i from 0 to n-1 step 2:
43481 ** s0 += x[i] + s1;
43482 ** s1 += x[i+1] + s0;
43483 ** endfor
43485 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
43486 ** in reverse order (the largest fibonacci weight occurs on the first element
43487 ** of the sequence being summed.) The s1 value spans all 32-bit
43488 ** terms of the sequence whereas s0 omits the final term.
43490 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
43491 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
43492 ** The VFS.xSync operations serve as write barriers - all writes launched
43493 ** before the xSync must complete before any write that launches after the
43494 ** xSync begins.
43496 ** After each checkpoint, the salt-1 value is incremented and the salt-2
43497 ** value is randomized. This prevents old and new frames in the WAL from
43498 ** being considered valid at the same time and being checkpointing together
43499 ** following a crash.
43501 ** READER ALGORITHM
43503 ** To read a page from the database (call it page number P), a reader
43504 ** first checks the WAL to see if it contains page P. If so, then the
43505 ** last valid instance of page P that is a followed by a commit frame
43506 ** or is a commit frame itself becomes the value read. If the WAL
43507 ** contains no copies of page P that are valid and which are a commit
43508 ** frame or are followed by a commit frame, then page P is read from
43509 ** the database file.
43511 ** To start a read transaction, the reader records the index of the last
43512 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
43513 ** for all subsequent read operations. New transactions can be appended
43514 ** to the WAL, but as long as the reader uses its original mxFrame value
43515 ** and ignores the newly appended content, it will see a consistent snapshot
43516 ** of the database from a single point in time. This technique allows
43517 ** multiple concurrent readers to view different versions of the database
43518 ** content simultaneously.
43520 ** The reader algorithm in the previous paragraphs works correctly, but
43521 ** because frames for page P can appear anywhere within the WAL, the
43522 ** reader has to scan the entire WAL looking for page P frames. If the
43523 ** WAL is large (multiple megabytes is typical) that scan can be slow,
43524 ** and read performance suffers. To overcome this problem, a separate
43525 ** data structure called the wal-index is maintained to expedite the
43526 ** search for frames of a particular page.
43528 ** WAL-INDEX FORMAT
43530 ** Conceptually, the wal-index is shared memory, though VFS implementations
43531 ** might choose to implement the wal-index using a mmapped file. Because
43532 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
43533 ** on a network filesystem. All users of the database must be able to
43534 ** share memory.
43536 ** The wal-index is transient. After a crash, the wal-index can (and should
43537 ** be) reconstructed from the original WAL file. In fact, the VFS is required
43538 ** to either truncate or zero the header of the wal-index when the last
43539 ** connection to it closes. Because the wal-index is transient, it can
43540 ** use an architecture-specific format; it does not have to be cross-platform.
43541 ** Hence, unlike the database and WAL file formats which store all values
43542 ** as big endian, the wal-index can store multi-byte values in the native
43543 ** byte order of the host computer.
43545 ** The purpose of the wal-index is to answer this question quickly: Given
43546 ** a page number P, return the index of the last frame for page P in the WAL,
43547 ** or return NULL if there are no frames for page P in the WAL.
43549 ** The wal-index consists of a header region, followed by an one or
43550 ** more index blocks.
43552 ** The wal-index header contains the total number of frames within the WAL
43553 ** in the the mxFrame field.
43555 ** Each index block except for the first contains information on
43556 ** HASHTABLE_NPAGE frames. The first index block contains information on
43557 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
43558 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
43559 ** first index block are the same size as all other index blocks in the
43560 ** wal-index.
43562 ** Each index block contains two sections, a page-mapping that contains the
43563 ** database page number associated with each wal frame, and a hash-table
43564 ** that allows readers to query an index block for a specific page number.
43565 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
43566 ** for the first index block) 32-bit page numbers. The first entry in the
43567 ** first index-block contains the database page number corresponding to the
43568 ** first frame in the WAL file. The first entry in the second index block
43569 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
43570 ** the log, and so on.
43572 ** The last index block in a wal-index usually contains less than the full
43573 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
43574 ** depending on the contents of the WAL file. This does not change the
43575 ** allocated size of the page-mapping array - the page-mapping array merely
43576 ** contains unused entries.
43578 ** Even without using the hash table, the last frame for page P
43579 ** can be found by scanning the page-mapping sections of each index block
43580 ** starting with the last index block and moving toward the first, and
43581 ** within each index block, starting at the end and moving toward the
43582 ** beginning. The first entry that equals P corresponds to the frame
43583 ** holding the content for that page.
43585 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
43586 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
43587 ** hash table for each page number in the mapping section, so the hash
43588 ** table is never more than half full. The expected number of collisions
43589 ** prior to finding a match is 1. Each entry of the hash table is an
43590 ** 1-based index of an entry in the mapping section of the same
43591 ** index block. Let K be the 1-based index of the largest entry in
43592 ** the mapping section. (For index blocks other than the last, K will
43593 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
43594 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
43595 ** contain a value of 0.
43597 ** To look for page P in the hash table, first compute a hash iKey on
43598 ** P as follows:
43600 ** iKey = (P * 383) % HASHTABLE_NSLOT
43602 ** Then start scanning entries of the hash table, starting with iKey
43603 ** (wrapping around to the beginning when the end of the hash table is
43604 ** reached) until an unused hash slot is found. Let the first unused slot
43605 ** be at index iUnused. (iUnused might be less than iKey if there was
43606 ** wrap-around.) Because the hash table is never more than half full,
43607 ** the search is guaranteed to eventually hit an unused entry. Let
43608 ** iMax be the value between iKey and iUnused, closest to iUnused,
43609 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
43610 ** no hash slot such that aHash[i]==p) then page P is not in the
43611 ** current index block. Otherwise the iMax-th mapping entry of the
43612 ** current index block corresponds to the last entry that references
43613 ** page P.
43615 ** A hash search begins with the last index block and moves toward the
43616 ** first index block, looking for entries corresponding to page P. On
43617 ** average, only two or three slots in each index block need to be
43618 ** examined in order to either find the last entry for page P, or to
43619 ** establish that no such entry exists in the block. Each index block
43620 ** holds over 4000 entries. So two or three index blocks are sufficient
43621 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
43622 ** comparisons (on average) suffice to either locate a frame in the
43623 ** WAL or to establish that the frame does not exist in the WAL. This
43624 ** is much faster than scanning the entire 10MB WAL.
43626 ** Note that entries are added in order of increasing K. Hence, one
43627 ** reader might be using some value K0 and a second reader that started
43628 ** at a later time (after additional transactions were added to the WAL
43629 ** and to the wal-index) might be using a different value K1, where K1>K0.
43630 ** Both readers can use the same hash table and mapping section to get
43631 ** the correct result. There may be entries in the hash table with
43632 ** K>K0 but to the first reader, those entries will appear to be unused
43633 ** slots in the hash table and so the first reader will get an answer as
43634 ** if no values greater than K0 had ever been inserted into the hash table
43635 ** in the first place - which is what reader one wants. Meanwhile, the
43636 ** second reader using K1 will see additional values that were inserted
43637 ** later, which is exactly what reader two wants.
43639 ** When a rollback occurs, the value of K is decreased. Hash table entries
43640 ** that correspond to frames greater than the new K value are removed
43641 ** from the hash table at this point.
43643 #ifndef SQLITE_OMIT_WAL
43647 ** Trace output macros
43649 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43650 SQLITE_PRIVATE int sqlite3WalTrace = 0;
43651 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
43652 #else
43653 # define WALTRACE(X)
43654 #endif
43657 ** The maximum (and only) versions of the wal and wal-index formats
43658 ** that may be interpreted by this version of SQLite.
43660 ** If a client begins recovering a WAL file and finds that (a) the checksum
43661 ** values in the wal-header are correct and (b) the version field is not
43662 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
43664 ** Similarly, if a client successfully reads a wal-index header (i.e. the
43665 ** checksum test is successful) and finds that the version field is not
43666 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
43667 ** returns SQLITE_CANTOPEN.
43669 #define WAL_MAX_VERSION 3007000
43670 #define WALINDEX_MAX_VERSION 3007000
43673 ** Indices of various locking bytes. WAL_NREADER is the number
43674 ** of available reader locks and should be at least 3.
43676 #define WAL_WRITE_LOCK 0
43677 #define WAL_ALL_BUT_WRITE 1
43678 #define WAL_CKPT_LOCK 1
43679 #define WAL_RECOVER_LOCK 2
43680 #define WAL_READ_LOCK(I) (3+(I))
43681 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
43684 /* Object declarations */
43685 typedef struct WalIndexHdr WalIndexHdr;
43686 typedef struct WalIterator WalIterator;
43687 typedef struct WalCkptInfo WalCkptInfo;
43691 ** The following object holds a copy of the wal-index header content.
43693 ** The actual header in the wal-index consists of two copies of this
43694 ** object.
43696 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
43697 ** Or it can be 1 to represent a 65536-byte page. The latter case was
43698 ** added in 3.7.1 when support for 64K pages was added.
43700 struct WalIndexHdr {
43701 u32 iVersion; /* Wal-index version */
43702 u32 unused; /* Unused (padding) field */
43703 u32 iChange; /* Counter incremented each transaction */
43704 u8 isInit; /* 1 when initialized */
43705 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
43706 u16 szPage; /* Database page size in bytes. 1==64K */
43707 u32 mxFrame; /* Index of last valid frame in the WAL */
43708 u32 nPage; /* Size of database in pages */
43709 u32 aFrameCksum[2]; /* Checksum of last frame in log */
43710 u32 aSalt[2]; /* Two salt values copied from WAL header */
43711 u32 aCksum[2]; /* Checksum over all prior fields */
43715 ** A copy of the following object occurs in the wal-index immediately
43716 ** following the second copy of the WalIndexHdr. This object stores
43717 ** information used by checkpoint.
43719 ** nBackfill is the number of frames in the WAL that have been written
43720 ** back into the database. (We call the act of moving content from WAL to
43721 ** database "backfilling".) The nBackfill number is never greater than
43722 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
43723 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
43724 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
43725 ** mxFrame back to zero when the WAL is reset.
43727 ** There is one entry in aReadMark[] for each reader lock. If a reader
43728 ** holds read-lock K, then the value in aReadMark[K] is no greater than
43729 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
43730 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
43731 ** a special case; its value is never used and it exists as a place-holder
43732 ** to avoid having to offset aReadMark[] indexs by one. Readers holding
43733 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
43734 ** directly from the database.
43736 ** The value of aReadMark[K] may only be changed by a thread that
43737 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
43738 ** aReadMark[K] cannot changed while there is a reader is using that mark
43739 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
43741 ** The checkpointer may only transfer frames from WAL to database where
43742 ** the frame numbers are less than or equal to every aReadMark[] that is
43743 ** in use (that is, every aReadMark[j] for which there is a corresponding
43744 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
43745 ** largest value and will increase an unused aReadMark[] to mxFrame if there
43746 ** is not already an aReadMark[] equal to mxFrame. The exception to the
43747 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
43748 ** in the WAL has been backfilled into the database) then new readers
43749 ** will choose aReadMark[0] which has value 0 and hence such reader will
43750 ** get all their all content directly from the database file and ignore
43751 ** the WAL.
43753 ** Writers normally append new frames to the end of the WAL. However,
43754 ** if nBackfill equals mxFrame (meaning that all WAL content has been
43755 ** written back into the database) and if no readers are using the WAL
43756 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
43757 ** the writer will first "reset" the WAL back to the beginning and start
43758 ** writing new content beginning at frame 1.
43760 ** We assume that 32-bit loads are atomic and so no locks are needed in
43761 ** order to read from any aReadMark[] entries.
43763 struct WalCkptInfo {
43764 u32 nBackfill; /* Number of WAL frames backfilled into DB */
43765 u32 aReadMark[WAL_NREADER]; /* Reader marks */
43767 #define READMARK_NOT_USED 0xffffffff
43770 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
43771 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
43772 ** only support mandatory file-locks, we do not read or write data
43773 ** from the region of the file on which locks are applied.
43775 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
43776 #define WALINDEX_LOCK_RESERVED 16
43777 #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
43779 /* Size of header before each frame in wal */
43780 #define WAL_FRAME_HDRSIZE 24
43782 /* Size of write ahead log header, including checksum. */
43783 /* #define WAL_HDRSIZE 24 */
43784 #define WAL_HDRSIZE 32
43786 /* WAL magic value. Either this value, or the same value with the least
43787 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
43788 ** big-endian format in the first 4 bytes of a WAL file.
43790 ** If the LSB is set, then the checksums for each frame within the WAL
43791 ** file are calculated by treating all data as an array of 32-bit
43792 ** big-endian words. Otherwise, they are calculated by interpreting
43793 ** all data as 32-bit little-endian words.
43795 #define WAL_MAGIC 0x377f0682
43798 ** Return the offset of frame iFrame in the write-ahead log file,
43799 ** assuming a database page size of szPage bytes. The offset returned
43800 ** is to the start of the write-ahead log frame-header.
43802 #define walFrameOffset(iFrame, szPage) ( \
43803 WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
43807 ** An open write-ahead log file is represented by an instance of the
43808 ** following object.
43810 struct Wal {
43811 sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
43812 sqlite3_file *pDbFd; /* File handle for the database file */
43813 sqlite3_file *pWalFd; /* File handle for WAL file */
43814 u32 iCallback; /* Value to pass to log callback (or 0) */
43815 int nWiData; /* Size of array apWiData */
43816 volatile u32 **apWiData; /* Pointer to wal-index content in memory */
43817 u32 szPage; /* Database page size */
43818 i16 readLock; /* Which read lock is being held. -1 for none */
43819 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
43820 u8 writeLock; /* True if in a write transaction */
43821 u8 ckptLock; /* True if holding a checkpoint lock */
43822 u8 readOnly; /* True if the WAL file is open read-only */
43823 WalIndexHdr hdr; /* Wal-index header for current transaction */
43824 const char *zWalName; /* Name of WAL file */
43825 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
43826 #ifdef SQLITE_DEBUG
43827 u8 lockError; /* True if a locking error has occurred */
43828 #endif
43832 ** Candidate values for Wal.exclusiveMode.
43834 #define WAL_NORMAL_MODE 0
43835 #define WAL_EXCLUSIVE_MODE 1
43836 #define WAL_HEAPMEMORY_MODE 2
43839 ** Each page of the wal-index mapping contains a hash-table made up of
43840 ** an array of HASHTABLE_NSLOT elements of the following type.
43842 typedef u16 ht_slot;
43845 ** This structure is used to implement an iterator that loops through
43846 ** all frames in the WAL in database page order. Where two or more frames
43847 ** correspond to the same database page, the iterator visits only the
43848 ** frame most recently written to the WAL (in other words, the frame with
43849 ** the largest index).
43851 ** The internals of this structure are only accessed by:
43853 ** walIteratorInit() - Create a new iterator,
43854 ** walIteratorNext() - Step an iterator,
43855 ** walIteratorFree() - Free an iterator.
43857 ** This functionality is used by the checkpoint code (see walCheckpoint()).
43859 struct WalIterator {
43860 int iPrior; /* Last result returned from the iterator */
43861 int nSegment; /* Number of entries in aSegment[] */
43862 struct WalSegment {
43863 int iNext; /* Next slot in aIndex[] not yet returned */
43864 ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
43865 u32 *aPgno; /* Array of page numbers. */
43866 int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
43867 int iZero; /* Frame number associated with aPgno[0] */
43868 } aSegment[1]; /* One for every 32KB page in the wal-index */
43872 ** Define the parameters of the hash tables in the wal-index file. There
43873 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
43874 ** wal-index.
43876 ** Changing any of these constants will alter the wal-index format and
43877 ** create incompatibilities.
43879 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
43880 #define HASHTABLE_HASH_1 383 /* Should be prime */
43881 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
43884 ** The block of page numbers associated with the first hash-table in a
43885 ** wal-index is smaller than usual. This is so that there is a complete
43886 ** hash-table on each aligned 32KB page of the wal-index.
43888 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
43890 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
43891 #define WALINDEX_PGSZ ( \
43892 sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
43896 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
43897 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
43898 ** numbered from zero.
43900 ** If this call is successful, *ppPage is set to point to the wal-index
43901 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
43902 ** then an SQLite error code is returned and *ppPage is set to 0.
43904 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
43905 int rc = SQLITE_OK;
43907 /* Enlarge the pWal->apWiData[] array if required */
43908 if( pWal->nWiData<=iPage ){
43909 int nByte = sizeof(u32*)*(iPage+1);
43910 volatile u32 **apNew;
43911 apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
43912 if( !apNew ){
43913 *ppPage = 0;
43914 return SQLITE_NOMEM;
43916 memset((void*)&apNew[pWal->nWiData], 0,
43917 sizeof(u32*)*(iPage+1-pWal->nWiData));
43918 pWal->apWiData = apNew;
43919 pWal->nWiData = iPage+1;
43922 /* Request a pointer to the required page from the VFS */
43923 if( pWal->apWiData[iPage]==0 ){
43924 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
43925 pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
43926 if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
43927 }else{
43928 rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
43929 pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
43934 *ppPage = pWal->apWiData[iPage];
43935 assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
43936 return rc;
43940 ** Return a pointer to the WalCkptInfo structure in the wal-index.
43942 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
43943 assert( pWal->nWiData>0 && pWal->apWiData[0] );
43944 return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
43948 ** Return a pointer to the WalIndexHdr structure in the wal-index.
43950 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
43951 assert( pWal->nWiData>0 && pWal->apWiData[0] );
43952 return (volatile WalIndexHdr*)pWal->apWiData[0];
43956 ** The argument to this macro must be of type u32. On a little-endian
43957 ** architecture, it returns the u32 value that results from interpreting
43958 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
43959 ** returns the value that would be produced by intepreting the 4 bytes
43960 ** of the input value as a little-endian integer.
43962 #define BYTESWAP32(x) ( \
43963 (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
43964 + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
43968 ** Generate or extend an 8 byte checksum based on the data in
43969 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
43970 ** initial values of 0 and 0 if aIn==NULL).
43972 ** The checksum is written back into aOut[] before returning.
43974 ** nByte must be a positive multiple of 8.
43976 static void walChecksumBytes(
43977 int nativeCksum, /* True for native byte-order, false for non-native */
43978 u8 *a, /* Content to be checksummed */
43979 int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
43980 const u32 *aIn, /* Initial checksum value input */
43981 u32 *aOut /* OUT: Final checksum value output */
43983 u32 s1, s2;
43984 u32 *aData = (u32 *)a;
43985 u32 *aEnd = (u32 *)&a[nByte];
43987 if( aIn ){
43988 s1 = aIn[0];
43989 s2 = aIn[1];
43990 }else{
43991 s1 = s2 = 0;
43994 assert( nByte>=8 );
43995 assert( (nByte&0x00000007)==0 );
43997 if( nativeCksum ){
43998 do {
43999 s1 += *aData++ + s2;
44000 s2 += *aData++ + s1;
44001 }while( aData<aEnd );
44002 }else{
44003 do {
44004 s1 += BYTESWAP32(aData[0]) + s2;
44005 s2 += BYTESWAP32(aData[1]) + s1;
44006 aData += 2;
44007 }while( aData<aEnd );
44010 aOut[0] = s1;
44011 aOut[1] = s2;
44014 static void walShmBarrier(Wal *pWal){
44015 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
44016 sqlite3OsShmBarrier(pWal->pDbFd);
44021 ** Write the header information in pWal->hdr into the wal-index.
44023 ** The checksum on pWal->hdr is updated before it is written.
44025 static void walIndexWriteHdr(Wal *pWal){
44026 volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
44027 const int nCksum = offsetof(WalIndexHdr, aCksum);
44029 assert( pWal->writeLock );
44030 pWal->hdr.isInit = 1;
44031 pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
44032 walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
44033 memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44034 walShmBarrier(pWal);
44035 memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44039 ** This function encodes a single frame header and writes it to a buffer
44040 ** supplied by the caller. A frame-header is made up of a series of
44041 ** 4-byte big-endian integers, as follows:
44043 ** 0: Page number.
44044 ** 4: For commit records, the size of the database image in pages
44045 ** after the commit. For all other records, zero.
44046 ** 8: Salt-1 (copied from the wal-header)
44047 ** 12: Salt-2 (copied from the wal-header)
44048 ** 16: Checksum-1.
44049 ** 20: Checksum-2.
44051 static void walEncodeFrame(
44052 Wal *pWal, /* The write-ahead log */
44053 u32 iPage, /* Database page number for frame */
44054 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
44055 u8 *aData, /* Pointer to page data */
44056 u8 *aFrame /* OUT: Write encoded frame here */
44058 int nativeCksum; /* True for native byte-order checksums */
44059 u32 *aCksum = pWal->hdr.aFrameCksum;
44060 assert( WAL_FRAME_HDRSIZE==24 );
44061 sqlite3Put4byte(&aFrame[0], iPage);
44062 sqlite3Put4byte(&aFrame[4], nTruncate);
44063 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
44065 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
44066 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
44067 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
44069 sqlite3Put4byte(&aFrame[16], aCksum[0]);
44070 sqlite3Put4byte(&aFrame[20], aCksum[1]);
44074 ** Check to see if the frame with header in aFrame[] and content
44075 ** in aData[] is valid. If it is a valid frame, fill *piPage and
44076 ** *pnTruncate and return true. Return if the frame is not valid.
44078 static int walDecodeFrame(
44079 Wal *pWal, /* The write-ahead log */
44080 u32 *piPage, /* OUT: Database page number for frame */
44081 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
44082 u8 *aData, /* Pointer to page data (for checksum) */
44083 u8 *aFrame /* Frame data */
44085 int nativeCksum; /* True for native byte-order checksums */
44086 u32 *aCksum = pWal->hdr.aFrameCksum;
44087 u32 pgno; /* Page number of the frame */
44088 assert( WAL_FRAME_HDRSIZE==24 );
44090 /* A frame is only valid if the salt values in the frame-header
44091 ** match the salt values in the wal-header.
44093 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
44094 return 0;
44097 /* A frame is only valid if the page number is creater than zero.
44099 pgno = sqlite3Get4byte(&aFrame[0]);
44100 if( pgno==0 ){
44101 return 0;
44104 /* A frame is only valid if a checksum of the WAL header,
44105 ** all prior frams, the first 16 bytes of this frame-header,
44106 ** and the frame-data matches the checksum in the last 8
44107 ** bytes of this frame-header.
44109 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
44110 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
44111 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
44112 if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
44113 || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
44115 /* Checksum failed. */
44116 return 0;
44119 /* If we reach this point, the frame is valid. Return the page number
44120 ** and the new database size.
44122 *piPage = pgno;
44123 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
44124 return 1;
44128 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44130 ** Names of locks. This routine is used to provide debugging output and is not
44131 ** a part of an ordinary build.
44133 static const char *walLockName(int lockIdx){
44134 if( lockIdx==WAL_WRITE_LOCK ){
44135 return "WRITE-LOCK";
44136 }else if( lockIdx==WAL_CKPT_LOCK ){
44137 return "CKPT-LOCK";
44138 }else if( lockIdx==WAL_RECOVER_LOCK ){
44139 return "RECOVER-LOCK";
44140 }else{
44141 static char zName[15];
44142 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
44143 lockIdx-WAL_READ_LOCK(0));
44144 return zName;
44147 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
44151 ** Set or release locks on the WAL. Locks are either shared or exclusive.
44152 ** A lock cannot be moved directly between shared and exclusive - it must go
44153 ** through the unlocked state first.
44155 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
44157 static int walLockShared(Wal *pWal, int lockIdx){
44158 int rc;
44159 if( pWal->exclusiveMode ) return SQLITE_OK;
44160 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44161 SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
44162 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
44163 walLockName(lockIdx), rc ? "failed" : "ok"));
44164 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44165 return rc;
44167 static void walUnlockShared(Wal *pWal, int lockIdx){
44168 if( pWal->exclusiveMode ) return;
44169 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44170 SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
44171 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
44173 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
44174 int rc;
44175 if( pWal->exclusiveMode ) return SQLITE_OK;
44176 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44177 SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
44178 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
44179 walLockName(lockIdx), n, rc ? "failed" : "ok"));
44180 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44181 return rc;
44183 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
44184 if( pWal->exclusiveMode ) return;
44185 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44186 SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
44187 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
44188 walLockName(lockIdx), n));
44192 ** Compute a hash on a page number. The resulting hash value must land
44193 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
44194 ** the hash to the next value in the event of a collision.
44196 static int walHash(u32 iPage){
44197 assert( iPage>0 );
44198 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
44199 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
44201 static int walNextHash(int iPriorHash){
44202 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
44206 ** Return pointers to the hash table and page number array stored on
44207 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
44208 ** numbered starting from 0.
44210 ** Set output variable *paHash to point to the start of the hash table
44211 ** in the wal-index file. Set *piZero to one less than the frame
44212 ** number of the first frame indexed by this hash table. If a
44213 ** slot in the hash table is set to N, it refers to frame number
44214 ** (*piZero+N) in the log.
44216 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
44217 ** first frame indexed by the hash table, frame (*piZero+1).
44219 static int walHashGet(
44220 Wal *pWal, /* WAL handle */
44221 int iHash, /* Find the iHash'th table */
44222 volatile ht_slot **paHash, /* OUT: Pointer to hash index */
44223 volatile u32 **paPgno, /* OUT: Pointer to page number array */
44224 u32 *piZero /* OUT: Frame associated with *paPgno[0] */
44226 int rc; /* Return code */
44227 volatile u32 *aPgno;
44229 rc = walIndexPage(pWal, iHash, &aPgno);
44230 assert( rc==SQLITE_OK || iHash>0 );
44232 if( rc==SQLITE_OK ){
44233 u32 iZero;
44234 volatile ht_slot *aHash;
44236 aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
44237 if( iHash==0 ){
44238 aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
44239 iZero = 0;
44240 }else{
44241 iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
44244 *paPgno = &aPgno[-1];
44245 *paHash = aHash;
44246 *piZero = iZero;
44248 return rc;
44252 ** Return the number of the wal-index page that contains the hash-table
44253 ** and page-number array that contain entries corresponding to WAL frame
44254 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
44255 ** are numbered starting from 0.
44257 static int walFramePage(u32 iFrame){
44258 int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
44259 assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
44260 && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
44261 && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
44262 && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
44263 && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
44265 return iHash;
44269 ** Return the page number associated with frame iFrame in this WAL.
44271 static u32 walFramePgno(Wal *pWal, u32 iFrame){
44272 int iHash = walFramePage(iFrame);
44273 if( iHash==0 ){
44274 return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
44276 return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
44280 ** Remove entries from the hash table that point to WAL slots greater
44281 ** than pWal->hdr.mxFrame.
44283 ** This function is called whenever pWal->hdr.mxFrame is decreased due
44284 ** to a rollback or savepoint.
44286 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
44287 ** updated. Any later hash tables will be automatically cleared when
44288 ** pWal->hdr.mxFrame advances to the point where those hash tables are
44289 ** actually needed.
44291 static void walCleanupHash(Wal *pWal){
44292 volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
44293 volatile u32 *aPgno = 0; /* Page number array for hash table */
44294 u32 iZero = 0; /* frame == (aHash[x]+iZero) */
44295 int iLimit = 0; /* Zero values greater than this */
44296 int nByte; /* Number of bytes to zero in aPgno[] */
44297 int i; /* Used to iterate through aHash[] */
44299 assert( pWal->writeLock );
44300 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
44301 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
44302 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
44304 if( pWal->hdr.mxFrame==0 ) return;
44306 /* Obtain pointers to the hash-table and page-number array containing
44307 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
44308 ** that the page said hash-table and array reside on is already mapped.
44310 assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
44311 assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
44312 walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
44314 /* Zero all hash-table entries that correspond to frame numbers greater
44315 ** than pWal->hdr.mxFrame.
44317 iLimit = pWal->hdr.mxFrame - iZero;
44318 assert( iLimit>0 );
44319 for(i=0; i<HASHTABLE_NSLOT; i++){
44320 if( aHash[i]>iLimit ){
44321 aHash[i] = 0;
44325 /* Zero the entries in the aPgno array that correspond to frames with
44326 ** frame numbers greater than pWal->hdr.mxFrame.
44328 nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
44329 memset((void *)&aPgno[iLimit+1], 0, nByte);
44331 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44332 /* Verify that the every entry in the mapping region is still reachable
44333 ** via the hash table even after the cleanup.
44335 if( iLimit ){
44336 int i; /* Loop counter */
44337 int iKey; /* Hash key */
44338 for(i=1; i<=iLimit; i++){
44339 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44340 if( aHash[iKey]==i ) break;
44342 assert( aHash[iKey]==i );
44345 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44350 ** Set an entry in the wal-index that will map database page number
44351 ** pPage into WAL frame iFrame.
44353 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
44354 int rc; /* Return code */
44355 u32 iZero = 0; /* One less than frame number of aPgno[1] */
44356 volatile u32 *aPgno = 0; /* Page number array */
44357 volatile ht_slot *aHash = 0; /* Hash table */
44359 rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
44361 /* Assuming the wal-index file was successfully mapped, populate the
44362 ** page number array and hash table entry.
44364 if( rc==SQLITE_OK ){
44365 int iKey; /* Hash table key */
44366 int idx; /* Value to write to hash-table slot */
44367 int nCollide; /* Number of hash collisions */
44369 idx = iFrame - iZero;
44370 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
44372 /* If this is the first entry to be added to this hash-table, zero the
44373 ** entire hash table and aPgno[] array before proceding.
44375 if( idx==1 ){
44376 int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
44377 memset((void*)&aPgno[1], 0, nByte);
44380 /* If the entry in aPgno[] is already set, then the previous writer
44381 ** must have exited unexpectedly in the middle of a transaction (after
44382 ** writing one or more dirty pages to the WAL to free up memory).
44383 ** Remove the remnants of that writers uncommitted transaction from
44384 ** the hash-table before writing any new entries.
44386 if( aPgno[idx] ){
44387 walCleanupHash(pWal);
44388 assert( !aPgno[idx] );
44391 /* Write the aPgno[] array entry and the hash-table slot. */
44392 nCollide = idx;
44393 for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
44394 if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
44396 aPgno[idx] = iPage;
44397 aHash[iKey] = (ht_slot)idx;
44399 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44400 /* Verify that the number of entries in the hash table exactly equals
44401 ** the number of entries in the mapping region.
44404 int i; /* Loop counter */
44405 int nEntry = 0; /* Number of entries in the hash table */
44406 for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
44407 assert( nEntry==idx );
44410 /* Verify that the every entry in the mapping region is reachable
44411 ** via the hash table. This turns out to be a really, really expensive
44412 ** thing to check, so only do this occasionally - not on every
44413 ** iteration.
44415 if( (idx&0x3ff)==0 ){
44416 int i; /* Loop counter */
44417 for(i=1; i<=idx; i++){
44418 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44419 if( aHash[iKey]==i ) break;
44421 assert( aHash[iKey]==i );
44424 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44428 return rc;
44433 ** Recover the wal-index by reading the write-ahead log file.
44435 ** This routine first tries to establish an exclusive lock on the
44436 ** wal-index to prevent other threads/processes from doing anything
44437 ** with the WAL or wal-index while recovery is running. The
44438 ** WAL_RECOVER_LOCK is also held so that other threads will know
44439 ** that this thread is running recovery. If unable to establish
44440 ** the necessary locks, this routine returns SQLITE_BUSY.
44442 static int walIndexRecover(Wal *pWal){
44443 int rc; /* Return Code */
44444 i64 nSize; /* Size of log file */
44445 u32 aFrameCksum[2] = {0, 0};
44446 int iLock; /* Lock offset to lock for checkpoint */
44447 int nLock; /* Number of locks to hold */
44449 /* Obtain an exclusive lock on all byte in the locking range not already
44450 ** locked by the caller. The caller is guaranteed to have locked the
44451 ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
44452 ** If successful, the same bytes that are locked here are unlocked before
44453 ** this function returns.
44455 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
44456 assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
44457 assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
44458 assert( pWal->writeLock );
44459 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
44460 nLock = SQLITE_SHM_NLOCK - iLock;
44461 rc = walLockExclusive(pWal, iLock, nLock);
44462 if( rc ){
44463 return rc;
44465 WALTRACE(("WAL%p: recovery begin...\n", pWal));
44467 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
44469 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
44470 if( rc!=SQLITE_OK ){
44471 goto recovery_error;
44474 if( nSize>WAL_HDRSIZE ){
44475 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
44476 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
44477 int szFrame; /* Number of bytes in buffer aFrame[] */
44478 u8 *aData; /* Pointer to data part of aFrame buffer */
44479 int iFrame; /* Index of last frame read */
44480 i64 iOffset; /* Next offset to read from log file */
44481 int szPage; /* Page size according to the log */
44482 u32 magic; /* Magic value read from WAL header */
44483 u32 version; /* Magic value read from WAL header */
44485 /* Read in the WAL header. */
44486 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
44487 if( rc!=SQLITE_OK ){
44488 goto recovery_error;
44491 /* If the database page size is not a power of two, or is greater than
44492 ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
44493 ** data. Similarly, if the 'magic' value is invalid, ignore the whole
44494 ** WAL file.
44496 magic = sqlite3Get4byte(&aBuf[0]);
44497 szPage = sqlite3Get4byte(&aBuf[8]);
44498 if( (magic&0xFFFFFFFE)!=WAL_MAGIC
44499 || szPage&(szPage-1)
44500 || szPage>SQLITE_MAX_PAGE_SIZE
44501 || szPage<512
44503 goto finished;
44505 pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
44506 pWal->szPage = szPage;
44507 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
44508 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
44510 /* Verify that the WAL header checksum is correct */
44511 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
44512 aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
44514 if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
44515 || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
44517 goto finished;
44520 /* Verify that the version number on the WAL format is one that
44521 ** are able to understand */
44522 version = sqlite3Get4byte(&aBuf[4]);
44523 if( version!=WAL_MAX_VERSION ){
44524 rc = SQLITE_CANTOPEN_BKPT;
44525 goto finished;
44528 /* Malloc a buffer to read frames into. */
44529 szFrame = szPage + WAL_FRAME_HDRSIZE;
44530 aFrame = (u8 *)sqlite3_malloc(szFrame);
44531 if( !aFrame ){
44532 rc = SQLITE_NOMEM;
44533 goto recovery_error;
44535 aData = &aFrame[WAL_FRAME_HDRSIZE];
44537 /* Read all frames from the log file. */
44538 iFrame = 0;
44539 for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
44540 u32 pgno; /* Database page number for frame */
44541 u32 nTruncate; /* dbsize field from frame header */
44542 int isValid; /* True if this frame is valid */
44544 /* Read and decode the next log frame. */
44545 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
44546 if( rc!=SQLITE_OK ) break;
44547 isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
44548 if( !isValid ) break;
44549 rc = walIndexAppend(pWal, ++iFrame, pgno);
44550 if( rc!=SQLITE_OK ) break;
44552 /* If nTruncate is non-zero, this is a commit record. */
44553 if( nTruncate ){
44554 pWal->hdr.mxFrame = iFrame;
44555 pWal->hdr.nPage = nTruncate;
44556 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
44557 testcase( szPage<=32768 );
44558 testcase( szPage>=65536 );
44559 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
44560 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
44564 sqlite3_free(aFrame);
44567 finished:
44568 if( rc==SQLITE_OK ){
44569 volatile WalCkptInfo *pInfo;
44570 int i;
44571 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
44572 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
44573 walIndexWriteHdr(pWal);
44575 /* Reset the checkpoint-header. This is safe because this thread is
44576 ** currently holding locks that exclude all other readers, writers and
44577 ** checkpointers.
44579 pInfo = walCkptInfo(pWal);
44580 pInfo->nBackfill = 0;
44581 pInfo->aReadMark[0] = 0;
44582 for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
44584 /* If more than one frame was recovered from the log file, report an
44585 ** event via sqlite3_log(). This is to help with identifying performance
44586 ** problems caused by applications routinely shutting down without
44587 ** checkpointing the log file.
44589 if( pWal->hdr.nPage ){
44590 sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
44591 pWal->hdr.nPage, pWal->zWalName
44596 recovery_error:
44597 WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
44598 walUnlockExclusive(pWal, iLock, nLock);
44599 return rc;
44603 ** Close an open wal-index.
44605 static void walIndexClose(Wal *pWal, int isDelete){
44606 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44607 int i;
44608 for(i=0; i<pWal->nWiData; i++){
44609 sqlite3_free((void *)pWal->apWiData[i]);
44610 pWal->apWiData[i] = 0;
44612 }else{
44613 sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
44618 ** Open a connection to the WAL file zWalName. The database file must
44619 ** already be opened on connection pDbFd. The buffer that zWalName points
44620 ** to must remain valid for the lifetime of the returned Wal* handle.
44622 ** A SHARED lock should be held on the database file when this function
44623 ** is called. The purpose of this SHARED lock is to prevent any other
44624 ** client from unlinking the WAL or wal-index file. If another process
44625 ** were to do this just after this client opened one of these files, the
44626 ** system would be badly broken.
44628 ** If the log file is successfully opened, SQLITE_OK is returned and
44629 ** *ppWal is set to point to a new WAL handle. If an error occurs,
44630 ** an SQLite error code is returned and *ppWal is left unmodified.
44632 SQLITE_PRIVATE int sqlite3WalOpen(
44633 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
44634 sqlite3_file *pDbFd, /* The open database file */
44635 const char *zWalName, /* Name of the WAL file */
44636 int bNoShm, /* True to run in heap-memory mode */
44637 Wal **ppWal /* OUT: Allocated Wal handle */
44639 int rc; /* Return Code */
44640 Wal *pRet; /* Object to allocate and return */
44641 int flags; /* Flags passed to OsOpen() */
44643 assert( zWalName && zWalName[0] );
44644 assert( pDbFd );
44646 /* In the amalgamation, the os_unix.c and os_win.c source files come before
44647 ** this source file. Verify that the #defines of the locking byte offsets
44648 ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
44650 #ifdef WIN_SHM_BASE
44651 assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
44652 #endif
44653 #ifdef UNIX_SHM_BASE
44654 assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
44655 #endif
44658 /* Allocate an instance of struct Wal to return. */
44659 *ppWal = 0;
44660 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
44661 if( !pRet ){
44662 return SQLITE_NOMEM;
44665 pRet->pVfs = pVfs;
44666 pRet->pWalFd = (sqlite3_file *)&pRet[1];
44667 pRet->pDbFd = pDbFd;
44668 pRet->readLock = -1;
44669 pRet->zWalName = zWalName;
44670 pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
44672 /* Open file handle on the write-ahead log file. */
44673 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
44674 rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
44675 if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
44676 pRet->readOnly = 1;
44679 if( rc!=SQLITE_OK ){
44680 walIndexClose(pRet, 0);
44681 sqlite3OsClose(pRet->pWalFd);
44682 sqlite3_free(pRet);
44683 }else{
44684 *ppWal = pRet;
44685 WALTRACE(("WAL%d: opened\n", pRet));
44687 return rc;
44691 ** Find the smallest page number out of all pages held in the WAL that
44692 ** has not been returned by any prior invocation of this method on the
44693 ** same WalIterator object. Write into *piFrame the frame index where
44694 ** that page was last written into the WAL. Write into *piPage the page
44695 ** number.
44697 ** Return 0 on success. If there are no pages in the WAL with a page
44698 ** number larger than *piPage, then return 1.
44700 static int walIteratorNext(
44701 WalIterator *p, /* Iterator */
44702 u32 *piPage, /* OUT: The page number of the next page */
44703 u32 *piFrame /* OUT: Wal frame index of next page */
44705 u32 iMin; /* Result pgno must be greater than iMin */
44706 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
44707 int i; /* For looping through segments */
44709 iMin = p->iPrior;
44710 assert( iMin<0xffffffff );
44711 for(i=p->nSegment-1; i>=0; i--){
44712 struct WalSegment *pSegment = &p->aSegment[i];
44713 while( pSegment->iNext<pSegment->nEntry ){
44714 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
44715 if( iPg>iMin ){
44716 if( iPg<iRet ){
44717 iRet = iPg;
44718 *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
44720 break;
44722 pSegment->iNext++;
44726 *piPage = p->iPrior = iRet;
44727 return (iRet==0xFFFFFFFF);
44731 ** This function merges two sorted lists into a single sorted list.
44733 ** aLeft[] and aRight[] are arrays of indices. The sort key is
44734 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
44735 ** is guaranteed for all J<K:
44737 ** aContent[aLeft[J]] < aContent[aLeft[K]]
44738 ** aContent[aRight[J]] < aContent[aRight[K]]
44740 ** This routine overwrites aRight[] with a new (probably longer) sequence
44741 ** of indices such that the aRight[] contains every index that appears in
44742 ** either aLeft[] or the old aRight[] and such that the second condition
44743 ** above is still met.
44745 ** The aContent[aLeft[X]] values will be unique for all X. And the
44746 ** aContent[aRight[X]] values will be unique too. But there might be
44747 ** one or more combinations of X and Y such that
44749 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
44751 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
44753 static void walMerge(
44754 const u32 *aContent, /* Pages in wal - keys for the sort */
44755 ht_slot *aLeft, /* IN: Left hand input list */
44756 int nLeft, /* IN: Elements in array *paLeft */
44757 ht_slot **paRight, /* IN/OUT: Right hand input list */
44758 int *pnRight, /* IN/OUT: Elements in *paRight */
44759 ht_slot *aTmp /* Temporary buffer */
44761 int iLeft = 0; /* Current index in aLeft */
44762 int iRight = 0; /* Current index in aRight */
44763 int iOut = 0; /* Current index in output buffer */
44764 int nRight = *pnRight;
44765 ht_slot *aRight = *paRight;
44767 assert( nLeft>0 && nRight>0 );
44768 while( iRight<nRight || iLeft<nLeft ){
44769 ht_slot logpage;
44770 Pgno dbpage;
44772 if( (iLeft<nLeft)
44773 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
44775 logpage = aLeft[iLeft++];
44776 }else{
44777 logpage = aRight[iRight++];
44779 dbpage = aContent[logpage];
44781 aTmp[iOut++] = logpage;
44782 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
44784 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
44785 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
44788 *paRight = aLeft;
44789 *pnRight = iOut;
44790 memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
44794 ** Sort the elements in list aList using aContent[] as the sort key.
44795 ** Remove elements with duplicate keys, preferring to keep the
44796 ** larger aList[] values.
44798 ** The aList[] entries are indices into aContent[]. The values in
44799 ** aList[] are to be sorted so that for all J<K:
44801 ** aContent[aList[J]] < aContent[aList[K]]
44803 ** For any X and Y such that
44805 ** aContent[aList[X]] == aContent[aList[Y]]
44807 ** Keep the larger of the two values aList[X] and aList[Y] and discard
44808 ** the smaller.
44810 static void walMergesort(
44811 const u32 *aContent, /* Pages in wal */
44812 ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
44813 ht_slot *aList, /* IN/OUT: List to sort */
44814 int *pnList /* IN/OUT: Number of elements in aList[] */
44816 struct Sublist {
44817 int nList; /* Number of elements in aList */
44818 ht_slot *aList; /* Pointer to sub-list content */
44821 const int nList = *pnList; /* Size of input list */
44822 int nMerge = 0; /* Number of elements in list aMerge */
44823 ht_slot *aMerge = 0; /* List to be merged */
44824 int iList; /* Index into input list */
44825 int iSub = 0; /* Index into aSub array */
44826 struct Sublist aSub[13]; /* Array of sub-lists */
44828 memset(aSub, 0, sizeof(aSub));
44829 assert( nList<=HASHTABLE_NPAGE && nList>0 );
44830 assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
44832 for(iList=0; iList<nList; iList++){
44833 nMerge = 1;
44834 aMerge = &aList[iList];
44835 for(iSub=0; iList & (1<<iSub); iSub++){
44836 struct Sublist *p = &aSub[iSub];
44837 assert( p->aList && p->nList<=(1<<iSub) );
44838 assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
44839 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
44841 aSub[iSub].aList = aMerge;
44842 aSub[iSub].nList = nMerge;
44845 for(iSub++; iSub<ArraySize(aSub); iSub++){
44846 if( nList & (1<<iSub) ){
44847 struct Sublist *p = &aSub[iSub];
44848 assert( p->nList<=(1<<iSub) );
44849 assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
44850 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
44853 assert( aMerge==aList );
44854 *pnList = nMerge;
44856 #ifdef SQLITE_DEBUG
44858 int i;
44859 for(i=1; i<*pnList; i++){
44860 assert( aContent[aList[i]] > aContent[aList[i-1]] );
44863 #endif
44867 ** Free an iterator allocated by walIteratorInit().
44869 static void walIteratorFree(WalIterator *p){
44870 sqlite3ScratchFree(p);
44874 ** Construct a WalInterator object that can be used to loop over all
44875 ** pages in the WAL in ascending order. The caller must hold the checkpoint
44876 ** lock.
44878 ** On success, make *pp point to the newly allocated WalInterator object
44879 ** return SQLITE_OK. Otherwise, return an error code. If this routine
44880 ** returns an error, the value of *pp is undefined.
44882 ** The calling routine should invoke walIteratorFree() to destroy the
44883 ** WalIterator object when it has finished with it.
44885 static int walIteratorInit(Wal *pWal, WalIterator **pp){
44886 WalIterator *p; /* Return value */
44887 int nSegment; /* Number of segments to merge */
44888 u32 iLast; /* Last frame in log */
44889 int nByte; /* Number of bytes to allocate */
44890 int i; /* Iterator variable */
44891 ht_slot *aTmp; /* Temp space used by merge-sort */
44892 int rc = SQLITE_OK; /* Return Code */
44894 /* This routine only runs while holding the checkpoint lock. And
44895 ** it only runs if there is actually content in the log (mxFrame>0).
44897 assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
44898 iLast = pWal->hdr.mxFrame;
44900 /* Allocate space for the WalIterator object. */
44901 nSegment = walFramePage(iLast) + 1;
44902 nByte = sizeof(WalIterator)
44903 + (nSegment-1)*sizeof(struct WalSegment)
44904 + iLast*sizeof(ht_slot);
44905 p = (WalIterator *)sqlite3ScratchMalloc(nByte);
44906 if( !p ){
44907 return SQLITE_NOMEM;
44909 memset(p, 0, nByte);
44910 p->nSegment = nSegment;
44912 /* Allocate temporary space used by the merge-sort routine. This block
44913 ** of memory will be freed before this function returns.
44915 aTmp = (ht_slot *)sqlite3ScratchMalloc(
44916 sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
44918 if( !aTmp ){
44919 rc = SQLITE_NOMEM;
44922 for(i=0; rc==SQLITE_OK && i<nSegment; i++){
44923 volatile ht_slot *aHash;
44924 u32 iZero;
44925 volatile u32 *aPgno;
44927 rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
44928 if( rc==SQLITE_OK ){
44929 int j; /* Counter variable */
44930 int nEntry; /* Number of entries in this segment */
44931 ht_slot *aIndex; /* Sorted index for this segment */
44933 aPgno++;
44934 if( (i+1)==nSegment ){
44935 nEntry = (int)(iLast - iZero);
44936 }else{
44937 nEntry = (int)((u32*)aHash - (u32*)aPgno);
44939 aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
44940 iZero++;
44942 for(j=0; j<nEntry; j++){
44943 aIndex[j] = (ht_slot)j;
44945 walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
44946 p->aSegment[i].iZero = iZero;
44947 p->aSegment[i].nEntry = nEntry;
44948 p->aSegment[i].aIndex = aIndex;
44949 p->aSegment[i].aPgno = (u32 *)aPgno;
44952 sqlite3ScratchFree(aTmp);
44954 if( rc!=SQLITE_OK ){
44955 walIteratorFree(p);
44957 *pp = p;
44958 return rc;
44962 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
44963 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
44964 ** busy-handler function. Invoke it and retry the lock until either the
44965 ** lock is successfully obtained or the busy-handler returns 0.
44967 static int walBusyLock(
44968 Wal *pWal, /* WAL connection */
44969 int (*xBusy)(void*), /* Function to call when busy */
44970 void *pBusyArg, /* Context argument for xBusyHandler */
44971 int lockIdx, /* Offset of first byte to lock */
44972 int n /* Number of bytes to lock */
44974 int rc;
44975 do {
44976 rc = walLockExclusive(pWal, lockIdx, n);
44977 }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
44978 return rc;
44982 ** The cache of the wal-index header must be valid to call this function.
44983 ** Return the page-size in bytes used by the database.
44985 static int walPagesize(Wal *pWal){
44986 return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
44990 ** Copy as much content as we can from the WAL back into the database file
44991 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
44993 ** The amount of information copies from WAL to database might be limited
44994 ** by active readers. This routine will never overwrite a database page
44995 ** that a concurrent reader might be using.
44997 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
44998 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
44999 ** checkpoints are always run by a background thread or background
45000 ** process, foreground threads will never block on a lengthy fsync call.
45002 ** Fsync is called on the WAL before writing content out of the WAL and
45003 ** into the database. This ensures that if the new content is persistent
45004 ** in the WAL and can be recovered following a power-loss or hard reset.
45006 ** Fsync is also called on the database file if (and only if) the entire
45007 ** WAL content is copied into the database file. This second fsync makes
45008 ** it safe to delete the WAL since the new content will persist in the
45009 ** database file.
45011 ** This routine uses and updates the nBackfill field of the wal-index header.
45012 ** This is the only routine tha will increase the value of nBackfill.
45013 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
45014 ** its value.)
45016 ** The caller must be holding sufficient locks to ensure that no other
45017 ** checkpoint is running (in any other thread or process) at the same
45018 ** time.
45020 static int walCheckpoint(
45021 Wal *pWal, /* Wal connection */
45022 int eMode, /* One of PASSIVE, FULL or RESTART */
45023 int (*xBusyCall)(void*), /* Function to call when busy */
45024 void *pBusyArg, /* Context argument for xBusyHandler */
45025 int sync_flags, /* Flags for OsSync() (or 0) */
45026 u8 *zBuf /* Temporary buffer to use */
45028 int rc; /* Return code */
45029 int szPage; /* Database page-size */
45030 WalIterator *pIter = 0; /* Wal iterator context */
45031 u32 iDbpage = 0; /* Next database page to write */
45032 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
45033 u32 mxSafeFrame; /* Max frame that can be backfilled */
45034 u32 mxPage; /* Max database page to write */
45035 int i; /* Loop counter */
45036 volatile WalCkptInfo *pInfo; /* The checkpoint status information */
45037 int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
45039 szPage = walPagesize(pWal);
45040 testcase( szPage<=32768 );
45041 testcase( szPage>=65536 );
45042 pInfo = walCkptInfo(pWal);
45043 if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
45045 /* Allocate the iterator */
45046 rc = walIteratorInit(pWal, &pIter);
45047 if( rc!=SQLITE_OK ){
45048 return rc;
45050 assert( pIter );
45052 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
45054 /* Compute in mxSafeFrame the index of the last frame of the WAL that is
45055 ** safe to write into the database. Frames beyond mxSafeFrame might
45056 ** overwrite database pages that are in use by active readers and thus
45057 ** cannot be backfilled from the WAL.
45059 mxSafeFrame = pWal->hdr.mxFrame;
45060 mxPage = pWal->hdr.nPage;
45061 for(i=1; i<WAL_NREADER; i++){
45062 u32 y = pInfo->aReadMark[i];
45063 if( mxSafeFrame>y ){
45064 assert( y<=pWal->hdr.mxFrame );
45065 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
45066 if( rc==SQLITE_OK ){
45067 pInfo->aReadMark[i] = READMARK_NOT_USED;
45068 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45069 }else if( rc==SQLITE_BUSY ){
45070 mxSafeFrame = y;
45071 xBusy = 0;
45072 }else{
45073 goto walcheckpoint_out;
45078 if( pInfo->nBackfill<mxSafeFrame
45079 && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
45081 i64 nSize; /* Current size of database file */
45082 u32 nBackfill = pInfo->nBackfill;
45084 /* Sync the WAL to disk */
45085 if( sync_flags ){
45086 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
45089 /* If the database file may grow as a result of this checkpoint, hint
45090 ** about the eventual size of the db file to the VFS layer.
45092 if( rc==SQLITE_OK ){
45093 i64 nReq = ((i64)mxPage * szPage);
45094 rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
45095 if( rc==SQLITE_OK && nSize<nReq ){
45096 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
45100 /* Iterate through the contents of the WAL, copying data to the db file. */
45101 while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
45102 i64 iOffset;
45103 assert( walFramePgno(pWal, iFrame)==iDbpage );
45104 if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
45105 iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
45106 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
45107 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
45108 if( rc!=SQLITE_OK ) break;
45109 iOffset = (iDbpage-1)*(i64)szPage;
45110 testcase( IS_BIG_INT(iOffset) );
45111 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
45112 if( rc!=SQLITE_OK ) break;
45115 /* If work was actually accomplished... */
45116 if( rc==SQLITE_OK ){
45117 if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
45118 i64 szDb = pWal->hdr.nPage*(i64)szPage;
45119 testcase( IS_BIG_INT(szDb) );
45120 rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
45121 if( rc==SQLITE_OK && sync_flags ){
45122 rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
45125 if( rc==SQLITE_OK ){
45126 pInfo->nBackfill = mxSafeFrame;
45130 /* Release the reader lock held while backfilling */
45131 walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
45134 if( rc==SQLITE_BUSY ){
45135 /* Reset the return code so as not to report a checkpoint failure
45136 ** just because there are active readers. */
45137 rc = SQLITE_OK;
45140 /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
45141 ** file has been copied into the database file, then block until all
45142 ** readers have finished using the wal file. This ensures that the next
45143 ** process to write to the database restarts the wal file.
45145 if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
45146 assert( pWal->writeLock );
45147 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
45148 rc = SQLITE_BUSY;
45149 }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
45150 assert( mxSafeFrame==pWal->hdr.mxFrame );
45151 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
45152 if( rc==SQLITE_OK ){
45153 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45158 walcheckpoint_out:
45159 walIteratorFree(pIter);
45160 return rc;
45164 ** Close a connection to a log file.
45166 SQLITE_PRIVATE int sqlite3WalClose(
45167 Wal *pWal, /* Wal to close */
45168 int sync_flags, /* Flags to pass to OsSync() (or 0) */
45169 int nBuf,
45170 u8 *zBuf /* Buffer of at least nBuf bytes */
45172 int rc = SQLITE_OK;
45173 if( pWal ){
45174 int isDelete = 0; /* True to unlink wal and wal-index files */
45176 /* If an EXCLUSIVE lock can be obtained on the database file (using the
45177 ** ordinary, rollback-mode locking methods, this guarantees that the
45178 ** connection associated with this log file is the only connection to
45179 ** the database. In this case checkpoint the database and unlink both
45180 ** the wal and wal-index files.
45182 ** The EXCLUSIVE lock is not released before returning.
45184 rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
45185 if( rc==SQLITE_OK ){
45186 if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
45187 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
45189 rc = sqlite3WalCheckpoint(
45190 pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
45192 if( rc==SQLITE_OK ){
45193 isDelete = 1;
45197 walIndexClose(pWal, isDelete);
45198 sqlite3OsClose(pWal->pWalFd);
45199 if( isDelete ){
45200 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
45202 WALTRACE(("WAL%p: closed\n", pWal));
45203 sqlite3_free((void *)pWal->apWiData);
45204 sqlite3_free(pWal);
45206 return rc;
45210 ** Try to read the wal-index header. Return 0 on success and 1 if
45211 ** there is a problem.
45213 ** The wal-index is in shared memory. Another thread or process might
45214 ** be writing the header at the same time this procedure is trying to
45215 ** read it, which might result in inconsistency. A dirty read is detected
45216 ** by verifying that both copies of the header are the same and also by
45217 ** a checksum on the header.
45219 ** If and only if the read is consistent and the header is different from
45220 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
45221 ** and *pChanged is set to 1.
45223 ** If the checksum cannot be verified return non-zero. If the header
45224 ** is read successfully and the checksum verified, return zero.
45226 static int walIndexTryHdr(Wal *pWal, int *pChanged){
45227 u32 aCksum[2]; /* Checksum on the header content */
45228 WalIndexHdr h1, h2; /* Two copies of the header content */
45229 WalIndexHdr volatile *aHdr; /* Header in shared memory */
45231 /* The first page of the wal-index must be mapped at this point. */
45232 assert( pWal->nWiData>0 && pWal->apWiData[0] );
45234 /* Read the header. This might happen concurrently with a write to the
45235 ** same area of shared memory on a different CPU in a SMP,
45236 ** meaning it is possible that an inconsistent snapshot is read
45237 ** from the file. If this happens, return non-zero.
45239 ** There are two copies of the header at the beginning of the wal-index.
45240 ** When reading, read [0] first then [1]. Writes are in the reverse order.
45241 ** Memory barriers are used to prevent the compiler or the hardware from
45242 ** reordering the reads and writes.
45244 aHdr = walIndexHdr(pWal);
45245 memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
45246 walShmBarrier(pWal);
45247 memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
45249 if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
45250 return 1; /* Dirty read */
45252 if( h1.isInit==0 ){
45253 return 1; /* Malformed header - probably all zeros */
45255 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
45256 if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
45257 return 1; /* Checksum does not match */
45260 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
45261 *pChanged = 1;
45262 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
45263 pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45264 testcase( pWal->szPage<=32768 );
45265 testcase( pWal->szPage>=65536 );
45268 /* The header was successfully read. Return zero. */
45269 return 0;
45273 ** Read the wal-index header from the wal-index and into pWal->hdr.
45274 ** If the wal-header appears to be corrupt, try to reconstruct the
45275 ** wal-index from the WAL before returning.
45277 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
45278 ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
45279 ** to 0.
45281 ** If the wal-index header is successfully read, return SQLITE_OK.
45282 ** Otherwise an SQLite error code.
45284 static int walIndexReadHdr(Wal *pWal, int *pChanged){
45285 int rc; /* Return code */
45286 int badHdr; /* True if a header read failed */
45287 volatile u32 *page0; /* Chunk of wal-index containing header */
45289 /* Ensure that page 0 of the wal-index (the page that contains the
45290 ** wal-index header) is mapped. Return early if an error occurs here.
45292 assert( pChanged );
45293 rc = walIndexPage(pWal, 0, &page0);
45294 if( rc!=SQLITE_OK ){
45295 return rc;
45297 assert( page0 || pWal->writeLock==0 );
45299 /* If the first page of the wal-index has been mapped, try to read the
45300 ** wal-index header immediately, without holding any lock. This usually
45301 ** works, but may fail if the wal-index header is corrupt or currently
45302 ** being modified by another thread or process.
45304 badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
45306 /* If the first attempt failed, it might have been due to a race
45307 ** with a writer. So get a WRITE lock and try again.
45309 assert( badHdr==0 || pWal->writeLock==0 );
45310 if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
45311 pWal->writeLock = 1;
45312 if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
45313 badHdr = walIndexTryHdr(pWal, pChanged);
45314 if( badHdr ){
45315 /* If the wal-index header is still malformed even while holding
45316 ** a WRITE lock, it can only mean that the header is corrupted and
45317 ** needs to be reconstructed. So run recovery to do exactly that.
45319 rc = walIndexRecover(pWal);
45320 *pChanged = 1;
45323 pWal->writeLock = 0;
45324 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45327 /* If the header is read successfully, check the version number to make
45328 ** sure the wal-index was not constructed with some future format that
45329 ** this version of SQLite cannot understand.
45331 if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
45332 rc = SQLITE_CANTOPEN_BKPT;
45335 return rc;
45339 ** This is the value that walTryBeginRead returns when it needs to
45340 ** be retried.
45342 #define WAL_RETRY (-1)
45345 ** Attempt to start a read transaction. This might fail due to a race or
45346 ** other transient condition. When that happens, it returns WAL_RETRY to
45347 ** indicate to the caller that it is safe to retry immediately.
45349 ** On success return SQLITE_OK. On a permanent failure (such an
45350 ** I/O error or an SQLITE_BUSY because another process is running
45351 ** recovery) return a positive error code.
45353 ** The useWal parameter is true to force the use of the WAL and disable
45354 ** the case where the WAL is bypassed because it has been completely
45355 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
45356 ** to make a copy of the wal-index header into pWal->hdr. If the
45357 ** wal-index header has changed, *pChanged is set to 1 (as an indication
45358 ** to the caller that the local paget cache is obsolete and needs to be
45359 ** flushed.) When useWal==1, the wal-index header is assumed to already
45360 ** be loaded and the pChanged parameter is unused.
45362 ** The caller must set the cnt parameter to the number of prior calls to
45363 ** this routine during the current read attempt that returned WAL_RETRY.
45364 ** This routine will start taking more aggressive measures to clear the
45365 ** race conditions after multiple WAL_RETRY returns, and after an excessive
45366 ** number of errors will ultimately return SQLITE_PROTOCOL. The
45367 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
45368 ** and is not honoring the locking protocol. There is a vanishingly small
45369 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
45370 ** bad luck when there is lots of contention for the wal-index, but that
45371 ** possibility is so small that it can be safely neglected, we believe.
45373 ** On success, this routine obtains a read lock on
45374 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
45375 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
45376 ** that means the Wal does not hold any read lock. The reader must not
45377 ** access any database page that is modified by a WAL frame up to and
45378 ** including frame number aReadMark[pWal->readLock]. The reader will
45379 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
45380 ** Or if pWal->readLock==0, then the reader will ignore the WAL
45381 ** completely and get all content directly from the database file.
45382 ** If the useWal parameter is 1 then the WAL will never be ignored and
45383 ** this routine will always set pWal->readLock>0 on success.
45384 ** When the read transaction is completed, the caller must release the
45385 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
45387 ** This routine uses the nBackfill and aReadMark[] fields of the header
45388 ** to select a particular WAL_READ_LOCK() that strives to let the
45389 ** checkpoint process do as much work as possible. This routine might
45390 ** update values of the aReadMark[] array in the header, but if it does
45391 ** so it takes care to hold an exclusive lock on the corresponding
45392 ** WAL_READ_LOCK() while changing values.
45394 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
45395 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
45396 u32 mxReadMark; /* Largest aReadMark[] value */
45397 int mxI; /* Index of largest aReadMark[] value */
45398 int i; /* Loop counter */
45399 int rc = SQLITE_OK; /* Return code */
45401 assert( pWal->readLock<0 ); /* Not currently locked */
45403 /* Take steps to avoid spinning forever if there is a protocol error.
45405 ** Circumstances that cause a RETRY should only last for the briefest
45406 ** instances of time. No I/O or other system calls are done while the
45407 ** locks are held, so the locks should not be held for very long. But
45408 ** if we are unlucky, another process that is holding a lock might get
45409 ** paged out or take a page-fault that is time-consuming to resolve,
45410 ** during the few nanoseconds that it is holding the lock. In that case,
45411 ** it might take longer than normal for the lock to free.
45413 ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
45414 ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
45415 ** is more of a scheduler yield than an actual delay. But on the 10th
45416 ** an subsequent retries, the delays start becoming longer and longer,
45417 ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
45418 ** The total delay time before giving up is less than 1 second.
45420 if( cnt>5 ){
45421 int nDelay = 1; /* Pause time in microseconds */
45422 if( cnt>100 ){
45423 VVA_ONLY( pWal->lockError = 1; )
45424 return SQLITE_PROTOCOL;
45426 if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
45427 sqlite3OsSleep(pWal->pVfs, nDelay);
45430 if( !useWal ){
45431 rc = walIndexReadHdr(pWal, pChanged);
45432 if( rc==SQLITE_BUSY ){
45433 /* If there is not a recovery running in another thread or process
45434 ** then convert BUSY errors to WAL_RETRY. If recovery is known to
45435 ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
45436 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
45437 ** would be technically correct. But the race is benign since with
45438 ** WAL_RETRY this routine will be called again and will probably be
45439 ** right on the second iteration.
45441 if( pWal->apWiData[0]==0 ){
45442 /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
45443 ** We assume this is a transient condition, so return WAL_RETRY. The
45444 ** xShmMap() implementation used by the default unix and win32 VFS
45445 ** modules may return SQLITE_BUSY due to a race condition in the
45446 ** code that determines whether or not the shared-memory region
45447 ** must be zeroed before the requested page is returned.
45449 rc = WAL_RETRY;
45450 }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
45451 walUnlockShared(pWal, WAL_RECOVER_LOCK);
45452 rc = WAL_RETRY;
45453 }else if( rc==SQLITE_BUSY ){
45454 rc = SQLITE_BUSY_RECOVERY;
45457 if( rc!=SQLITE_OK ){
45458 return rc;
45462 pInfo = walCkptInfo(pWal);
45463 if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
45464 /* The WAL has been completely backfilled (or it is empty).
45465 ** and can be safely ignored.
45467 rc = walLockShared(pWal, WAL_READ_LOCK(0));
45468 walShmBarrier(pWal);
45469 if( rc==SQLITE_OK ){
45470 if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
45471 /* It is not safe to allow the reader to continue here if frames
45472 ** may have been appended to the log before READ_LOCK(0) was obtained.
45473 ** When holding READ_LOCK(0), the reader ignores the entire log file,
45474 ** which implies that the database file contains a trustworthy
45475 ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
45476 ** happening, this is usually correct.
45478 ** However, if frames have been appended to the log (or if the log
45479 ** is wrapped and written for that matter) before the READ_LOCK(0)
45480 ** is obtained, that is not necessarily true. A checkpointer may
45481 ** have started to backfill the appended frames but crashed before
45482 ** it finished. Leaving a corrupt image in the database file.
45484 walUnlockShared(pWal, WAL_READ_LOCK(0));
45485 return WAL_RETRY;
45487 pWal->readLock = 0;
45488 return SQLITE_OK;
45489 }else if( rc!=SQLITE_BUSY ){
45490 return rc;
45494 /* If we get this far, it means that the reader will want to use
45495 ** the WAL to get at content from recent commits. The job now is
45496 ** to select one of the aReadMark[] entries that is closest to
45497 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
45499 mxReadMark = 0;
45500 mxI = 0;
45501 for(i=1; i<WAL_NREADER; i++){
45502 u32 thisMark = pInfo->aReadMark[i];
45503 if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
45504 assert( thisMark!=READMARK_NOT_USED );
45505 mxReadMark = thisMark;
45506 mxI = i;
45509 /* There was once an "if" here. The extra "{" is to preserve indentation. */
45511 if( mxReadMark < pWal->hdr.mxFrame || mxI==0 ){
45512 for(i=1; i<WAL_NREADER; i++){
45513 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
45514 if( rc==SQLITE_OK ){
45515 mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
45516 mxI = i;
45517 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45518 break;
45519 }else if( rc!=SQLITE_BUSY ){
45520 return rc;
45524 if( mxI==0 ){
45525 assert( rc==SQLITE_BUSY );
45526 return WAL_RETRY;
45529 rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
45530 if( rc ){
45531 return rc==SQLITE_BUSY ? WAL_RETRY : rc;
45533 /* Now that the read-lock has been obtained, check that neither the
45534 ** value in the aReadMark[] array or the contents of the wal-index
45535 ** header have changed.
45537 ** It is necessary to check that the wal-index header did not change
45538 ** between the time it was read and when the shared-lock was obtained
45539 ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
45540 ** that the log file may have been wrapped by a writer, or that frames
45541 ** that occur later in the log than pWal->hdr.mxFrame may have been
45542 ** copied into the database by a checkpointer. If either of these things
45543 ** happened, then reading the database with the current value of
45544 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
45545 ** instead.
45547 ** This does not guarantee that the copy of the wal-index header is up to
45548 ** date before proceeding. That would not be possible without somehow
45549 ** blocking writers. It only guarantees that a dangerous checkpoint or
45550 ** log-wrap (either of which would require an exclusive lock on
45551 ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
45553 walShmBarrier(pWal);
45554 if( pInfo->aReadMark[mxI]!=mxReadMark
45555 || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
45557 walUnlockShared(pWal, WAL_READ_LOCK(mxI));
45558 return WAL_RETRY;
45559 }else{
45560 assert( mxReadMark<=pWal->hdr.mxFrame );
45561 pWal->readLock = (i16)mxI;
45564 return rc;
45568 ** Begin a read transaction on the database.
45570 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
45571 ** it takes a snapshot of the state of the WAL and wal-index for the current
45572 ** instant in time. The current thread will continue to use this snapshot.
45573 ** Other threads might append new content to the WAL and wal-index but
45574 ** that extra content is ignored by the current thread.
45576 ** If the database contents have changes since the previous read
45577 ** transaction, then *pChanged is set to 1 before returning. The
45578 ** Pager layer will use this to know that is cache is stale and
45579 ** needs to be flushed.
45581 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
45582 int rc; /* Return code */
45583 int cnt = 0; /* Number of TryBeginRead attempts */
45586 rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
45587 }while( rc==WAL_RETRY );
45588 testcase( (rc&0xff)==SQLITE_BUSY );
45589 testcase( (rc&0xff)==SQLITE_IOERR );
45590 testcase( rc==SQLITE_PROTOCOL );
45591 testcase( rc==SQLITE_OK );
45592 return rc;
45596 ** Finish with a read transaction. All this does is release the
45597 ** read-lock.
45599 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
45600 sqlite3WalEndWriteTransaction(pWal);
45601 if( pWal->readLock>=0 ){
45602 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
45603 pWal->readLock = -1;
45608 ** Read a page from the WAL, if it is present in the WAL and if the
45609 ** current read transaction is configured to use the WAL.
45611 ** The *pInWal is set to 1 if the requested page is in the WAL and
45612 ** has been loaded. Or *pInWal is set to 0 if the page was not in
45613 ** the WAL and needs to be read out of the database.
45615 SQLITE_PRIVATE int sqlite3WalRead(
45616 Wal *pWal, /* WAL handle */
45617 Pgno pgno, /* Database page number to read data for */
45618 int *pInWal, /* OUT: True if data is read from WAL */
45619 int nOut, /* Size of buffer pOut in bytes */
45620 u8 *pOut /* Buffer to write page data to */
45622 u32 iRead = 0; /* If !=0, WAL frame to return data from */
45623 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
45624 int iHash; /* Used to loop through N hash tables */
45626 /* This routine is only be called from within a read transaction. */
45627 assert( pWal->readLock>=0 || pWal->lockError );
45629 /* If the "last page" field of the wal-index header snapshot is 0, then
45630 ** no data will be read from the wal under any circumstances. Return early
45631 ** in this case as an optimization. Likewise, if pWal->readLock==0,
45632 ** then the WAL is ignored by the reader so return early, as if the
45633 ** WAL were empty.
45635 if( iLast==0 || pWal->readLock==0 ){
45636 *pInWal = 0;
45637 return SQLITE_OK;
45640 /* Search the hash table or tables for an entry matching page number
45641 ** pgno. Each iteration of the following for() loop searches one
45642 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
45644 ** This code might run concurrently to the code in walIndexAppend()
45645 ** that adds entries to the wal-index (and possibly to this hash
45646 ** table). This means the value just read from the hash
45647 ** slot (aHash[iKey]) may have been added before or after the
45648 ** current read transaction was opened. Values added after the
45649 ** read transaction was opened may have been written incorrectly -
45650 ** i.e. these slots may contain garbage data. However, we assume
45651 ** that any slots written before the current read transaction was
45652 ** opened remain unmodified.
45654 ** For the reasons above, the if(...) condition featured in the inner
45655 ** loop of the following block is more stringent that would be required
45656 ** if we had exclusive access to the hash-table:
45658 ** (aPgno[iFrame]==pgno):
45659 ** This condition filters out normal hash-table collisions.
45661 ** (iFrame<=iLast):
45662 ** This condition filters out entries that were added to the hash
45663 ** table after the current read-transaction had started.
45665 for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
45666 volatile ht_slot *aHash; /* Pointer to hash table */
45667 volatile u32 *aPgno; /* Pointer to array of page numbers */
45668 u32 iZero; /* Frame number corresponding to aPgno[0] */
45669 int iKey; /* Hash slot index */
45670 int nCollide; /* Number of hash collisions remaining */
45671 int rc; /* Error code */
45673 rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
45674 if( rc!=SQLITE_OK ){
45675 return rc;
45677 nCollide = HASHTABLE_NSLOT;
45678 for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
45679 u32 iFrame = aHash[iKey] + iZero;
45680 if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
45681 assert( iFrame>iRead );
45682 iRead = iFrame;
45684 if( (nCollide--)==0 ){
45685 return SQLITE_CORRUPT_BKPT;
45690 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45691 /* If expensive assert() statements are available, do a linear search
45692 ** of the wal-index file content. Make sure the results agree with the
45693 ** result obtained using the hash indexes above. */
45695 u32 iRead2 = 0;
45696 u32 iTest;
45697 for(iTest=iLast; iTest>0; iTest--){
45698 if( walFramePgno(pWal, iTest)==pgno ){
45699 iRead2 = iTest;
45700 break;
45703 assert( iRead==iRead2 );
45705 #endif
45707 /* If iRead is non-zero, then it is the log frame number that contains the
45708 ** required page. Read and return data from the log file.
45710 if( iRead ){
45711 int sz;
45712 i64 iOffset;
45713 sz = pWal->hdr.szPage;
45714 sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45715 testcase( sz<=32768 );
45716 testcase( sz>=65536 );
45717 iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
45718 *pInWal = 1;
45719 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45720 return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
45723 *pInWal = 0;
45724 return SQLITE_OK;
45729 ** Return the size of the database in pages (or zero, if unknown).
45731 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
45732 if( pWal && ALWAYS(pWal->readLock>=0) ){
45733 return pWal->hdr.nPage;
45735 return 0;
45740 ** This function starts a write transaction on the WAL.
45742 ** A read transaction must have already been started by a prior call
45743 ** to sqlite3WalBeginReadTransaction().
45745 ** If another thread or process has written into the database since
45746 ** the read transaction was started, then it is not possible for this
45747 ** thread to write as doing so would cause a fork. So this routine
45748 ** returns SQLITE_BUSY in that case and no write transaction is started.
45750 ** There can only be a single writer active at a time.
45752 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
45753 int rc;
45755 /* Cannot start a write transaction without first holding a read
45756 ** transaction. */
45757 assert( pWal->readLock>=0 );
45759 if( pWal->readOnly ){
45760 return SQLITE_READONLY;
45763 /* Only one writer allowed at a time. Get the write lock. Return
45764 ** SQLITE_BUSY if unable.
45766 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
45767 if( rc ){
45768 return rc;
45770 pWal->writeLock = 1;
45772 /* If another connection has written to the database file since the
45773 ** time the read transaction on this connection was started, then
45774 ** the write is disallowed.
45776 if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
45777 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45778 pWal->writeLock = 0;
45779 rc = SQLITE_BUSY;
45782 return rc;
45786 ** End a write transaction. The commit has already been done. This
45787 ** routine merely releases the lock.
45789 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
45790 if( pWal->writeLock ){
45791 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45792 pWal->writeLock = 0;
45794 return SQLITE_OK;
45798 ** If any data has been written (but not committed) to the log file, this
45799 ** function moves the write-pointer back to the start of the transaction.
45801 ** Additionally, the callback function is invoked for each frame written
45802 ** to the WAL since the start of the transaction. If the callback returns
45803 ** other than SQLITE_OK, it is not invoked again and the error code is
45804 ** returned to the caller.
45806 ** Otherwise, if the callback function does not return an error, this
45807 ** function returns SQLITE_OK.
45809 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
45810 int rc = SQLITE_OK;
45811 if( ALWAYS(pWal->writeLock) ){
45812 Pgno iMax = pWal->hdr.mxFrame;
45813 Pgno iFrame;
45815 /* Restore the clients cache of the wal-index header to the state it
45816 ** was in before the client began writing to the database.
45818 memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
45820 for(iFrame=pWal->hdr.mxFrame+1;
45821 ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
45822 iFrame++
45824 /* This call cannot fail. Unless the page for which the page number
45825 ** is passed as the second argument is (a) in the cache and
45826 ** (b) has an outstanding reference, then xUndo is either a no-op
45827 ** (if (a) is false) or simply expels the page from the cache (if (b)
45828 ** is false).
45830 ** If the upper layer is doing a rollback, it is guaranteed that there
45831 ** are no outstanding references to any page other than page 1. And
45832 ** page 1 is never written to the log until the transaction is
45833 ** committed. As a result, the call to xUndo may not fail.
45835 assert( walFramePgno(pWal, iFrame)!=1 );
45836 rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
45838 walCleanupHash(pWal);
45840 assert( rc==SQLITE_OK );
45841 return rc;
45845 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
45846 ** values. This function populates the array with values required to
45847 ** "rollback" the write position of the WAL handle back to the current
45848 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
45850 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
45851 assert( pWal->writeLock );
45852 aWalData[0] = pWal->hdr.mxFrame;
45853 aWalData[1] = pWal->hdr.aFrameCksum[0];
45854 aWalData[2] = pWal->hdr.aFrameCksum[1];
45855 aWalData[3] = pWal->nCkpt;
45859 ** Move the write position of the WAL back to the point identified by
45860 ** the values in the aWalData[] array. aWalData must point to an array
45861 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
45862 ** by a call to WalSavepoint().
45864 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
45865 int rc = SQLITE_OK;
45867 assert( pWal->writeLock );
45868 assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
45870 if( aWalData[3]!=pWal->nCkpt ){
45871 /* This savepoint was opened immediately after the write-transaction
45872 ** was started. Right after that, the writer decided to wrap around
45873 ** to the start of the log. Update the savepoint values to match.
45875 aWalData[0] = 0;
45876 aWalData[3] = pWal->nCkpt;
45879 if( aWalData[0]<pWal->hdr.mxFrame ){
45880 pWal->hdr.mxFrame = aWalData[0];
45881 pWal->hdr.aFrameCksum[0] = aWalData[1];
45882 pWal->hdr.aFrameCksum[1] = aWalData[2];
45883 walCleanupHash(pWal);
45886 return rc;
45890 ** This function is called just before writing a set of frames to the log
45891 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
45892 ** to the current log file, it is possible to overwrite the start of the
45893 ** existing log file with the new frames (i.e. "reset" the log). If so,
45894 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
45895 ** unchanged.
45897 ** SQLITE_OK is returned if no error is encountered (regardless of whether
45898 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
45899 ** if an error occurs.
45901 static int walRestartLog(Wal *pWal){
45902 int rc = SQLITE_OK;
45903 int cnt;
45905 if( pWal->readLock==0 ){
45906 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
45907 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
45908 if( pInfo->nBackfill>0 ){
45909 u32 salt1;
45910 sqlite3_randomness(4, &salt1);
45911 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45912 if( rc==SQLITE_OK ){
45913 /* If all readers are using WAL_READ_LOCK(0) (in other words if no
45914 ** readers are currently using the WAL), then the transactions
45915 ** frames will overwrite the start of the existing log. Update the
45916 ** wal-index header to reflect this.
45918 ** In theory it would be Ok to update the cache of the header only
45919 ** at this point. But updating the actual wal-index header is also
45920 ** safe and means there is no special case for sqlite3WalUndo()
45921 ** to handle if this transaction is rolled back.
45923 int i; /* Loop counter */
45924 u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
45925 pWal->nCkpt++;
45926 pWal->hdr.mxFrame = 0;
45927 sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
45928 aSalt[1] = salt1;
45929 walIndexWriteHdr(pWal);
45930 pInfo->nBackfill = 0;
45931 for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
45932 assert( pInfo->aReadMark[0]==0 );
45933 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45934 }else if( rc!=SQLITE_BUSY ){
45935 return rc;
45938 walUnlockShared(pWal, WAL_READ_LOCK(0));
45939 pWal->readLock = -1;
45940 cnt = 0;
45942 int notUsed;
45943 rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
45944 }while( rc==WAL_RETRY );
45945 assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
45946 testcase( (rc&0xff)==SQLITE_IOERR );
45947 testcase( rc==SQLITE_PROTOCOL );
45948 testcase( rc==SQLITE_OK );
45950 return rc;
45954 ** Write a set of frames to the log. The caller must hold the write-lock
45955 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
45957 SQLITE_PRIVATE int sqlite3WalFrames(
45958 Wal *pWal, /* Wal handle to write to */
45959 int szPage, /* Database page-size in bytes */
45960 PgHdr *pList, /* List of dirty pages to write */
45961 Pgno nTruncate, /* Database size after this commit */
45962 int isCommit, /* True if this is a commit */
45963 int sync_flags /* Flags to pass to OsSync() (or 0) */
45965 int rc; /* Used to catch return codes */
45966 u32 iFrame; /* Next frame address */
45967 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
45968 PgHdr *p; /* Iterator to run through pList with. */
45969 PgHdr *pLast = 0; /* Last frame in list */
45970 int nLast = 0; /* Number of extra copies of last page */
45972 assert( pList );
45973 assert( pWal->writeLock );
45975 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45976 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
45977 WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
45978 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
45980 #endif
45982 /* See if it is possible to write these frames into the start of the
45983 ** log file, instead of appending to it at pWal->hdr.mxFrame.
45985 if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
45986 return rc;
45989 /* If this is the first frame written into the log, write the WAL
45990 ** header to the start of the WAL file. See comments at the top of
45991 ** this source file for a description of the WAL header format.
45993 iFrame = pWal->hdr.mxFrame;
45994 if( iFrame==0 ){
45995 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
45996 u32 aCksum[2]; /* Checksum for wal-header */
45998 sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
45999 sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
46000 sqlite3Put4byte(&aWalHdr[8], szPage);
46001 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
46002 sqlite3_randomness(8, pWal->hdr.aSalt);
46003 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
46004 walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
46005 sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
46006 sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
46008 pWal->szPage = szPage;
46009 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
46010 pWal->hdr.aFrameCksum[0] = aCksum[0];
46011 pWal->hdr.aFrameCksum[1] = aCksum[1];
46013 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
46014 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
46015 if( rc!=SQLITE_OK ){
46016 return rc;
46019 assert( (int)pWal->szPage==szPage );
46021 /* Write the log file. */
46022 for(p=pList; p; p=p->pDirty){
46023 u32 nDbsize; /* Db-size field for frame header */
46024 i64 iOffset; /* Write offset in log file */
46025 void *pData;
46027 iOffset = walFrameOffset(++iFrame, szPage);
46028 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46030 /* Populate and write the frame header */
46031 nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
46032 #if defined(SQLITE_HAS_CODEC)
46033 if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
46034 #else
46035 pData = p->pData;
46036 #endif
46037 walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
46038 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
46039 if( rc!=SQLITE_OK ){
46040 return rc;
46043 /* Write the page data */
46044 rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
46045 if( rc!=SQLITE_OK ){
46046 return rc;
46048 pLast = p;
46051 /* Sync the log file if the 'isSync' flag was specified. */
46052 if( sync_flags ){
46053 i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
46054 i64 iOffset = walFrameOffset(iFrame+1, szPage);
46056 assert( isCommit );
46057 assert( iSegment>0 );
46059 iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
46060 while( iOffset<iSegment ){
46061 void *pData;
46062 #if defined(SQLITE_HAS_CODEC)
46063 if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
46064 #else
46065 pData = pLast->pData;
46066 #endif
46067 walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
46068 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46069 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
46070 if( rc!=SQLITE_OK ){
46071 return rc;
46073 iOffset += WAL_FRAME_HDRSIZE;
46074 rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset);
46075 if( rc!=SQLITE_OK ){
46076 return rc;
46078 nLast++;
46079 iOffset += szPage;
46082 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
46085 /* Append data to the wal-index. It is not necessary to lock the
46086 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
46087 ** guarantees that there are no other writers, and no data that may
46088 ** be in use by existing readers is being overwritten.
46090 iFrame = pWal->hdr.mxFrame;
46091 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
46092 iFrame++;
46093 rc = walIndexAppend(pWal, iFrame, p->pgno);
46095 while( nLast>0 && rc==SQLITE_OK ){
46096 iFrame++;
46097 nLast--;
46098 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
46101 if( rc==SQLITE_OK ){
46102 /* Update the private copy of the header. */
46103 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
46104 testcase( szPage<=32768 );
46105 testcase( szPage>=65536 );
46106 pWal->hdr.mxFrame = iFrame;
46107 if( isCommit ){
46108 pWal->hdr.iChange++;
46109 pWal->hdr.nPage = nTruncate;
46111 /* If this is a commit, update the wal-index header too. */
46112 if( isCommit ){
46113 walIndexWriteHdr(pWal);
46114 pWal->iCallback = iFrame;
46118 WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
46119 return rc;
46123 ** This routine is called to implement sqlite3_wal_checkpoint() and
46124 ** related interfaces.
46126 ** Obtain a CHECKPOINT lock and then backfill as much information as
46127 ** we can from WAL into the database.
46129 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
46130 ** callback. In this case this function runs a blocking checkpoint.
46132 SQLITE_PRIVATE int sqlite3WalCheckpoint(
46133 Wal *pWal, /* Wal connection */
46134 int eMode, /* PASSIVE, FULL or RESTART */
46135 int (*xBusy)(void*), /* Function to call when busy */
46136 void *pBusyArg, /* Context argument for xBusyHandler */
46137 int sync_flags, /* Flags to sync db file with (or 0) */
46138 int nBuf, /* Size of temporary buffer */
46139 u8 *zBuf, /* Temporary buffer to use */
46140 int *pnLog, /* OUT: Number of frames in WAL */
46141 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
46143 int rc; /* Return code */
46144 int isChanged = 0; /* True if a new wal-index header is loaded */
46145 int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
46147 assert( pWal->ckptLock==0 );
46148 assert( pWal->writeLock==0 );
46150 WALTRACE(("WAL%p: checkpoint begins\n", pWal));
46151 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
46152 if( rc ){
46153 /* Usually this is SQLITE_BUSY meaning that another thread or process
46154 ** is already running a checkpoint, or maybe a recovery. But it might
46155 ** also be SQLITE_IOERR. */
46156 return rc;
46158 pWal->ckptLock = 1;
46160 /* If this is a blocking-checkpoint, then obtain the write-lock as well
46161 ** to prevent any writers from running while the checkpoint is underway.
46162 ** This has to be done before the call to walIndexReadHdr() below.
46164 ** If the writer lock cannot be obtained, then a passive checkpoint is
46165 ** run instead. Since the checkpointer is not holding the writer lock,
46166 ** there is no point in blocking waiting for any readers. Assuming no
46167 ** other error occurs, this function will return SQLITE_BUSY to the caller.
46169 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
46170 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
46171 if( rc==SQLITE_OK ){
46172 pWal->writeLock = 1;
46173 }else if( rc==SQLITE_BUSY ){
46174 eMode2 = SQLITE_CHECKPOINT_PASSIVE;
46175 rc = SQLITE_OK;
46179 /* Read the wal-index header. */
46180 if( rc==SQLITE_OK ){
46181 rc = walIndexReadHdr(pWal, &isChanged);
46184 /* Copy data from the log to the database file. */
46185 if( rc==SQLITE_OK ){
46186 if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
46187 rc = SQLITE_CORRUPT_BKPT;
46188 }else{
46189 rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
46192 /* If no error occurred, set the output variables. */
46193 if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
46194 if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
46195 if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
46199 if( isChanged ){
46200 /* If a new wal-index header was loaded before the checkpoint was
46201 ** performed, then the pager-cache associated with pWal is now
46202 ** out of date. So zero the cached wal-index header to ensure that
46203 ** next time the pager opens a snapshot on this database it knows that
46204 ** the cache needs to be reset.
46206 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
46209 /* Release the locks. */
46210 sqlite3WalEndWriteTransaction(pWal);
46211 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
46212 pWal->ckptLock = 0;
46213 WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
46214 return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
46217 /* Return the value to pass to a sqlite3_wal_hook callback, the
46218 ** number of frames in the WAL at the point of the last commit since
46219 ** sqlite3WalCallback() was called. If no commits have occurred since
46220 ** the last call, then return 0.
46222 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
46223 u32 ret = 0;
46224 if( pWal ){
46225 ret = pWal->iCallback;
46226 pWal->iCallback = 0;
46228 return (int)ret;
46232 ** This function is called to change the WAL subsystem into or out
46233 ** of locking_mode=EXCLUSIVE.
46235 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
46236 ** into locking_mode=NORMAL. This means that we must acquire a lock
46237 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
46238 ** or if the acquisition of the lock fails, then return 0. If the
46239 ** transition out of exclusive-mode is successful, return 1. This
46240 ** operation must occur while the pager is still holding the exclusive
46241 ** lock on the main database file.
46243 ** If op is one, then change from locking_mode=NORMAL into
46244 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
46245 ** be released. Return 1 if the transition is made and 0 if the
46246 ** WAL is already in exclusive-locking mode - meaning that this
46247 ** routine is a no-op. The pager must already hold the exclusive lock
46248 ** on the main database file before invoking this operation.
46250 ** If op is negative, then do a dry-run of the op==1 case but do
46251 ** not actually change anything. The pager uses this to see if it
46252 ** should acquire the database exclusive lock prior to invoking
46253 ** the op==1 case.
46255 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
46256 int rc;
46257 assert( pWal->writeLock==0 );
46258 assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
46260 /* pWal->readLock is usually set, but might be -1 if there was a
46261 ** prior error while attempting to acquire are read-lock. This cannot
46262 ** happen if the connection is actually in exclusive mode (as no xShmLock
46263 ** locks are taken in this case). Nor should the pager attempt to
46264 ** upgrade to exclusive-mode following such an error.
46266 assert( pWal->readLock>=0 || pWal->lockError );
46267 assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
46269 if( op==0 ){
46270 if( pWal->exclusiveMode ){
46271 pWal->exclusiveMode = 0;
46272 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
46273 pWal->exclusiveMode = 1;
46275 rc = pWal->exclusiveMode==0;
46276 }else{
46277 /* Already in locking_mode=NORMAL */
46278 rc = 0;
46280 }else if( op>0 ){
46281 assert( pWal->exclusiveMode==0 );
46282 assert( pWal->readLock>=0 );
46283 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46284 pWal->exclusiveMode = 1;
46285 rc = 1;
46286 }else{
46287 rc = pWal->exclusiveMode==0;
46289 return rc;
46293 ** Return true if the argument is non-NULL and the WAL module is using
46294 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46295 ** WAL module is using shared-memory, return false.
46297 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
46298 return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
46301 #endif /* #ifndef SQLITE_OMIT_WAL */
46303 /************** End of wal.c *************************************************/
46304 /************** Begin file btmutex.c *****************************************/
46306 ** 2007 August 27
46308 ** The author disclaims copyright to this source code. In place of
46309 ** a legal notice, here is a blessing:
46311 ** May you do good and not evil.
46312 ** May you find forgiveness for yourself and forgive others.
46313 ** May you share freely, never taking more than you give.
46315 *************************************************************************
46317 ** This file contains code used to implement mutexes on Btree objects.
46318 ** This code really belongs in btree.c. But btree.c is getting too
46319 ** big and we want to break it down some. This packaged seemed like
46320 ** a good breakout.
46322 /************** Include btreeInt.h in the middle of btmutex.c ****************/
46323 /************** Begin file btreeInt.h ****************************************/
46325 ** 2004 April 6
46327 ** The author disclaims copyright to this source code. In place of
46328 ** a legal notice, here is a blessing:
46330 ** May you do good and not evil.
46331 ** May you find forgiveness for yourself and forgive others.
46332 ** May you share freely, never taking more than you give.
46334 *************************************************************************
46335 ** This file implements a external (disk-based) database using BTrees.
46336 ** For a detailed discussion of BTrees, refer to
46338 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
46339 ** "Sorting And Searching", pages 473-480. Addison-Wesley
46340 ** Publishing Company, Reading, Massachusetts.
46342 ** The basic idea is that each page of the file contains N database
46343 ** entries and N+1 pointers to subpages.
46345 ** ----------------------------------------------------------------
46346 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
46347 ** ----------------------------------------------------------------
46349 ** All of the keys on the page that Ptr(0) points to have values less
46350 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
46351 ** values greater than Key(0) and less than Key(1). All of the keys
46352 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
46353 ** so forth.
46355 ** Finding a particular key requires reading O(log(M)) pages from the
46356 ** disk where M is the number of entries in the tree.
46358 ** In this implementation, a single file can hold one or more separate
46359 ** BTrees. Each BTree is identified by the index of its root page. The
46360 ** key and data for any entry are combined to form the "payload". A
46361 ** fixed amount of payload can be carried directly on the database
46362 ** page. If the payload is larger than the preset amount then surplus
46363 ** bytes are stored on overflow pages. The payload for an entry
46364 ** and the preceding pointer are combined to form a "Cell". Each
46365 ** page has a small header which contains the Ptr(N) pointer and other
46366 ** information such as the size of key and data.
46368 ** FORMAT DETAILS
46370 ** The file is divided into pages. The first page is called page 1,
46371 ** the second is page 2, and so forth. A page number of zero indicates
46372 ** "no such page". The page size can be any power of 2 between 512 and 65536.
46373 ** Each page can be either a btree page, a freelist page, an overflow
46374 ** page, or a pointer-map page.
46376 ** The first page is always a btree page. The first 100 bytes of the first
46377 ** page contain a special header (the "file header") that describes the file.
46378 ** The format of the file header is as follows:
46380 ** OFFSET SIZE DESCRIPTION
46381 ** 0 16 Header string: "SQLite format 3\000"
46382 ** 16 2 Page size in bytes.
46383 ** 18 1 File format write version
46384 ** 19 1 File format read version
46385 ** 20 1 Bytes of unused space at the end of each page
46386 ** 21 1 Max embedded payload fraction
46387 ** 22 1 Min embedded payload fraction
46388 ** 23 1 Min leaf payload fraction
46389 ** 24 4 File change counter
46390 ** 28 4 Reserved for future use
46391 ** 32 4 First freelist page
46392 ** 36 4 Number of freelist pages in the file
46393 ** 40 60 15 4-byte meta values passed to higher layers
46395 ** 40 4 Schema cookie
46396 ** 44 4 File format of schema layer
46397 ** 48 4 Size of page cache
46398 ** 52 4 Largest root-page (auto/incr_vacuum)
46399 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
46400 ** 60 4 User version
46401 ** 64 4 Incremental vacuum mode
46402 ** 68 4 unused
46403 ** 72 4 unused
46404 ** 76 4 unused
46406 ** All of the integer values are big-endian (most significant byte first).
46408 ** The file change counter is incremented when the database is changed
46409 ** This counter allows other processes to know when the file has changed
46410 ** and thus when they need to flush their cache.
46412 ** The max embedded payload fraction is the amount of the total usable
46413 ** space in a page that can be consumed by a single cell for standard
46414 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
46415 ** is to limit the maximum cell size so that at least 4 cells will fit
46416 ** on one page. Thus the default max embedded payload fraction is 64.
46418 ** If the payload for a cell is larger than the max payload, then extra
46419 ** payload is spilled to overflow pages. Once an overflow page is allocated,
46420 ** as many bytes as possible are moved into the overflow pages without letting
46421 ** the cell size drop below the min embedded payload fraction.
46423 ** The min leaf payload fraction is like the min embedded payload fraction
46424 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
46425 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
46426 ** not specified in the header.
46428 ** Each btree pages is divided into three sections: The header, the
46429 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
46430 ** file header that occurs before the page header.
46432 ** |----------------|
46433 ** | file header | 100 bytes. Page 1 only.
46434 ** |----------------|
46435 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
46436 ** |----------------|
46437 ** | cell pointer | | 2 bytes per cell. Sorted order.
46438 ** | array | | Grows downward
46439 ** | | v
46440 ** |----------------|
46441 ** | unallocated |
46442 ** | space |
46443 ** |----------------| ^ Grows upwards
46444 ** | cell content | | Arbitrary order interspersed with freeblocks.
46445 ** | area | | and free space fragments.
46446 ** |----------------|
46448 ** The page headers looks like this:
46450 ** OFFSET SIZE DESCRIPTION
46451 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
46452 ** 1 2 byte offset to the first freeblock
46453 ** 3 2 number of cells on this page
46454 ** 5 2 first byte of the cell content area
46455 ** 7 1 number of fragmented free bytes
46456 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
46458 ** The flags define the format of this btree page. The leaf flag means that
46459 ** this page has no children. The zerodata flag means that this page carries
46460 ** only keys and no data. The intkey flag means that the key is a integer
46461 ** which is stored in the key size entry of the cell header rather than in
46462 ** the payload area.
46464 ** The cell pointer array begins on the first byte after the page header.
46465 ** The cell pointer array contains zero or more 2-byte numbers which are
46466 ** offsets from the beginning of the page to the cell content in the cell
46467 ** content area. The cell pointers occur in sorted order. The system strives
46468 ** to keep free space after the last cell pointer so that new cells can
46469 ** be easily added without having to defragment the page.
46471 ** Cell content is stored at the very end of the page and grows toward the
46472 ** beginning of the page.
46474 ** Unused space within the cell content area is collected into a linked list of
46475 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
46476 ** to the first freeblock is given in the header. Freeblocks occur in
46477 ** increasing order. Because a freeblock must be at least 4 bytes in size,
46478 ** any group of 3 or fewer unused bytes in the cell content area cannot
46479 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
46480 ** a fragment. The total number of bytes in all fragments is recorded.
46481 ** in the page header at offset 7.
46483 ** SIZE DESCRIPTION
46484 ** 2 Byte offset of the next freeblock
46485 ** 2 Bytes in this freeblock
46487 ** Cells are of variable length. Cells are stored in the cell content area at
46488 ** the end of the page. Pointers to the cells are in the cell pointer array
46489 ** that immediately follows the page header. Cells is not necessarily
46490 ** contiguous or in order, but cell pointers are contiguous and in order.
46492 ** Cell content makes use of variable length integers. A variable
46493 ** length integer is 1 to 9 bytes where the lower 7 bits of each
46494 ** byte are used. The integer consists of all bytes that have bit 8 set and
46495 ** the first byte with bit 8 clear. The most significant byte of the integer
46496 ** appears first. A variable-length integer may not be more than 9 bytes long.
46497 ** As a special case, all 8 bytes of the 9th byte are used as data. This
46498 ** allows a 64-bit integer to be encoded in 9 bytes.
46500 ** 0x00 becomes 0x00000000
46501 ** 0x7f becomes 0x0000007f
46502 ** 0x81 0x00 becomes 0x00000080
46503 ** 0x82 0x00 becomes 0x00000100
46504 ** 0x80 0x7f becomes 0x0000007f
46505 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
46506 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
46508 ** Variable length integers are used for rowids and to hold the number of
46509 ** bytes of key and data in a btree cell.
46511 ** The content of a cell looks like this:
46513 ** SIZE DESCRIPTION
46514 ** 4 Page number of the left child. Omitted if leaf flag is set.
46515 ** var Number of bytes of data. Omitted if the zerodata flag is set.
46516 ** var Number of bytes of key. Or the key itself if intkey flag is set.
46517 ** * Payload
46518 ** 4 First page of the overflow chain. Omitted if no overflow
46520 ** Overflow pages form a linked list. Each page except the last is completely
46521 ** filled with data (pagesize - 4 bytes). The last page can have as little
46522 ** as 1 byte of data.
46524 ** SIZE DESCRIPTION
46525 ** 4 Page number of next overflow page
46526 ** * Data
46528 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
46529 ** file header points to the first in a linked list of trunk page. Each trunk
46530 ** page points to multiple leaf pages. The content of a leaf page is
46531 ** unspecified. A trunk page looks like this:
46533 ** SIZE DESCRIPTION
46534 ** 4 Page number of next trunk page
46535 ** 4 Number of leaf pointers on this page
46536 ** * zero or more pages numbers of leaves
46540 /* The following value is the maximum cell size assuming a maximum page
46541 ** size give above.
46543 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
46545 /* The maximum number of cells on a single page of the database. This
46546 ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
46547 ** plus 2 bytes for the index to the cell in the page header). Such
46548 ** small cells will be rare, but they are possible.
46550 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
46552 /* Forward declarations */
46553 typedef struct MemPage MemPage;
46554 typedef struct BtLock BtLock;
46557 ** This is a magic string that appears at the beginning of every
46558 ** SQLite database in order to identify the file as a real database.
46560 ** You can change this value at compile-time by specifying a
46561 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
46562 ** header must be exactly 16 bytes including the zero-terminator so
46563 ** the string itself should be 15 characters long. If you change
46564 ** the header, then your custom library will not be able to read
46565 ** databases generated by the standard tools and the standard tools
46566 ** will not be able to read databases created by your custom library.
46568 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
46569 # define SQLITE_FILE_HEADER "SQLite format 3"
46570 #endif
46573 ** Page type flags. An ORed combination of these flags appear as the
46574 ** first byte of on-disk image of every BTree page.
46576 #define PTF_INTKEY 0x01
46577 #define PTF_ZERODATA 0x02
46578 #define PTF_LEAFDATA 0x04
46579 #define PTF_LEAF 0x08
46582 ** As each page of the file is loaded into memory, an instance of the following
46583 ** structure is appended and initialized to zero. This structure stores
46584 ** information about the page that is decoded from the raw file page.
46586 ** The pParent field points back to the parent page. This allows us to
46587 ** walk up the BTree from any leaf to the root. Care must be taken to
46588 ** unref() the parent page pointer when this page is no longer referenced.
46589 ** The pageDestructor() routine handles that chore.
46591 ** Access to all fields of this structure is controlled by the mutex
46592 ** stored in MemPage.pBt->mutex.
46594 struct MemPage {
46595 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
46596 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
46597 u8 intKey; /* True if intkey flag is set */
46598 u8 leaf; /* True if leaf flag is set */
46599 u8 hasData; /* True if this page stores data */
46600 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
46601 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
46602 u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
46603 u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
46604 u16 cellOffset; /* Index in aData of first cell pointer */
46605 u16 nFree; /* Number of free bytes on the page */
46606 u16 nCell; /* Number of cells on this page, local and ovfl */
46607 u16 maskPage; /* Mask for page offset */
46608 struct _OvflCell { /* Cells that will not fit on aData[] */
46609 u8 *pCell; /* Pointers to the body of the overflow cell */
46610 u16 idx; /* Insert this cell before idx-th non-overflow cell */
46611 } aOvfl[5];
46612 BtShared *pBt; /* Pointer to BtShared that this page is part of */
46613 u8 *aData; /* Pointer to disk image of the page data */
46614 DbPage *pDbPage; /* Pager page handle */
46615 Pgno pgno; /* Page number for this page */
46619 ** The in-memory image of a disk page has the auxiliary information appended
46620 ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
46621 ** that extra information.
46623 #define EXTRA_SIZE sizeof(MemPage)
46626 ** A linked list of the following structures is stored at BtShared.pLock.
46627 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
46628 ** is opened on the table with root page BtShared.iTable. Locks are removed
46629 ** from this list when a transaction is committed or rolled back, or when
46630 ** a btree handle is closed.
46632 struct BtLock {
46633 Btree *pBtree; /* Btree handle holding this lock */
46634 Pgno iTable; /* Root page of table */
46635 u8 eLock; /* READ_LOCK or WRITE_LOCK */
46636 BtLock *pNext; /* Next in BtShared.pLock list */
46639 /* Candidate values for BtLock.eLock */
46640 #define READ_LOCK 1
46641 #define WRITE_LOCK 2
46643 /* A Btree handle
46645 ** A database connection contains a pointer to an instance of
46646 ** this object for every database file that it has open. This structure
46647 ** is opaque to the database connection. The database connection cannot
46648 ** see the internals of this structure and only deals with pointers to
46649 ** this structure.
46651 ** For some database files, the same underlying database cache might be
46652 ** shared between multiple connections. In that case, each connection
46653 ** has it own instance of this object. But each instance of this object
46654 ** points to the same BtShared object. The database cache and the
46655 ** schema associated with the database file are all contained within
46656 ** the BtShared object.
46658 ** All fields in this structure are accessed under sqlite3.mutex.
46659 ** The pBt pointer itself may not be changed while there exists cursors
46660 ** in the referenced BtShared that point back to this Btree since those
46661 ** cursors have to go through this Btree to find their BtShared and
46662 ** they often do so without holding sqlite3.mutex.
46664 struct Btree {
46665 sqlite3 *db; /* The database connection holding this btree */
46666 BtShared *pBt; /* Sharable content of this btree */
46667 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
46668 u8 sharable; /* True if we can share pBt with another db */
46669 u8 locked; /* True if db currently has pBt locked */
46670 int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
46671 int nBackup; /* Number of backup operations reading this btree */
46672 Btree *pNext; /* List of other sharable Btrees from the same db */
46673 Btree *pPrev; /* Back pointer of the same list */
46674 #ifndef SQLITE_OMIT_SHARED_CACHE
46675 BtLock lock; /* Object used to lock page 1 */
46676 #endif
46680 ** Btree.inTrans may take one of the following values.
46682 ** If the shared-data extension is enabled, there may be multiple users
46683 ** of the Btree structure. At most one of these may open a write transaction,
46684 ** but any number may have active read transactions.
46686 #define TRANS_NONE 0
46687 #define TRANS_READ 1
46688 #define TRANS_WRITE 2
46691 ** An instance of this object represents a single database file.
46693 ** A single database file can be in use as the same time by two
46694 ** or more database connections. When two or more connections are
46695 ** sharing the same database file, each connection has it own
46696 ** private Btree object for the file and each of those Btrees points
46697 ** to this one BtShared object. BtShared.nRef is the number of
46698 ** connections currently sharing this database file.
46700 ** Fields in this structure are accessed under the BtShared.mutex
46701 ** mutex, except for nRef and pNext which are accessed under the
46702 ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
46703 ** may not be modified once it is initially set as long as nRef>0.
46704 ** The pSchema field may be set once under BtShared.mutex and
46705 ** thereafter is unchanged as long as nRef>0.
46707 ** isPending:
46709 ** If a BtShared client fails to obtain a write-lock on a database
46710 ** table (because there exists one or more read-locks on the table),
46711 ** the shared-cache enters 'pending-lock' state and isPending is
46712 ** set to true.
46714 ** The shared-cache leaves the 'pending lock' state when either of
46715 ** the following occur:
46717 ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
46718 ** 2) The number of locks held by other connections drops to zero.
46720 ** while in the 'pending-lock' state, no connection may start a new
46721 ** transaction.
46723 ** This feature is included to help prevent writer-starvation.
46725 struct BtShared {
46726 Pager *pPager; /* The page cache */
46727 sqlite3 *db; /* Database connection currently using this Btree */
46728 BtCursor *pCursor; /* A list of all open cursors */
46729 MemPage *pPage1; /* First page of the database */
46730 u8 readOnly; /* True if the underlying file is readonly */
46731 u8 pageSizeFixed; /* True if the page size can no longer be changed */
46732 u8 secureDelete; /* True if secure_delete is enabled */
46733 u8 initiallyEmpty; /* Database is empty at start of transaction */
46734 u8 openFlags; /* Flags to sqlite3BtreeOpen() */
46735 #ifndef SQLITE_OMIT_AUTOVACUUM
46736 u8 autoVacuum; /* True if auto-vacuum is enabled */
46737 u8 incrVacuum; /* True if incr-vacuum is enabled */
46738 #endif
46739 u8 inTransaction; /* Transaction state */
46740 u8 doNotUseWAL; /* If true, do not open write-ahead-log file */
46741 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
46742 u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
46743 u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
46744 u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
46745 u32 pageSize; /* Total number of bytes on a page */
46746 u32 usableSize; /* Number of usable bytes on each page */
46747 int nTransaction; /* Number of open transactions (read + write) */
46748 u32 nPage; /* Number of pages in the database */
46749 void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
46750 void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
46751 sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
46752 Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
46753 #ifndef SQLITE_OMIT_SHARED_CACHE
46754 int nRef; /* Number of references to this structure */
46755 BtShared *pNext; /* Next on a list of sharable BtShared structs */
46756 BtLock *pLock; /* List of locks held on this shared-btree struct */
46757 Btree *pWriter; /* Btree with currently open write transaction */
46758 u8 isExclusive; /* True if pWriter has an EXCLUSIVE lock on the db */
46759 u8 isPending; /* If waiting for read-locks to clear */
46760 #endif
46761 u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
46765 ** An instance of the following structure is used to hold information
46766 ** about a cell. The parseCellPtr() function fills in this structure
46767 ** based on information extract from the raw disk page.
46769 typedef struct CellInfo CellInfo;
46770 struct CellInfo {
46771 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
46772 u8 *pCell; /* Pointer to the start of cell content */
46773 u32 nData; /* Number of bytes of data */
46774 u32 nPayload; /* Total amount of payload */
46775 u16 nHeader; /* Size of the cell content header in bytes */
46776 u16 nLocal; /* Amount of payload held locally */
46777 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
46778 u16 nSize; /* Size of the cell content on the main b-tree page */
46782 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
46783 ** this will be declared corrupt. This value is calculated based on a
46784 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
46785 ** root-node and 3 for all other internal nodes.
46787 ** If a tree that appears to be taller than this is encountered, it is
46788 ** assumed that the database is corrupt.
46790 #define BTCURSOR_MAX_DEPTH 20
46793 ** A cursor is a pointer to a particular entry within a particular
46794 ** b-tree within a database file.
46796 ** The entry is identified by its MemPage and the index in
46797 ** MemPage.aCell[] of the entry.
46799 ** A single database file can shared by two more database connections,
46800 ** but cursors cannot be shared. Each cursor is associated with a
46801 ** particular database connection identified BtCursor.pBtree.db.
46803 ** Fields in this structure are accessed under the BtShared.mutex
46804 ** found at self->pBt->mutex.
46806 struct BtCursor {
46807 Btree *pBtree; /* The Btree to which this cursor belongs */
46808 BtShared *pBt; /* The BtShared this cursor points to */
46809 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
46810 struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
46811 Pgno pgnoRoot; /* The root page of this tree */
46812 sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
46813 CellInfo info; /* A parse of the cell we are pointing at */
46814 i64 nKey; /* Size of pKey, or last integer key */
46815 void *pKey; /* Saved key that was cursor's last known position */
46816 int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
46817 u8 wrFlag; /* True if writable */
46818 u8 atLast; /* Cursor pointing to the last entry */
46819 u8 validNKey; /* True if info.nKey is valid */
46820 u8 eState; /* One of the CURSOR_XXX constants (see below) */
46821 #ifndef SQLITE_OMIT_INCRBLOB
46822 Pgno *aOverflow; /* Cache of overflow page locations */
46823 u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
46824 #endif
46825 i16 iPage; /* Index of current page in apPage */
46826 u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
46827 MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
46831 ** Potential values for BtCursor.eState.
46833 ** CURSOR_VALID:
46834 ** Cursor points to a valid entry. getPayload() etc. may be called.
46836 ** CURSOR_INVALID:
46837 ** Cursor does not point to a valid entry. This can happen (for example)
46838 ** because the table is empty or because BtreeCursorFirst() has not been
46839 ** called.
46841 ** CURSOR_REQUIRESEEK:
46842 ** The table that this cursor was opened on still exists, but has been
46843 ** modified since the cursor was last used. The cursor position is saved
46844 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
46845 ** this state, restoreCursorPosition() can be called to attempt to
46846 ** seek the cursor to the saved position.
46848 ** CURSOR_FAULT:
46849 ** A unrecoverable error (an I/O error or a malloc failure) has occurred
46850 ** on a different connection that shares the BtShared cache with this
46851 ** cursor. The error has left the cache in an inconsistent state.
46852 ** Do nothing else with this cursor. Any attempt to use the cursor
46853 ** should return the error code stored in BtCursor.skip
46855 #define CURSOR_INVALID 0
46856 #define CURSOR_VALID 1
46857 #define CURSOR_REQUIRESEEK 2
46858 #define CURSOR_FAULT 3
46861 ** The database page the PENDING_BYTE occupies. This page is never used.
46863 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
46866 ** These macros define the location of the pointer-map entry for a
46867 ** database page. The first argument to each is the number of usable
46868 ** bytes on each page of the database (often 1024). The second is the
46869 ** page number to look up in the pointer map.
46871 ** PTRMAP_PAGENO returns the database page number of the pointer-map
46872 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
46873 ** the offset of the requested map entry.
46875 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
46876 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
46877 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
46878 ** this test.
46880 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
46881 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
46882 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
46885 ** The pointer map is a lookup table that identifies the parent page for
46886 ** each child page in the database file. The parent page is the page that
46887 ** contains a pointer to the child. Every page in the database contains
46888 ** 0 or 1 parent pages. (In this context 'database page' refers
46889 ** to any page that is not part of the pointer map itself.) Each pointer map
46890 ** entry consists of a single byte 'type' and a 4 byte parent page number.
46891 ** The PTRMAP_XXX identifiers below are the valid types.
46893 ** The purpose of the pointer map is to facility moving pages from one
46894 ** position in the file to another as part of autovacuum. When a page
46895 ** is moved, the pointer in its parent must be updated to point to the
46896 ** new location. The pointer map is used to locate the parent page quickly.
46898 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
46899 ** used in this case.
46901 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
46902 ** is not used in this case.
46904 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
46905 ** overflow pages. The page number identifies the page that
46906 ** contains the cell with a pointer to this overflow page.
46908 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
46909 ** overflow pages. The page-number identifies the previous
46910 ** page in the overflow page list.
46912 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
46913 ** identifies the parent page in the btree.
46915 #define PTRMAP_ROOTPAGE 1
46916 #define PTRMAP_FREEPAGE 2
46917 #define PTRMAP_OVERFLOW1 3
46918 #define PTRMAP_OVERFLOW2 4
46919 #define PTRMAP_BTREE 5
46921 /* A bunch of assert() statements to check the transaction state variables
46922 ** of handle p (type Btree*) are internally consistent.
46924 #define btreeIntegrity(p) \
46925 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
46926 assert( p->pBt->inTransaction>=p->inTrans );
46930 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
46931 ** if the database supports auto-vacuum or not. Because it is used
46932 ** within an expression that is an argument to another macro
46933 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
46934 ** So, this macro is defined instead.
46936 #ifndef SQLITE_OMIT_AUTOVACUUM
46937 #define ISAUTOVACUUM (pBt->autoVacuum)
46938 #else
46939 #define ISAUTOVACUUM 0
46940 #endif
46944 ** This structure is passed around through all the sanity checking routines
46945 ** in order to keep track of some global state information.
46947 typedef struct IntegrityCk IntegrityCk;
46948 struct IntegrityCk {
46949 BtShared *pBt; /* The tree being checked out */
46950 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
46951 Pgno nPage; /* Number of pages in the database */
46952 int *anRef; /* Number of times each page is referenced */
46953 int mxErr; /* Stop accumulating errors when this reaches zero */
46954 int nErr; /* Number of messages written to zErrMsg so far */
46955 int mallocFailed; /* A memory allocation error has occurred */
46956 StrAccum errMsg; /* Accumulate the error message text here */
46960 ** Read or write a two- and four-byte big-endian integer values.
46962 #define get2byte(x) ((x)[0]<<8 | (x)[1])
46963 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
46964 #define get4byte sqlite3Get4byte
46965 #define put4byte sqlite3Put4byte
46967 /************** End of btreeInt.h ********************************************/
46968 /************** Continuing where we left off in btmutex.c ********************/
46969 #ifndef SQLITE_OMIT_SHARED_CACHE
46970 #if SQLITE_THREADSAFE
46973 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
46974 ** set BtShared.db to the database handle associated with p and the
46975 ** p->locked boolean to true.
46977 static void lockBtreeMutex(Btree *p){
46978 assert( p->locked==0 );
46979 assert( sqlite3_mutex_notheld(p->pBt->mutex) );
46980 assert( sqlite3_mutex_held(p->db->mutex) );
46982 sqlite3_mutex_enter(p->pBt->mutex);
46983 p->pBt->db = p->db;
46984 p->locked = 1;
46988 ** Release the BtShared mutex associated with B-Tree handle p and
46989 ** clear the p->locked boolean.
46991 static void unlockBtreeMutex(Btree *p){
46992 BtShared *pBt = p->pBt;
46993 assert( p->locked==1 );
46994 assert( sqlite3_mutex_held(pBt->mutex) );
46995 assert( sqlite3_mutex_held(p->db->mutex) );
46996 assert( p->db==pBt->db );
46998 sqlite3_mutex_leave(pBt->mutex);
46999 p->locked = 0;
47003 ** Enter a mutex on the given BTree object.
47005 ** If the object is not sharable, then no mutex is ever required
47006 ** and this routine is a no-op. The underlying mutex is non-recursive.
47007 ** But we keep a reference count in Btree.wantToLock so the behavior
47008 ** of this interface is recursive.
47010 ** To avoid deadlocks, multiple Btrees are locked in the same order
47011 ** by all database connections. The p->pNext is a list of other
47012 ** Btrees belonging to the same database connection as the p Btree
47013 ** which need to be locked after p. If we cannot get a lock on
47014 ** p, then first unlock all of the others on p->pNext, then wait
47015 ** for the lock to become available on p, then relock all of the
47016 ** subsequent Btrees that desire a lock.
47018 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
47019 Btree *pLater;
47021 /* Some basic sanity checking on the Btree. The list of Btrees
47022 ** connected by pNext and pPrev should be in sorted order by
47023 ** Btree.pBt value. All elements of the list should belong to
47024 ** the same connection. Only shared Btrees are on the list. */
47025 assert( p->pNext==0 || p->pNext->pBt>p->pBt );
47026 assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
47027 assert( p->pNext==0 || p->pNext->db==p->db );
47028 assert( p->pPrev==0 || p->pPrev->db==p->db );
47029 assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
47031 /* Check for locking consistency */
47032 assert( !p->locked || p->wantToLock>0 );
47033 assert( p->sharable || p->wantToLock==0 );
47035 /* We should already hold a lock on the database connection */
47036 assert( sqlite3_mutex_held(p->db->mutex) );
47038 /* Unless the database is sharable and unlocked, then BtShared.db
47039 ** should already be set correctly. */
47040 assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
47042 if( !p->sharable ) return;
47043 p->wantToLock++;
47044 if( p->locked ) return;
47046 /* In most cases, we should be able to acquire the lock we
47047 ** want without having to go throught the ascending lock
47048 ** procedure that follows. Just be sure not to block.
47050 if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
47051 p->pBt->db = p->db;
47052 p->locked = 1;
47053 return;
47056 /* To avoid deadlock, first release all locks with a larger
47057 ** BtShared address. Then acquire our lock. Then reacquire
47058 ** the other BtShared locks that we used to hold in ascending
47059 ** order.
47061 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
47062 assert( pLater->sharable );
47063 assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
47064 assert( !pLater->locked || pLater->wantToLock>0 );
47065 if( pLater->locked ){
47066 unlockBtreeMutex(pLater);
47069 lockBtreeMutex(p);
47070 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
47071 if( pLater->wantToLock ){
47072 lockBtreeMutex(pLater);
47078 ** Exit the recursive mutex on a Btree.
47080 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
47081 if( p->sharable ){
47082 assert( p->wantToLock>0 );
47083 p->wantToLock--;
47084 if( p->wantToLock==0 ){
47085 unlockBtreeMutex(p);
47090 #ifndef NDEBUG
47092 ** Return true if the BtShared mutex is held on the btree, or if the
47093 ** B-Tree is not marked as sharable.
47095 ** This routine is used only from within assert() statements.
47097 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
47098 assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
47099 assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
47100 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
47101 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
47103 return (p->sharable==0 || p->locked);
47105 #endif
47108 #ifndef SQLITE_OMIT_INCRBLOB
47110 ** Enter and leave a mutex on a Btree given a cursor owned by that
47111 ** Btree. These entry points are used by incremental I/O and can be
47112 ** omitted if that module is not used.
47114 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
47115 sqlite3BtreeEnter(pCur->pBtree);
47117 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
47118 sqlite3BtreeLeave(pCur->pBtree);
47120 #endif /* SQLITE_OMIT_INCRBLOB */
47124 ** Enter the mutex on every Btree associated with a database
47125 ** connection. This is needed (for example) prior to parsing
47126 ** a statement since we will be comparing table and column names
47127 ** against all schemas and we do not want those schemas being
47128 ** reset out from under us.
47130 ** There is a corresponding leave-all procedures.
47132 ** Enter the mutexes in accending order by BtShared pointer address
47133 ** to avoid the possibility of deadlock when two threads with
47134 ** two or more btrees in common both try to lock all their btrees
47135 ** at the same instant.
47137 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
47138 int i;
47139 Btree *p;
47140 assert( sqlite3_mutex_held(db->mutex) );
47141 for(i=0; i<db->nDb; i++){
47142 p = db->aDb[i].pBt;
47143 if( p ) sqlite3BtreeEnter(p);
47146 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
47147 int i;
47148 Btree *p;
47149 assert( sqlite3_mutex_held(db->mutex) );
47150 for(i=0; i<db->nDb; i++){
47151 p = db->aDb[i].pBt;
47152 if( p ) sqlite3BtreeLeave(p);
47157 ** Return true if a particular Btree requires a lock. Return FALSE if
47158 ** no lock is ever required since it is not sharable.
47160 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
47161 return p->sharable;
47164 #ifndef NDEBUG
47166 ** Return true if the current thread holds the database connection
47167 ** mutex and all required BtShared mutexes.
47169 ** This routine is used inside assert() statements only.
47171 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
47172 int i;
47173 if( !sqlite3_mutex_held(db->mutex) ){
47174 return 0;
47176 for(i=0; i<db->nDb; i++){
47177 Btree *p;
47178 p = db->aDb[i].pBt;
47179 if( p && p->sharable &&
47180 (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
47181 return 0;
47184 return 1;
47186 #endif /* NDEBUG */
47188 #ifndef NDEBUG
47190 ** Return true if the correct mutexes are held for accessing the
47191 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
47192 ** access are:
47194 ** (1) The mutex on db
47195 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
47197 ** If pSchema is not NULL, then iDb is computed from pSchema and
47198 ** db using sqlite3SchemaToIndex().
47200 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
47201 Btree *p;
47202 assert( db!=0 );
47203 if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
47204 assert( iDb>=0 && iDb<db->nDb );
47205 if( !sqlite3_mutex_held(db->mutex) ) return 0;
47206 if( iDb==1 ) return 1;
47207 p = db->aDb[iDb].pBt;
47208 assert( p!=0 );
47209 return p->sharable==0 || p->locked==1;
47211 #endif /* NDEBUG */
47213 #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
47215 ** The following are special cases for mutex enter routines for use
47216 ** in single threaded applications that use shared cache. Except for
47217 ** these two routines, all mutex operations are no-ops in that case and
47218 ** are null #defines in btree.h.
47220 ** If shared cache is disabled, then all btree mutex routines, including
47221 ** the ones below, are no-ops and are null #defines in btree.h.
47224 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
47225 p->pBt->db = p->db;
47227 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
47228 int i;
47229 for(i=0; i<db->nDb; i++){
47230 Btree *p = db->aDb[i].pBt;
47231 if( p ){
47232 p->pBt->db = p->db;
47236 #endif /* if SQLITE_THREADSAFE */
47237 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
47239 /************** End of btmutex.c *********************************************/
47240 /************** Begin file btree.c *******************************************/
47242 ** 2004 April 6
47244 ** The author disclaims copyright to this source code. In place of
47245 ** a legal notice, here is a blessing:
47247 ** May you do good and not evil.
47248 ** May you find forgiveness for yourself and forgive others.
47249 ** May you share freely, never taking more than you give.
47251 *************************************************************************
47252 ** This file implements a external (disk-based) database using BTrees.
47253 ** See the header comment on "btreeInt.h" for additional information.
47254 ** Including a description of file format and an overview of operation.
47258 ** The header string that appears at the beginning of every
47259 ** SQLite database.
47261 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
47264 ** Set this global variable to 1 to enable tracing using the TRACE
47265 ** macro.
47267 #if 0
47268 int sqlite3BtreeTrace=1; /* True to enable tracing */
47269 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
47270 #else
47271 # define TRACE(X)
47272 #endif
47275 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
47276 ** But if the value is zero, make it 65536.
47278 ** This routine is used to extract the "offset to cell content area" value
47279 ** from the header of a btree page. If the page size is 65536 and the page
47280 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
47281 ** This routine makes the necessary adjustment to 65536.
47283 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
47285 #ifndef SQLITE_OMIT_SHARED_CACHE
47287 ** A list of BtShared objects that are eligible for participation
47288 ** in shared cache. This variable has file scope during normal builds,
47289 ** but the test harness needs to access it so we make it global for
47290 ** test builds.
47292 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
47294 #ifdef SQLITE_TEST
47295 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47296 #else
47297 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47298 #endif
47299 #endif /* SQLITE_OMIT_SHARED_CACHE */
47301 #ifndef SQLITE_OMIT_SHARED_CACHE
47303 ** Enable or disable the shared pager and schema features.
47305 ** This routine has no effect on existing database connections.
47306 ** The shared cache setting effects only future calls to
47307 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
47309 SQLITE_API int sqlite3_enable_shared_cache(int enable){
47310 sqlite3GlobalConfig.sharedCacheEnabled = enable;
47311 return SQLITE_OK;
47313 #endif
47317 #ifdef SQLITE_OMIT_SHARED_CACHE
47319 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
47320 ** and clearAllSharedCacheTableLocks()
47321 ** manipulate entries in the BtShared.pLock linked list used to store
47322 ** shared-cache table level locks. If the library is compiled with the
47323 ** shared-cache feature disabled, then there is only ever one user
47324 ** of each BtShared structure and so this locking is not necessary.
47325 ** So define the lock related functions as no-ops.
47327 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
47328 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
47329 #define clearAllSharedCacheTableLocks(a)
47330 #define downgradeAllSharedCacheTableLocks(a)
47331 #define hasSharedCacheTableLock(a,b,c,d) 1
47332 #define hasReadConflicts(a, b) 0
47333 #endif
47335 #ifndef SQLITE_OMIT_SHARED_CACHE
47337 #ifdef SQLITE_DEBUG
47339 **** This function is only used as part of an assert() statement. ***
47341 ** Check to see if pBtree holds the required locks to read or write to the
47342 ** table with root page iRoot. Return 1 if it does and 0 if not.
47344 ** For example, when writing to a table with root-page iRoot via
47345 ** Btree connection pBtree:
47347 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
47349 ** When writing to an index that resides in a sharable database, the
47350 ** caller should have first obtained a lock specifying the root page of
47351 ** the corresponding table. This makes things a bit more complicated,
47352 ** as this module treats each table as a separate structure. To determine
47353 ** the table corresponding to the index being written, this
47354 ** function has to search through the database schema.
47356 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
47357 ** hold a write-lock on the schema table (root page 1). This is also
47358 ** acceptable.
47360 static int hasSharedCacheTableLock(
47361 Btree *pBtree, /* Handle that must hold lock */
47362 Pgno iRoot, /* Root page of b-tree */
47363 int isIndex, /* True if iRoot is the root of an index b-tree */
47364 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
47366 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
47367 Pgno iTab = 0;
47368 BtLock *pLock;
47370 /* If this database is not shareable, or if the client is reading
47371 ** and has the read-uncommitted flag set, then no lock is required.
47372 ** Return true immediately.
47374 if( (pBtree->sharable==0)
47375 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
47377 return 1;
47380 /* If the client is reading or writing an index and the schema is
47381 ** not loaded, then it is too difficult to actually check to see if
47382 ** the correct locks are held. So do not bother - just return true.
47383 ** This case does not come up very often anyhow.
47385 if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
47386 return 1;
47389 /* Figure out the root-page that the lock should be held on. For table
47390 ** b-trees, this is just the root page of the b-tree being read or
47391 ** written. For index b-trees, it is the root page of the associated
47392 ** table. */
47393 if( isIndex ){
47394 HashElem *p;
47395 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
47396 Index *pIdx = (Index *)sqliteHashData(p);
47397 if( pIdx->tnum==(int)iRoot ){
47398 iTab = pIdx->pTable->tnum;
47401 }else{
47402 iTab = iRoot;
47405 /* Search for the required lock. Either a write-lock on root-page iTab, a
47406 ** write-lock on the schema table, or (if the client is reading) a
47407 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
47408 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
47409 if( pLock->pBtree==pBtree
47410 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
47411 && pLock->eLock>=eLockType
47413 return 1;
47417 /* Failed to find the required lock. */
47418 return 0;
47420 #endif /* SQLITE_DEBUG */
47422 #ifdef SQLITE_DEBUG
47424 **** This function may be used as part of assert() statements only. ****
47426 ** Return true if it would be illegal for pBtree to write into the
47427 ** table or index rooted at iRoot because other shared connections are
47428 ** simultaneously reading that same table or index.
47430 ** It is illegal for pBtree to write if some other Btree object that
47431 ** shares the same BtShared object is currently reading or writing
47432 ** the iRoot table. Except, if the other Btree object has the
47433 ** read-uncommitted flag set, then it is OK for the other object to
47434 ** have a read cursor.
47436 ** For example, before writing to any part of the table or index
47437 ** rooted at page iRoot, one should call:
47439 ** assert( !hasReadConflicts(pBtree, iRoot) );
47441 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
47442 BtCursor *p;
47443 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
47444 if( p->pgnoRoot==iRoot
47445 && p->pBtree!=pBtree
47446 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
47448 return 1;
47451 return 0;
47453 #endif /* #ifdef SQLITE_DEBUG */
47456 ** Query to see if Btree handle p may obtain a lock of type eLock
47457 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
47458 ** SQLITE_OK if the lock may be obtained (by calling
47459 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
47461 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
47462 BtShared *pBt = p->pBt;
47463 BtLock *pIter;
47465 assert( sqlite3BtreeHoldsMutex(p) );
47466 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47467 assert( p->db!=0 );
47468 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
47470 /* If requesting a write-lock, then the Btree must have an open write
47471 ** transaction on this file. And, obviously, for this to be so there
47472 ** must be an open write transaction on the file itself.
47474 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
47475 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
47477 /* This routine is a no-op if the shared-cache is not enabled */
47478 if( !p->sharable ){
47479 return SQLITE_OK;
47482 /* If some other connection is holding an exclusive lock, the
47483 ** requested lock may not be obtained.
47485 if( pBt->pWriter!=p && pBt->isExclusive ){
47486 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
47487 return SQLITE_LOCKED_SHAREDCACHE;
47490 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47491 /* The condition (pIter->eLock!=eLock) in the following if(...)
47492 ** statement is a simplification of:
47494 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
47496 ** since we know that if eLock==WRITE_LOCK, then no other connection
47497 ** may hold a WRITE_LOCK on any table in this file (since there can
47498 ** only be a single writer).
47500 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
47501 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
47502 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
47503 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
47504 if( eLock==WRITE_LOCK ){
47505 assert( p==pBt->pWriter );
47506 pBt->isPending = 1;
47508 return SQLITE_LOCKED_SHAREDCACHE;
47511 return SQLITE_OK;
47513 #endif /* !SQLITE_OMIT_SHARED_CACHE */
47515 #ifndef SQLITE_OMIT_SHARED_CACHE
47517 ** Add a lock on the table with root-page iTable to the shared-btree used
47518 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
47519 ** WRITE_LOCK.
47521 ** This function assumes the following:
47523 ** (a) The specified Btree object p is connected to a sharable
47524 ** database (one with the BtShared.sharable flag set), and
47526 ** (b) No other Btree objects hold a lock that conflicts
47527 ** with the requested lock (i.e. querySharedCacheTableLock() has
47528 ** already been called and returned SQLITE_OK).
47530 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
47531 ** is returned if a malloc attempt fails.
47533 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
47534 BtShared *pBt = p->pBt;
47535 BtLock *pLock = 0;
47536 BtLock *pIter;
47538 assert( sqlite3BtreeHoldsMutex(p) );
47539 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47540 assert( p->db!=0 );
47542 /* A connection with the read-uncommitted flag set will never try to
47543 ** obtain a read-lock using this function. The only read-lock obtained
47544 ** by a connection in read-uncommitted mode is on the sqlite_master
47545 ** table, and that lock is obtained in BtreeBeginTrans(). */
47546 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
47548 /* This function should only be called on a sharable b-tree after it
47549 ** has been determined that no other b-tree holds a conflicting lock. */
47550 assert( p->sharable );
47551 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
47553 /* First search the list for an existing lock on this table. */
47554 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47555 if( pIter->iTable==iTable && pIter->pBtree==p ){
47556 pLock = pIter;
47557 break;
47561 /* If the above search did not find a BtLock struct associating Btree p
47562 ** with table iTable, allocate one and link it into the list.
47564 if( !pLock ){
47565 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
47566 if( !pLock ){
47567 return SQLITE_NOMEM;
47569 pLock->iTable = iTable;
47570 pLock->pBtree = p;
47571 pLock->pNext = pBt->pLock;
47572 pBt->pLock = pLock;
47575 /* Set the BtLock.eLock variable to the maximum of the current lock
47576 ** and the requested lock. This means if a write-lock was already held
47577 ** and a read-lock requested, we don't incorrectly downgrade the lock.
47579 assert( WRITE_LOCK>READ_LOCK );
47580 if( eLock>pLock->eLock ){
47581 pLock->eLock = eLock;
47584 return SQLITE_OK;
47586 #endif /* !SQLITE_OMIT_SHARED_CACHE */
47588 #ifndef SQLITE_OMIT_SHARED_CACHE
47590 ** Release all the table locks (locks obtained via calls to
47591 ** the setSharedCacheTableLock() procedure) held by Btree object p.
47593 ** This function assumes that Btree p has an open read or write
47594 ** transaction. If it does not, then the BtShared.isPending variable
47595 ** may be incorrectly cleared.
47597 static void clearAllSharedCacheTableLocks(Btree *p){
47598 BtShared *pBt = p->pBt;
47599 BtLock **ppIter = &pBt->pLock;
47601 assert( sqlite3BtreeHoldsMutex(p) );
47602 assert( p->sharable || 0==*ppIter );
47603 assert( p->inTrans>0 );
47605 while( *ppIter ){
47606 BtLock *pLock = *ppIter;
47607 assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
47608 assert( pLock->pBtree->inTrans>=pLock->eLock );
47609 if( pLock->pBtree==p ){
47610 *ppIter = pLock->pNext;
47611 assert( pLock->iTable!=1 || pLock==&p->lock );
47612 if( pLock->iTable!=1 ){
47613 sqlite3_free(pLock);
47615 }else{
47616 ppIter = &pLock->pNext;
47620 assert( pBt->isPending==0 || pBt->pWriter );
47621 if( pBt->pWriter==p ){
47622 pBt->pWriter = 0;
47623 pBt->isExclusive = 0;
47624 pBt->isPending = 0;
47625 }else if( pBt->nTransaction==2 ){
47626 /* This function is called when Btree p is concluding its
47627 ** transaction. If there currently exists a writer, and p is not
47628 ** that writer, then the number of locks held by connections other
47629 ** than the writer must be about to drop to zero. In this case
47630 ** set the isPending flag to 0.
47632 ** If there is not currently a writer, then BtShared.isPending must
47633 ** be zero already. So this next line is harmless in that case.
47635 pBt->isPending = 0;
47640 ** This function changes all write-locks held by Btree p into read-locks.
47642 static void downgradeAllSharedCacheTableLocks(Btree *p){
47643 BtShared *pBt = p->pBt;
47644 if( pBt->pWriter==p ){
47645 BtLock *pLock;
47646 pBt->pWriter = 0;
47647 pBt->isExclusive = 0;
47648 pBt->isPending = 0;
47649 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
47650 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
47651 pLock->eLock = READ_LOCK;
47656 #endif /* SQLITE_OMIT_SHARED_CACHE */
47658 static void releasePage(MemPage *pPage); /* Forward reference */
47661 ***** This routine is used inside of assert() only ****
47663 ** Verify that the cursor holds the mutex on its BtShared
47665 #ifdef SQLITE_DEBUG
47666 static int cursorHoldsMutex(BtCursor *p){
47667 return sqlite3_mutex_held(p->pBt->mutex);
47669 #endif
47672 #ifndef SQLITE_OMIT_INCRBLOB
47674 ** Invalidate the overflow page-list cache for cursor pCur, if any.
47676 static void invalidateOverflowCache(BtCursor *pCur){
47677 assert( cursorHoldsMutex(pCur) );
47678 sqlite3_free(pCur->aOverflow);
47679 pCur->aOverflow = 0;
47683 ** Invalidate the overflow page-list cache for all cursors opened
47684 ** on the shared btree structure pBt.
47686 static void invalidateAllOverflowCache(BtShared *pBt){
47687 BtCursor *p;
47688 assert( sqlite3_mutex_held(pBt->mutex) );
47689 for(p=pBt->pCursor; p; p=p->pNext){
47690 invalidateOverflowCache(p);
47695 ** This function is called before modifying the contents of a table
47696 ** to invalidate any incrblob cursors that are open on the
47697 ** row or one of the rows being modified.
47699 ** If argument isClearTable is true, then the entire contents of the
47700 ** table is about to be deleted. In this case invalidate all incrblob
47701 ** cursors open on any row within the table with root-page pgnoRoot.
47703 ** Otherwise, if argument isClearTable is false, then the row with
47704 ** rowid iRow is being replaced or deleted. In this case invalidate
47705 ** only those incrblob cursors open on that specific row.
47707 static void invalidateIncrblobCursors(
47708 Btree *pBtree, /* The database file to check */
47709 i64 iRow, /* The rowid that might be changing */
47710 int isClearTable /* True if all rows are being deleted */
47712 BtCursor *p;
47713 BtShared *pBt = pBtree->pBt;
47714 assert( sqlite3BtreeHoldsMutex(pBtree) );
47715 for(p=pBt->pCursor; p; p=p->pNext){
47716 if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
47717 p->eState = CURSOR_INVALID;
47722 #else
47723 /* Stub functions when INCRBLOB is omitted */
47724 #define invalidateOverflowCache(x)
47725 #define invalidateAllOverflowCache(x)
47726 #define invalidateIncrblobCursors(x,y,z)
47727 #endif /* SQLITE_OMIT_INCRBLOB */
47730 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
47731 ** when a page that previously contained data becomes a free-list leaf
47732 ** page.
47734 ** The BtShared.pHasContent bitvec exists to work around an obscure
47735 ** bug caused by the interaction of two useful IO optimizations surrounding
47736 ** free-list leaf pages:
47738 ** 1) When all data is deleted from a page and the page becomes
47739 ** a free-list leaf page, the page is not written to the database
47740 ** (as free-list leaf pages contain no meaningful data). Sometimes
47741 ** such a page is not even journalled (as it will not be modified,
47742 ** why bother journalling it?).
47744 ** 2) When a free-list leaf page is reused, its content is not read
47745 ** from the database or written to the journal file (why should it
47746 ** be, if it is not at all meaningful?).
47748 ** By themselves, these optimizations work fine and provide a handy
47749 ** performance boost to bulk delete or insert operations. However, if
47750 ** a page is moved to the free-list and then reused within the same
47751 ** transaction, a problem comes up. If the page is not journalled when
47752 ** it is moved to the free-list and it is also not journalled when it
47753 ** is extracted from the free-list and reused, then the original data
47754 ** may be lost. In the event of a rollback, it may not be possible
47755 ** to restore the database to its original configuration.
47757 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
47758 ** moved to become a free-list leaf page, the corresponding bit is
47759 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
47760 ** optimization 2 above is omitted if the corresponding bit is already
47761 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
47762 ** at the end of every transaction.
47764 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
47765 int rc = SQLITE_OK;
47766 if( !pBt->pHasContent ){
47767 assert( pgno<=pBt->nPage );
47768 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
47769 if( !pBt->pHasContent ){
47770 rc = SQLITE_NOMEM;
47773 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
47774 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
47776 return rc;
47780 ** Query the BtShared.pHasContent vector.
47782 ** This function is called when a free-list leaf page is removed from the
47783 ** free-list for reuse. It returns false if it is safe to retrieve the
47784 ** page from the pager layer with the 'no-content' flag set. True otherwise.
47786 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
47787 Bitvec *p = pBt->pHasContent;
47788 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
47792 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
47793 ** invoked at the conclusion of each write-transaction.
47795 static void btreeClearHasContent(BtShared *pBt){
47796 sqlite3BitvecDestroy(pBt->pHasContent);
47797 pBt->pHasContent = 0;
47801 ** Save the current cursor position in the variables BtCursor.nKey
47802 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
47804 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
47805 ** prior to calling this routine.
47807 static int saveCursorPosition(BtCursor *pCur){
47808 int rc;
47810 assert( CURSOR_VALID==pCur->eState );
47811 assert( 0==pCur->pKey );
47812 assert( cursorHoldsMutex(pCur) );
47814 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
47815 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
47817 /* If this is an intKey table, then the above call to BtreeKeySize()
47818 ** stores the integer key in pCur->nKey. In this case this value is
47819 ** all that is required. Otherwise, if pCur is not open on an intKey
47820 ** table, then malloc space for and store the pCur->nKey bytes of key
47821 ** data.
47823 if( 0==pCur->apPage[0]->intKey ){
47824 void *pKey = sqlite3Malloc( (int)pCur->nKey );
47825 if( pKey ){
47826 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
47827 if( rc==SQLITE_OK ){
47828 pCur->pKey = pKey;
47829 }else{
47830 sqlite3_free(pKey);
47832 }else{
47833 rc = SQLITE_NOMEM;
47836 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
47838 if( rc==SQLITE_OK ){
47839 int i;
47840 for(i=0; i<=pCur->iPage; i++){
47841 releasePage(pCur->apPage[i]);
47842 pCur->apPage[i] = 0;
47844 pCur->iPage = -1;
47845 pCur->eState = CURSOR_REQUIRESEEK;
47848 invalidateOverflowCache(pCur);
47849 return rc;
47853 ** Save the positions of all cursors (except pExcept) that are open on
47854 ** the table with root-page iRoot. Usually, this is called just before cursor
47855 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
47857 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
47858 BtCursor *p;
47859 assert( sqlite3_mutex_held(pBt->mutex) );
47860 assert( pExcept==0 || pExcept->pBt==pBt );
47861 for(p=pBt->pCursor; p; p=p->pNext){
47862 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
47863 p->eState==CURSOR_VALID ){
47864 int rc = saveCursorPosition(p);
47865 if( SQLITE_OK!=rc ){
47866 return rc;
47870 return SQLITE_OK;
47874 ** Clear the current cursor position.
47876 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
47877 assert( cursorHoldsMutex(pCur) );
47878 sqlite3_free(pCur->pKey);
47879 pCur->pKey = 0;
47880 pCur->eState = CURSOR_INVALID;
47884 ** In this version of BtreeMoveto, pKey is a packed index record
47885 ** such as is generated by the OP_MakeRecord opcode. Unpack the
47886 ** record and then call BtreeMovetoUnpacked() to do the work.
47888 static int btreeMoveto(
47889 BtCursor *pCur, /* Cursor open on the btree to be searched */
47890 const void *pKey, /* Packed key if the btree is an index */
47891 i64 nKey, /* Integer key for tables. Size of pKey for indices */
47892 int bias, /* Bias search to the high end */
47893 int *pRes /* Write search results here */
47895 int rc; /* Status code */
47896 UnpackedRecord *pIdxKey; /* Unpacked index key */
47897 char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
47899 if( pKey ){
47900 assert( nKey==(i64)(int)nKey );
47901 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
47902 aSpace, sizeof(aSpace));
47903 if( pIdxKey==0 ) return SQLITE_NOMEM;
47904 }else{
47905 pIdxKey = 0;
47907 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
47908 if( pKey ){
47909 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
47911 return rc;
47915 ** Restore the cursor to the position it was in (or as close to as possible)
47916 ** when saveCursorPosition() was called. Note that this call deletes the
47917 ** saved position info stored by saveCursorPosition(), so there can be
47918 ** at most one effective restoreCursorPosition() call after each
47919 ** saveCursorPosition().
47921 static int btreeRestoreCursorPosition(BtCursor *pCur){
47922 int rc;
47923 assert( cursorHoldsMutex(pCur) );
47924 assert( pCur->eState>=CURSOR_REQUIRESEEK );
47925 if( pCur->eState==CURSOR_FAULT ){
47926 return pCur->skipNext;
47928 pCur->eState = CURSOR_INVALID;
47929 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
47930 if( rc==SQLITE_OK ){
47931 sqlite3_free(pCur->pKey);
47932 pCur->pKey = 0;
47933 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
47935 return rc;
47938 #define restoreCursorPosition(p) \
47939 (p->eState>=CURSOR_REQUIRESEEK ? \
47940 btreeRestoreCursorPosition(p) : \
47941 SQLITE_OK)
47944 ** Determine whether or not a cursor has moved from the position it
47945 ** was last placed at. Cursors can move when the row they are pointing
47946 ** at is deleted out from under them.
47948 ** This routine returns an error code if something goes wrong. The
47949 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
47951 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
47952 int rc;
47954 rc = restoreCursorPosition(pCur);
47955 if( rc ){
47956 *pHasMoved = 1;
47957 return rc;
47959 if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
47960 *pHasMoved = 1;
47961 }else{
47962 *pHasMoved = 0;
47964 return SQLITE_OK;
47967 #ifndef SQLITE_OMIT_AUTOVACUUM
47969 ** Given a page number of a regular database page, return the page
47970 ** number for the pointer-map page that contains the entry for the
47971 ** input page number.
47973 ** Return 0 (not a valid page) for pgno==1 since there is
47974 ** no pointer map associated with page 1. The integrity_check logic
47975 ** requires that ptrmapPageno(*,1)!=1.
47977 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
47978 int nPagesPerMapPage;
47979 Pgno iPtrMap, ret;
47980 assert( sqlite3_mutex_held(pBt->mutex) );
47981 if( pgno<2 ) return 0;
47982 nPagesPerMapPage = (pBt->usableSize/5)+1;
47983 iPtrMap = (pgno-2)/nPagesPerMapPage;
47984 ret = (iPtrMap*nPagesPerMapPage) + 2;
47985 if( ret==PENDING_BYTE_PAGE(pBt) ){
47986 ret++;
47988 return ret;
47992 ** Write an entry into the pointer map.
47994 ** This routine updates the pointer map entry for page number 'key'
47995 ** so that it maps to type 'eType' and parent page number 'pgno'.
47997 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
47998 ** a no-op. If an error occurs, the appropriate error code is written
47999 ** into *pRC.
48001 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
48002 DbPage *pDbPage; /* The pointer map page */
48003 u8 *pPtrmap; /* The pointer map data */
48004 Pgno iPtrmap; /* The pointer map page number */
48005 int offset; /* Offset in pointer map page */
48006 int rc; /* Return code from subfunctions */
48008 if( *pRC ) return;
48010 assert( sqlite3_mutex_held(pBt->mutex) );
48011 /* The master-journal page number must never be used as a pointer map page */
48012 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
48014 assert( pBt->autoVacuum );
48015 if( key==0 ){
48016 *pRC = SQLITE_CORRUPT_BKPT;
48017 return;
48019 iPtrmap = PTRMAP_PAGENO(pBt, key);
48020 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
48021 if( rc!=SQLITE_OK ){
48022 *pRC = rc;
48023 return;
48025 offset = PTRMAP_PTROFFSET(iPtrmap, key);
48026 if( offset<0 ){
48027 *pRC = SQLITE_CORRUPT_BKPT;
48028 goto ptrmap_exit;
48030 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
48032 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
48033 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
48034 *pRC= rc = sqlite3PagerWrite(pDbPage);
48035 if( rc==SQLITE_OK ){
48036 pPtrmap[offset] = eType;
48037 put4byte(&pPtrmap[offset+1], parent);
48041 ptrmap_exit:
48042 sqlite3PagerUnref(pDbPage);
48046 ** Read an entry from the pointer map.
48048 ** This routine retrieves the pointer map entry for page 'key', writing
48049 ** the type and parent page number to *pEType and *pPgno respectively.
48050 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
48052 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
48053 DbPage *pDbPage; /* The pointer map page */
48054 int iPtrmap; /* Pointer map page index */
48055 u8 *pPtrmap; /* Pointer map page data */
48056 int offset; /* Offset of entry in pointer map */
48057 int rc;
48059 assert( sqlite3_mutex_held(pBt->mutex) );
48061 iPtrmap = PTRMAP_PAGENO(pBt, key);
48062 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
48063 if( rc!=0 ){
48064 return rc;
48066 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
48068 offset = PTRMAP_PTROFFSET(iPtrmap, key);
48069 assert( pEType!=0 );
48070 *pEType = pPtrmap[offset];
48071 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
48073 sqlite3PagerUnref(pDbPage);
48074 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
48075 return SQLITE_OK;
48078 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
48079 #define ptrmapPut(w,x,y,z,rc)
48080 #define ptrmapGet(w,x,y,z) SQLITE_OK
48081 #define ptrmapPutOvflPtr(x, y, rc)
48082 #endif
48085 ** Given a btree page and a cell index (0 means the first cell on
48086 ** the page, 1 means the second cell, and so forth) return a pointer
48087 ** to the cell content.
48089 ** This routine works only for pages that do not contain overflow cells.
48091 #define findCell(P,I) \
48092 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
48095 ** This a more complex version of findCell() that works for
48096 ** pages that do contain overflow cells.
48098 static u8 *findOverflowCell(MemPage *pPage, int iCell){
48099 int i;
48100 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48101 for(i=pPage->nOverflow-1; i>=0; i--){
48102 int k;
48103 struct _OvflCell *pOvfl;
48104 pOvfl = &pPage->aOvfl[i];
48105 k = pOvfl->idx;
48106 if( k<=iCell ){
48107 if( k==iCell ){
48108 return pOvfl->pCell;
48110 iCell--;
48113 return findCell(pPage, iCell);
48117 ** Parse a cell content block and fill in the CellInfo structure. There
48118 ** are two versions of this function. btreeParseCell() takes a
48119 ** cell index as the second argument and btreeParseCellPtr()
48120 ** takes a pointer to the body of the cell as its second argument.
48122 ** Within this file, the parseCell() macro can be called instead of
48123 ** btreeParseCellPtr(). Using some compilers, this will be faster.
48125 static void btreeParseCellPtr(
48126 MemPage *pPage, /* Page containing the cell */
48127 u8 *pCell, /* Pointer to the cell text. */
48128 CellInfo *pInfo /* Fill in this structure */
48130 u16 n; /* Number bytes in cell content header */
48131 u32 nPayload; /* Number of bytes of cell payload */
48133 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48135 pInfo->pCell = pCell;
48136 assert( pPage->leaf==0 || pPage->leaf==1 );
48137 n = pPage->childPtrSize;
48138 assert( n==4-4*pPage->leaf );
48139 if( pPage->intKey ){
48140 if( pPage->hasData ){
48141 n += getVarint32(&pCell[n], nPayload);
48142 }else{
48143 nPayload = 0;
48145 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
48146 pInfo->nData = nPayload;
48147 }else{
48148 pInfo->nData = 0;
48149 n += getVarint32(&pCell[n], nPayload);
48150 pInfo->nKey = nPayload;
48152 pInfo->nPayload = nPayload;
48153 pInfo->nHeader = n;
48154 testcase( nPayload==pPage->maxLocal );
48155 testcase( nPayload==pPage->maxLocal+1 );
48156 if( likely(nPayload<=pPage->maxLocal) ){
48157 /* This is the (easy) common case where the entire payload fits
48158 ** on the local page. No overflow is required.
48160 if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
48161 pInfo->nLocal = (u16)nPayload;
48162 pInfo->iOverflow = 0;
48163 }else{
48164 /* If the payload will not fit completely on the local page, we have
48165 ** to decide how much to store locally and how much to spill onto
48166 ** overflow pages. The strategy is to minimize the amount of unused
48167 ** space on overflow pages while keeping the amount of local storage
48168 ** in between minLocal and maxLocal.
48170 ** Warning: changing the way overflow payload is distributed in any
48171 ** way will result in an incompatible file format.
48173 int minLocal; /* Minimum amount of payload held locally */
48174 int maxLocal; /* Maximum amount of payload held locally */
48175 int surplus; /* Overflow payload available for local storage */
48177 minLocal = pPage->minLocal;
48178 maxLocal = pPage->maxLocal;
48179 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
48180 testcase( surplus==maxLocal );
48181 testcase( surplus==maxLocal+1 );
48182 if( surplus <= maxLocal ){
48183 pInfo->nLocal = (u16)surplus;
48184 }else{
48185 pInfo->nLocal = (u16)minLocal;
48187 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
48188 pInfo->nSize = pInfo->iOverflow + 4;
48191 #define parseCell(pPage, iCell, pInfo) \
48192 btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
48193 static void btreeParseCell(
48194 MemPage *pPage, /* Page containing the cell */
48195 int iCell, /* The cell index. First cell is 0 */
48196 CellInfo *pInfo /* Fill in this structure */
48198 parseCell(pPage, iCell, pInfo);
48202 ** Compute the total number of bytes that a Cell needs in the cell
48203 ** data area of the btree-page. The return number includes the cell
48204 ** data header and the local payload, but not any overflow page or
48205 ** the space used by the cell pointer.
48207 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
48208 u8 *pIter = &pCell[pPage->childPtrSize];
48209 u32 nSize;
48211 #ifdef SQLITE_DEBUG
48212 /* The value returned by this function should always be the same as
48213 ** the (CellInfo.nSize) value found by doing a full parse of the
48214 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
48215 ** this function verifies that this invariant is not violated. */
48216 CellInfo debuginfo;
48217 btreeParseCellPtr(pPage, pCell, &debuginfo);
48218 #endif
48220 if( pPage->intKey ){
48221 u8 *pEnd;
48222 if( pPage->hasData ){
48223 pIter += getVarint32(pIter, nSize);
48224 }else{
48225 nSize = 0;
48228 /* pIter now points at the 64-bit integer key value, a variable length
48229 ** integer. The following block moves pIter to point at the first byte
48230 ** past the end of the key value. */
48231 pEnd = &pIter[9];
48232 while( (*pIter++)&0x80 && pIter<pEnd );
48233 }else{
48234 pIter += getVarint32(pIter, nSize);
48237 testcase( nSize==pPage->maxLocal );
48238 testcase( nSize==pPage->maxLocal+1 );
48239 if( nSize>pPage->maxLocal ){
48240 int minLocal = pPage->minLocal;
48241 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
48242 testcase( nSize==pPage->maxLocal );
48243 testcase( nSize==pPage->maxLocal+1 );
48244 if( nSize>pPage->maxLocal ){
48245 nSize = minLocal;
48247 nSize += 4;
48249 nSize += (u32)(pIter - pCell);
48251 /* The minimum size of any cell is 4 bytes. */
48252 if( nSize<4 ){
48253 nSize = 4;
48256 assert( nSize==debuginfo.nSize );
48257 return (u16)nSize;
48260 #ifdef SQLITE_DEBUG
48261 /* This variation on cellSizePtr() is used inside of assert() statements
48262 ** only. */
48263 static u16 cellSize(MemPage *pPage, int iCell){
48264 return cellSizePtr(pPage, findCell(pPage, iCell));
48266 #endif
48268 #ifndef SQLITE_OMIT_AUTOVACUUM
48270 ** If the cell pCell, part of page pPage contains a pointer
48271 ** to an overflow page, insert an entry into the pointer-map
48272 ** for the overflow page.
48274 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
48275 CellInfo info;
48276 if( *pRC ) return;
48277 assert( pCell!=0 );
48278 btreeParseCellPtr(pPage, pCell, &info);
48279 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
48280 if( info.iOverflow ){
48281 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
48282 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
48285 #endif
48289 ** Defragment the page given. All Cells are moved to the
48290 ** end of the page and all free space is collected into one
48291 ** big FreeBlk that occurs in between the header and cell
48292 ** pointer array and the cell content area.
48294 static int defragmentPage(MemPage *pPage){
48295 int i; /* Loop counter */
48296 int pc; /* Address of a i-th cell */
48297 int hdr; /* Offset to the page header */
48298 int size; /* Size of a cell */
48299 int usableSize; /* Number of usable bytes on a page */
48300 int cellOffset; /* Offset to the cell pointer array */
48301 int cbrk; /* Offset to the cell content area */
48302 int nCell; /* Number of cells on the page */
48303 unsigned char *data; /* The page data */
48304 unsigned char *temp; /* Temp area for cell content */
48305 int iCellFirst; /* First allowable cell index */
48306 int iCellLast; /* Last possible cell index */
48309 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48310 assert( pPage->pBt!=0 );
48311 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
48312 assert( pPage->nOverflow==0 );
48313 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48314 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
48315 data = pPage->aData;
48316 hdr = pPage->hdrOffset;
48317 cellOffset = pPage->cellOffset;
48318 nCell = pPage->nCell;
48319 assert( nCell==get2byte(&data[hdr+3]) );
48320 usableSize = pPage->pBt->usableSize;
48321 cbrk = get2byte(&data[hdr+5]);
48322 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
48323 cbrk = usableSize;
48324 iCellFirst = cellOffset + 2*nCell;
48325 iCellLast = usableSize - 4;
48326 for(i=0; i<nCell; i++){
48327 u8 *pAddr; /* The i-th cell pointer */
48328 pAddr = &data[cellOffset + i*2];
48329 pc = get2byte(pAddr);
48330 testcase( pc==iCellFirst );
48331 testcase( pc==iCellLast );
48332 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48333 /* These conditions have already been verified in btreeInitPage()
48334 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
48336 if( pc<iCellFirst || pc>iCellLast ){
48337 return SQLITE_CORRUPT_BKPT;
48339 #endif
48340 assert( pc>=iCellFirst && pc<=iCellLast );
48341 size = cellSizePtr(pPage, &temp[pc]);
48342 cbrk -= size;
48343 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48344 if( cbrk<iCellFirst ){
48345 return SQLITE_CORRUPT_BKPT;
48347 #else
48348 if( cbrk<iCellFirst || pc+size>usableSize ){
48349 return SQLITE_CORRUPT_BKPT;
48351 #endif
48352 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
48353 testcase( cbrk+size==usableSize );
48354 testcase( pc+size==usableSize );
48355 memcpy(&data[cbrk], &temp[pc], size);
48356 put2byte(pAddr, cbrk);
48358 assert( cbrk>=iCellFirst );
48359 put2byte(&data[hdr+5], cbrk);
48360 data[hdr+1] = 0;
48361 data[hdr+2] = 0;
48362 data[hdr+7] = 0;
48363 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
48364 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48365 if( cbrk-iCellFirst!=pPage->nFree ){
48366 return SQLITE_CORRUPT_BKPT;
48368 return SQLITE_OK;
48372 ** Allocate nByte bytes of space from within the B-Tree page passed
48373 ** as the first argument. Write into *pIdx the index into pPage->aData[]
48374 ** of the first byte of allocated space. Return either SQLITE_OK or
48375 ** an error code (usually SQLITE_CORRUPT).
48377 ** The caller guarantees that there is sufficient space to make the
48378 ** allocation. This routine might need to defragment in order to bring
48379 ** all the space together, however. This routine will avoid using
48380 ** the first two bytes past the cell pointer area since presumably this
48381 ** allocation is being made in order to insert a new cell, so we will
48382 ** also end up needing a new cell pointer.
48384 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
48385 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
48386 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
48387 int nFrag; /* Number of fragmented bytes on pPage */
48388 int top; /* First byte of cell content area */
48389 int gap; /* First byte of gap between cell pointers and cell content */
48390 int rc; /* Integer return code */
48391 int usableSize; /* Usable size of the page */
48393 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48394 assert( pPage->pBt );
48395 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48396 assert( nByte>=0 ); /* Minimum cell size is 4 */
48397 assert( pPage->nFree>=nByte );
48398 assert( pPage->nOverflow==0 );
48399 usableSize = pPage->pBt->usableSize;
48400 assert( nByte < usableSize-8 );
48402 nFrag = data[hdr+7];
48403 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
48404 gap = pPage->cellOffset + 2*pPage->nCell;
48405 top = get2byteNotZero(&data[hdr+5]);
48406 if( gap>top ) return SQLITE_CORRUPT_BKPT;
48407 testcase( gap+2==top );
48408 testcase( gap+1==top );
48409 testcase( gap==top );
48411 if( nFrag>=60 ){
48412 /* Always defragment highly fragmented pages */
48413 rc = defragmentPage(pPage);
48414 if( rc ) return rc;
48415 top = get2byteNotZero(&data[hdr+5]);
48416 }else if( gap+2<=top ){
48417 /* Search the freelist looking for a free slot big enough to satisfy
48418 ** the request. The allocation is made from the first free slot in
48419 ** the list that is large enough to accomadate it.
48421 int pc, addr;
48422 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
48423 int size; /* Size of the free slot */
48424 if( pc>usableSize-4 || pc<addr+4 ){
48425 return SQLITE_CORRUPT_BKPT;
48427 size = get2byte(&data[pc+2]);
48428 if( size>=nByte ){
48429 int x = size - nByte;
48430 testcase( x==4 );
48431 testcase( x==3 );
48432 if( x<4 ){
48433 /* Remove the slot from the free-list. Update the number of
48434 ** fragmented bytes within the page. */
48435 memcpy(&data[addr], &data[pc], 2);
48436 data[hdr+7] = (u8)(nFrag + x);
48437 }else if( size+pc > usableSize ){
48438 return SQLITE_CORRUPT_BKPT;
48439 }else{
48440 /* The slot remains on the free-list. Reduce its size to account
48441 ** for the portion used by the new allocation. */
48442 put2byte(&data[pc+2], x);
48444 *pIdx = pc + x;
48445 return SQLITE_OK;
48450 /* Check to make sure there is enough space in the gap to satisfy
48451 ** the allocation. If not, defragment.
48453 testcase( gap+2+nByte==top );
48454 if( gap+2+nByte>top ){
48455 rc = defragmentPage(pPage);
48456 if( rc ) return rc;
48457 top = get2byteNotZero(&data[hdr+5]);
48458 assert( gap+nByte<=top );
48462 /* Allocate memory from the gap in between the cell pointer array
48463 ** and the cell content area. The btreeInitPage() call has already
48464 ** validated the freelist. Given that the freelist is valid, there
48465 ** is no way that the allocation can extend off the end of the page.
48466 ** The assert() below verifies the previous sentence.
48468 top -= nByte;
48469 put2byte(&data[hdr+5], top);
48470 assert( top+nByte <= (int)pPage->pBt->usableSize );
48471 *pIdx = top;
48472 return SQLITE_OK;
48476 ** Return a section of the pPage->aData to the freelist.
48477 ** The first byte of the new free block is pPage->aDisk[start]
48478 ** and the size of the block is "size" bytes.
48480 ** Most of the effort here is involved in coalesing adjacent
48481 ** free blocks into a single big free block.
48483 static int freeSpace(MemPage *pPage, int start, int size){
48484 int addr, pbegin, hdr;
48485 int iLast; /* Largest possible freeblock offset */
48486 unsigned char *data = pPage->aData;
48488 assert( pPage->pBt!=0 );
48489 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48490 assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
48491 assert( (start + size) <= (int)pPage->pBt->usableSize );
48492 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48493 assert( size>=0 ); /* Minimum cell size is 4 */
48495 if( pPage->pBt->secureDelete ){
48496 /* Overwrite deleted information with zeros when the secure_delete
48497 ** option is enabled */
48498 memset(&data[start], 0, size);
48501 /* Add the space back into the linked list of freeblocks. Note that
48502 ** even though the freeblock list was checked by btreeInitPage(),
48503 ** btreeInitPage() did not detect overlapping cells or
48504 ** freeblocks that overlapped cells. Nor does it detect when the
48505 ** cell content area exceeds the value in the page header. If these
48506 ** situations arise, then subsequent insert operations might corrupt
48507 ** the freelist. So we do need to check for corruption while scanning
48508 ** the freelist.
48510 hdr = pPage->hdrOffset;
48511 addr = hdr + 1;
48512 iLast = pPage->pBt->usableSize - 4;
48513 assert( start<=iLast );
48514 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
48515 if( pbegin<addr+4 ){
48516 return SQLITE_CORRUPT_BKPT;
48518 addr = pbegin;
48520 if( pbegin>iLast ){
48521 return SQLITE_CORRUPT_BKPT;
48523 assert( pbegin>addr || pbegin==0 );
48524 put2byte(&data[addr], start);
48525 put2byte(&data[start], pbegin);
48526 put2byte(&data[start+2], size);
48527 pPage->nFree = pPage->nFree + (u16)size;
48529 /* Coalesce adjacent free blocks */
48530 addr = hdr + 1;
48531 while( (pbegin = get2byte(&data[addr]))>0 ){
48532 int pnext, psize, x;
48533 assert( pbegin>addr );
48534 assert( pbegin <= (int)pPage->pBt->usableSize-4 );
48535 pnext = get2byte(&data[pbegin]);
48536 psize = get2byte(&data[pbegin+2]);
48537 if( pbegin + psize + 3 >= pnext && pnext>0 ){
48538 int frag = pnext - (pbegin+psize);
48539 if( (frag<0) || (frag>(int)data[hdr+7]) ){
48540 return SQLITE_CORRUPT_BKPT;
48542 data[hdr+7] -= (u8)frag;
48543 x = get2byte(&data[pnext]);
48544 put2byte(&data[pbegin], x);
48545 x = pnext + get2byte(&data[pnext+2]) - pbegin;
48546 put2byte(&data[pbegin+2], x);
48547 }else{
48548 addr = pbegin;
48552 /* If the cell content area begins with a freeblock, remove it. */
48553 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
48554 int top;
48555 pbegin = get2byte(&data[hdr+1]);
48556 memcpy(&data[hdr+1], &data[pbegin], 2);
48557 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
48558 put2byte(&data[hdr+5], top);
48560 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48561 return SQLITE_OK;
48565 ** Decode the flags byte (the first byte of the header) for a page
48566 ** and initialize fields of the MemPage structure accordingly.
48568 ** Only the following combinations are supported. Anything different
48569 ** indicates a corrupt database files:
48571 ** PTF_ZERODATA
48572 ** PTF_ZERODATA | PTF_LEAF
48573 ** PTF_LEAFDATA | PTF_INTKEY
48574 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
48576 static int decodeFlags(MemPage *pPage, int flagByte){
48577 BtShared *pBt; /* A copy of pPage->pBt */
48579 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
48580 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48581 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
48582 flagByte &= ~PTF_LEAF;
48583 pPage->childPtrSize = 4-4*pPage->leaf;
48584 pBt = pPage->pBt;
48585 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
48586 pPage->intKey = 1;
48587 pPage->hasData = pPage->leaf;
48588 pPage->maxLocal = pBt->maxLeaf;
48589 pPage->minLocal = pBt->minLeaf;
48590 }else if( flagByte==PTF_ZERODATA ){
48591 pPage->intKey = 0;
48592 pPage->hasData = 0;
48593 pPage->maxLocal = pBt->maxLocal;
48594 pPage->minLocal = pBt->minLocal;
48595 }else{
48596 return SQLITE_CORRUPT_BKPT;
48598 return SQLITE_OK;
48602 ** Initialize the auxiliary information for a disk block.
48604 ** Return SQLITE_OK on success. If we see that the page does
48605 ** not contain a well-formed database page, then return
48606 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
48607 ** guarantee that the page is well-formed. It only shows that
48608 ** we failed to detect any corruption.
48610 static int btreeInitPage(MemPage *pPage){
48612 assert( pPage->pBt!=0 );
48613 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48614 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
48615 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
48616 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
48618 if( !pPage->isInit ){
48619 u16 pc; /* Address of a freeblock within pPage->aData[] */
48620 u8 hdr; /* Offset to beginning of page header */
48621 u8 *data; /* Equal to pPage->aData */
48622 BtShared *pBt; /* The main btree structure */
48623 int usableSize; /* Amount of usable space on each page */
48624 u16 cellOffset; /* Offset from start of page to first cell pointer */
48625 int nFree; /* Number of unused bytes on the page */
48626 int top; /* First byte of the cell content area */
48627 int iCellFirst; /* First allowable cell or freeblock offset */
48628 int iCellLast; /* Last possible cell or freeblock offset */
48630 pBt = pPage->pBt;
48632 hdr = pPage->hdrOffset;
48633 data = pPage->aData;
48634 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
48635 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
48636 pPage->maskPage = (u16)(pBt->pageSize - 1);
48637 pPage->nOverflow = 0;
48638 usableSize = pBt->usableSize;
48639 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
48640 top = get2byteNotZero(&data[hdr+5]);
48641 pPage->nCell = get2byte(&data[hdr+3]);
48642 if( pPage->nCell>MX_CELL(pBt) ){
48643 /* To many cells for a single page. The page must be corrupt */
48644 return SQLITE_CORRUPT_BKPT;
48646 testcase( pPage->nCell==MX_CELL(pBt) );
48648 /* A malformed database page might cause us to read past the end
48649 ** of page when parsing a cell.
48651 ** The following block of code checks early to see if a cell extends
48652 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
48653 ** returned if it does.
48655 iCellFirst = cellOffset + 2*pPage->nCell;
48656 iCellLast = usableSize - 4;
48657 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48659 int i; /* Index into the cell pointer array */
48660 int sz; /* Size of a cell */
48662 if( !pPage->leaf ) iCellLast--;
48663 for(i=0; i<pPage->nCell; i++){
48664 pc = get2byte(&data[cellOffset+i*2]);
48665 testcase( pc==iCellFirst );
48666 testcase( pc==iCellLast );
48667 if( pc<iCellFirst || pc>iCellLast ){
48668 return SQLITE_CORRUPT_BKPT;
48670 sz = cellSizePtr(pPage, &data[pc]);
48671 testcase( pc+sz==usableSize );
48672 if( pc+sz>usableSize ){
48673 return SQLITE_CORRUPT_BKPT;
48676 if( !pPage->leaf ) iCellLast++;
48678 #endif
48680 /* Compute the total free space on the page */
48681 pc = get2byte(&data[hdr+1]);
48682 nFree = data[hdr+7] + top;
48683 while( pc>0 ){
48684 u16 next, size;
48685 if( pc<iCellFirst || pc>iCellLast ){
48686 /* Start of free block is off the page */
48687 return SQLITE_CORRUPT_BKPT;
48689 next = get2byte(&data[pc]);
48690 size = get2byte(&data[pc+2]);
48691 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
48692 /* Free blocks must be in ascending order. And the last byte of
48693 ** the free-block must lie on the database page. */
48694 return SQLITE_CORRUPT_BKPT;
48696 nFree = nFree + size;
48697 pc = next;
48700 /* At this point, nFree contains the sum of the offset to the start
48701 ** of the cell-content area plus the number of free bytes within
48702 ** the cell-content area. If this is greater than the usable-size
48703 ** of the page, then the page must be corrupted. This check also
48704 ** serves to verify that the offset to the start of the cell-content
48705 ** area, according to the page header, lies within the page.
48707 if( nFree>usableSize ){
48708 return SQLITE_CORRUPT_BKPT;
48710 pPage->nFree = (u16)(nFree - iCellFirst);
48711 pPage->isInit = 1;
48713 return SQLITE_OK;
48717 ** Set up a raw page so that it looks like a database page holding
48718 ** no entries.
48720 static void zeroPage(MemPage *pPage, int flags){
48721 unsigned char *data = pPage->aData;
48722 BtShared *pBt = pPage->pBt;
48723 u8 hdr = pPage->hdrOffset;
48724 u16 first;
48726 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
48727 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
48728 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
48729 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48730 assert( sqlite3_mutex_held(pBt->mutex) );
48731 if( pBt->secureDelete ){
48732 memset(&data[hdr], 0, pBt->usableSize - hdr);
48734 data[hdr] = (char)flags;
48735 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
48736 memset(&data[hdr+1], 0, 4);
48737 data[hdr+7] = 0;
48738 put2byte(&data[hdr+5], pBt->usableSize);
48739 pPage->nFree = (u16)(pBt->usableSize - first);
48740 decodeFlags(pPage, flags);
48741 pPage->hdrOffset = hdr;
48742 pPage->cellOffset = first;
48743 pPage->nOverflow = 0;
48744 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
48745 pPage->maskPage = (u16)(pBt->pageSize - 1);
48746 pPage->nCell = 0;
48747 pPage->isInit = 1;
48752 ** Convert a DbPage obtained from the pager into a MemPage used by
48753 ** the btree layer.
48755 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
48756 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
48757 pPage->aData = sqlite3PagerGetData(pDbPage);
48758 pPage->pDbPage = pDbPage;
48759 pPage->pBt = pBt;
48760 pPage->pgno = pgno;
48761 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
48762 return pPage;
48766 ** Get a page from the pager. Initialize the MemPage.pBt and
48767 ** MemPage.aData elements if needed.
48769 ** If the noContent flag is set, it means that we do not care about
48770 ** the content of the page at this time. So do not go to the disk
48771 ** to fetch the content. Just fill in the content with zeros for now.
48772 ** If in the future we call sqlite3PagerWrite() on this page, that
48773 ** means we have started to be concerned about content and the disk
48774 ** read should occur at that point.
48776 static int btreeGetPage(
48777 BtShared *pBt, /* The btree */
48778 Pgno pgno, /* Number of the page to fetch */
48779 MemPage **ppPage, /* Return the page in this parameter */
48780 int noContent /* Do not load page content if true */
48782 int rc;
48783 DbPage *pDbPage;
48785 assert( sqlite3_mutex_held(pBt->mutex) );
48786 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
48787 if( rc ) return rc;
48788 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
48789 return SQLITE_OK;
48793 ** Retrieve a page from the pager cache. If the requested page is not
48794 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
48795 ** MemPage.aData elements if needed.
48797 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
48798 DbPage *pDbPage;
48799 assert( sqlite3_mutex_held(pBt->mutex) );
48800 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
48801 if( pDbPage ){
48802 return btreePageFromDbPage(pDbPage, pgno, pBt);
48804 return 0;
48808 ** Return the size of the database file in pages. If there is any kind of
48809 ** error, return ((unsigned int)-1).
48811 static Pgno btreePagecount(BtShared *pBt){
48812 return pBt->nPage;
48814 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
48815 assert( sqlite3BtreeHoldsMutex(p) );
48816 assert( ((p->pBt->nPage)&0x8000000)==0 );
48817 return (int)btreePagecount(p->pBt);
48821 ** Get a page from the pager and initialize it. This routine is just a
48822 ** convenience wrapper around separate calls to btreeGetPage() and
48823 ** btreeInitPage().
48825 ** If an error occurs, then the value *ppPage is set to is undefined. It
48826 ** may remain unchanged, or it may be set to an invalid value.
48828 static int getAndInitPage(
48829 BtShared *pBt, /* The database file */
48830 Pgno pgno, /* Number of the page to get */
48831 MemPage **ppPage /* Write the page pointer here */
48833 int rc;
48834 assert( sqlite3_mutex_held(pBt->mutex) );
48836 if( pgno>btreePagecount(pBt) ){
48837 rc = SQLITE_CORRUPT_BKPT;
48838 }else{
48839 rc = btreeGetPage(pBt, pgno, ppPage, 0);
48840 if( rc==SQLITE_OK ){
48841 rc = btreeInitPage(*ppPage);
48842 if( rc!=SQLITE_OK ){
48843 releasePage(*ppPage);
48848 testcase( pgno==0 );
48849 assert( pgno!=0 || rc==SQLITE_CORRUPT );
48850 return rc;
48854 ** Release a MemPage. This should be called once for each prior
48855 ** call to btreeGetPage.
48857 static void releasePage(MemPage *pPage){
48858 if( pPage ){
48859 assert( pPage->aData );
48860 assert( pPage->pBt );
48861 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
48862 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
48863 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48864 sqlite3PagerUnref(pPage->pDbPage);
48869 ** During a rollback, when the pager reloads information into the cache
48870 ** so that the cache is restored to its original state at the start of
48871 ** the transaction, for each page restored this routine is called.
48873 ** This routine needs to reset the extra data section at the end of the
48874 ** page to agree with the restored data.
48876 static void pageReinit(DbPage *pData){
48877 MemPage *pPage;
48878 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
48879 assert( sqlite3PagerPageRefcount(pData)>0 );
48880 if( pPage->isInit ){
48881 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48882 pPage->isInit = 0;
48883 if( sqlite3PagerPageRefcount(pData)>1 ){
48884 /* pPage might not be a btree page; it might be an overflow page
48885 ** or ptrmap page or a free page. In those cases, the following
48886 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
48887 ** But no harm is done by this. And it is very important that
48888 ** btreeInitPage() be called on every btree page so we make
48889 ** the call for every page that comes in for re-initing. */
48890 btreeInitPage(pPage);
48896 ** Invoke the busy handler for a btree.
48898 static int btreeInvokeBusyHandler(void *pArg){
48899 BtShared *pBt = (BtShared*)pArg;
48900 assert( pBt->db );
48901 assert( sqlite3_mutex_held(pBt->db->mutex) );
48902 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
48906 ** Open a database file.
48908 ** zFilename is the name of the database file. If zFilename is NULL
48909 ** then an ephemeral database is created. The ephemeral database might
48910 ** be exclusively in memory, or it might use a disk-based memory cache.
48911 ** Either way, the ephemeral database will be automatically deleted
48912 ** when sqlite3BtreeClose() is called.
48914 ** If zFilename is ":memory:" then an in-memory database is created
48915 ** that is automatically destroyed when it is closed.
48917 ** The "flags" parameter is a bitmask that might contain bits
48918 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK
48919 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
48920 ** These flags are passed through into sqlite3PagerOpen() and must
48921 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
48923 ** If the database is already opened in the same database connection
48924 ** and we are in shared cache mode, then the open will fail with an
48925 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
48926 ** objects in the same database connection since doing so will lead
48927 ** to problems with locking.
48929 SQLITE_PRIVATE int sqlite3BtreeOpen(
48930 const char *zFilename, /* Name of the file containing the BTree database */
48931 sqlite3 *db, /* Associated database handle */
48932 Btree **ppBtree, /* Pointer to new Btree object written here */
48933 int flags, /* Options */
48934 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
48936 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
48937 BtShared *pBt = 0; /* Shared part of btree structure */
48938 Btree *p; /* Handle to return */
48939 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
48940 int rc = SQLITE_OK; /* Result code from this function */
48941 u8 nReserve; /* Byte of unused space on each page */
48942 unsigned char zDbHeader[100]; /* Database header content */
48944 /* True if opening an ephemeral, temporary database */
48945 const int isTempDb = zFilename==0 || zFilename[0]==0;
48947 /* Set the variable isMemdb to true for an in-memory database, or
48948 ** false for a file-based database.
48950 #ifdef SQLITE_OMIT_MEMORYDB
48951 const int isMemdb = 0;
48952 #else
48953 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
48954 || (isTempDb && sqlite3TempInMemory(db));
48955 #endif
48957 assert( db!=0 );
48958 assert( sqlite3_mutex_held(db->mutex) );
48959 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
48961 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
48962 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
48964 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
48965 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
48967 if( db->flags & SQLITE_NoReadlock ){
48968 flags |= BTREE_NO_READLOCK;
48970 if( isMemdb ){
48971 flags |= BTREE_MEMORY;
48973 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
48974 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
48976 pVfs = db->pVfs;
48977 p = sqlite3MallocZero(sizeof(Btree));
48978 if( !p ){
48979 return SQLITE_NOMEM;
48981 p->inTrans = TRANS_NONE;
48982 p->db = db;
48983 #ifndef SQLITE_OMIT_SHARED_CACHE
48984 p->lock.pBtree = p;
48985 p->lock.iTable = 1;
48986 #endif
48988 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
48990 ** If this Btree is a candidate for shared cache, try to find an
48991 ** existing BtShared object that we can share with
48993 if( isMemdb==0 && isTempDb==0 ){
48994 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
48995 int nFullPathname = pVfs->mxPathname+1;
48996 char *zFullPathname = sqlite3Malloc(nFullPathname);
48997 sqlite3_mutex *mutexShared;
48998 p->sharable = 1;
48999 if( !zFullPathname ){
49000 sqlite3_free(p);
49001 return SQLITE_NOMEM;
49003 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
49004 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
49005 sqlite3_mutex_enter(mutexOpen);
49006 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49007 sqlite3_mutex_enter(mutexShared);
49008 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
49009 assert( pBt->nRef>0 );
49010 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
49011 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
49012 int iDb;
49013 for(iDb=db->nDb-1; iDb>=0; iDb--){
49014 Btree *pExisting = db->aDb[iDb].pBt;
49015 if( pExisting && pExisting->pBt==pBt ){
49016 sqlite3_mutex_leave(mutexShared);
49017 sqlite3_mutex_leave(mutexOpen);
49018 sqlite3_free(zFullPathname);
49019 sqlite3_free(p);
49020 return SQLITE_CONSTRAINT;
49023 p->pBt = pBt;
49024 pBt->nRef++;
49025 break;
49028 sqlite3_mutex_leave(mutexShared);
49029 sqlite3_free(zFullPathname);
49031 #ifdef SQLITE_DEBUG
49032 else{
49033 /* In debug mode, we mark all persistent databases as sharable
49034 ** even when they are not. This exercises the locking code and
49035 ** gives more opportunity for asserts(sqlite3_mutex_held())
49036 ** statements to find locking problems.
49038 p->sharable = 1;
49040 #endif
49042 #endif
49043 if( pBt==0 ){
49045 ** The following asserts make sure that structures used by the btree are
49046 ** the right size. This is to guard against size changes that result
49047 ** when compiling on a different architecture.
49049 assert( sizeof(i64)==8 || sizeof(i64)==4 );
49050 assert( sizeof(u64)==8 || sizeof(u64)==4 );
49051 assert( sizeof(u32)==4 );
49052 assert( sizeof(u16)==2 );
49053 assert( sizeof(Pgno)==4 );
49055 pBt = sqlite3MallocZero( sizeof(*pBt) );
49056 if( pBt==0 ){
49057 rc = SQLITE_NOMEM;
49058 goto btree_open_out;
49060 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
49061 EXTRA_SIZE, flags, vfsFlags, pageReinit);
49062 if( rc==SQLITE_OK ){
49063 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
49065 if( rc!=SQLITE_OK ){
49066 goto btree_open_out;
49068 pBt->openFlags = (u8)flags;
49069 pBt->db = db;
49070 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
49071 p->pBt = pBt;
49073 pBt->pCursor = 0;
49074 pBt->pPage1 = 0;
49075 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
49076 #ifdef SQLITE_SECURE_DELETE
49077 pBt->secureDelete = 1;
49078 #endif
49079 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
49080 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
49081 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
49082 pBt->pageSize = 0;
49083 #ifndef SQLITE_OMIT_AUTOVACUUM
49084 /* If the magic name ":memory:" will create an in-memory database, then
49085 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
49086 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
49087 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
49088 ** regular file-name. In this case the auto-vacuum applies as per normal.
49090 if( zFilename && !isMemdb ){
49091 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
49092 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
49094 #endif
49095 nReserve = 0;
49096 }else{
49097 nReserve = zDbHeader[20];
49098 pBt->pageSizeFixed = 1;
49099 #ifndef SQLITE_OMIT_AUTOVACUUM
49100 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
49101 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
49102 #endif
49104 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
49105 if( rc ) goto btree_open_out;
49106 pBt->usableSize = pBt->pageSize - nReserve;
49107 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
49109 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49110 /* Add the new BtShared object to the linked list sharable BtShareds.
49112 if( p->sharable ){
49113 sqlite3_mutex *mutexShared;
49114 pBt->nRef = 1;
49115 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49116 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
49117 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
49118 if( pBt->mutex==0 ){
49119 rc = SQLITE_NOMEM;
49120 db->mallocFailed = 0;
49121 goto btree_open_out;
49124 sqlite3_mutex_enter(mutexShared);
49125 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
49126 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
49127 sqlite3_mutex_leave(mutexShared);
49129 #endif
49132 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49133 /* If the new Btree uses a sharable pBtShared, then link the new
49134 ** Btree into the list of all sharable Btrees for the same connection.
49135 ** The list is kept in ascending order by pBt address.
49137 if( p->sharable ){
49138 int i;
49139 Btree *pSib;
49140 for(i=0; i<db->nDb; i++){
49141 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
49142 while( pSib->pPrev ){ pSib = pSib->pPrev; }
49143 if( p->pBt<pSib->pBt ){
49144 p->pNext = pSib;
49145 p->pPrev = 0;
49146 pSib->pPrev = p;
49147 }else{
49148 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
49149 pSib = pSib->pNext;
49151 p->pNext = pSib->pNext;
49152 p->pPrev = pSib;
49153 if( p->pNext ){
49154 p->pNext->pPrev = p;
49156 pSib->pNext = p;
49158 break;
49162 #endif
49163 *ppBtree = p;
49165 btree_open_out:
49166 if( rc!=SQLITE_OK ){
49167 if( pBt && pBt->pPager ){
49168 sqlite3PagerClose(pBt->pPager);
49170 sqlite3_free(pBt);
49171 sqlite3_free(p);
49172 *ppBtree = 0;
49173 }else{
49174 /* If the B-Tree was successfully opened, set the pager-cache size to the
49175 ** default value. Except, when opening on an existing shared pager-cache,
49176 ** do not change the pager-cache size.
49178 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
49179 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
49182 if( mutexOpen ){
49183 assert( sqlite3_mutex_held(mutexOpen) );
49184 sqlite3_mutex_leave(mutexOpen);
49186 return rc;
49190 ** Decrement the BtShared.nRef counter. When it reaches zero,
49191 ** remove the BtShared structure from the sharing list. Return
49192 ** true if the BtShared.nRef counter reaches zero and return
49193 ** false if it is still positive.
49195 static int removeFromSharingList(BtShared *pBt){
49196 #ifndef SQLITE_OMIT_SHARED_CACHE
49197 sqlite3_mutex *pMaster;
49198 BtShared *pList;
49199 int removed = 0;
49201 assert( sqlite3_mutex_notheld(pBt->mutex) );
49202 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49203 sqlite3_mutex_enter(pMaster);
49204 pBt->nRef--;
49205 if( pBt->nRef<=0 ){
49206 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
49207 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
49208 }else{
49209 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
49210 while( ALWAYS(pList) && pList->pNext!=pBt ){
49211 pList=pList->pNext;
49213 if( ALWAYS(pList) ){
49214 pList->pNext = pBt->pNext;
49217 if( SQLITE_THREADSAFE ){
49218 sqlite3_mutex_free(pBt->mutex);
49220 removed = 1;
49222 sqlite3_mutex_leave(pMaster);
49223 return removed;
49224 #else
49225 return 1;
49226 #endif
49230 ** Make sure pBt->pTmpSpace points to an allocation of
49231 ** MX_CELL_SIZE(pBt) bytes.
49233 static void allocateTempSpace(BtShared *pBt){
49234 if( !pBt->pTmpSpace ){
49235 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
49240 ** Free the pBt->pTmpSpace allocation
49242 static void freeTempSpace(BtShared *pBt){
49243 sqlite3PageFree( pBt->pTmpSpace);
49244 pBt->pTmpSpace = 0;
49248 ** Close an open database and invalidate all cursors.
49250 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
49251 BtShared *pBt = p->pBt;
49252 BtCursor *pCur;
49254 /* Close all cursors opened via this handle. */
49255 assert( sqlite3_mutex_held(p->db->mutex) );
49256 sqlite3BtreeEnter(p);
49257 pCur = pBt->pCursor;
49258 while( pCur ){
49259 BtCursor *pTmp = pCur;
49260 pCur = pCur->pNext;
49261 if( pTmp->pBtree==p ){
49262 sqlite3BtreeCloseCursor(pTmp);
49266 /* Rollback any active transaction and free the handle structure.
49267 ** The call to sqlite3BtreeRollback() drops any table-locks held by
49268 ** this handle.
49270 sqlite3BtreeRollback(p);
49271 sqlite3BtreeLeave(p);
49273 /* If there are still other outstanding references to the shared-btree
49274 ** structure, return now. The remainder of this procedure cleans
49275 ** up the shared-btree.
49277 assert( p->wantToLock==0 && p->locked==0 );
49278 if( !p->sharable || removeFromSharingList(pBt) ){
49279 /* The pBt is no longer on the sharing list, so we can access
49280 ** it without having to hold the mutex.
49282 ** Clean out and delete the BtShared object.
49284 assert( !pBt->pCursor );
49285 sqlite3PagerClose(pBt->pPager);
49286 if( pBt->xFreeSchema && pBt->pSchema ){
49287 pBt->xFreeSchema(pBt->pSchema);
49289 sqlite3DbFree(0, pBt->pSchema);
49290 freeTempSpace(pBt);
49291 sqlite3_free(pBt);
49294 #ifndef SQLITE_OMIT_SHARED_CACHE
49295 assert( p->wantToLock==0 );
49296 assert( p->locked==0 );
49297 if( p->pPrev ) p->pPrev->pNext = p->pNext;
49298 if( p->pNext ) p->pNext->pPrev = p->pPrev;
49299 #endif
49301 sqlite3_free(p);
49302 return SQLITE_OK;
49306 ** Change the limit on the number of pages allowed in the cache.
49308 ** The maximum number of cache pages is set to the absolute
49309 ** value of mxPage. If mxPage is negative, the pager will
49310 ** operate asynchronously - it will not stop to do fsync()s
49311 ** to insure data is written to the disk surface before
49312 ** continuing. Transactions still work if synchronous is off,
49313 ** and the database cannot be corrupted if this program
49314 ** crashes. But if the operating system crashes or there is
49315 ** an abrupt power failure when synchronous is off, the database
49316 ** could be left in an inconsistent and unrecoverable state.
49317 ** Synchronous is on by default so database corruption is not
49318 ** normally a worry.
49320 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
49321 BtShared *pBt = p->pBt;
49322 assert( sqlite3_mutex_held(p->db->mutex) );
49323 sqlite3BtreeEnter(p);
49324 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
49325 sqlite3BtreeLeave(p);
49326 return SQLITE_OK;
49330 ** Change the way data is synced to disk in order to increase or decrease
49331 ** how well the database resists damage due to OS crashes and power
49332 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
49333 ** there is a high probability of damage) Level 2 is the default. There
49334 ** is a very low but non-zero probability of damage. Level 3 reduces the
49335 ** probability of damage to near zero but with a write performance reduction.
49337 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
49338 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
49339 Btree *p, /* The btree to set the safety level on */
49340 int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
49341 int fullSync, /* PRAGMA fullfsync. */
49342 int ckptFullSync /* PRAGMA checkpoint_fullfync */
49344 BtShared *pBt = p->pBt;
49345 assert( sqlite3_mutex_held(p->db->mutex) );
49346 assert( level>=1 && level<=3 );
49347 sqlite3BtreeEnter(p);
49348 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
49349 sqlite3BtreeLeave(p);
49350 return SQLITE_OK;
49352 #endif
49355 ** Return TRUE if the given btree is set to safety level 1. In other
49356 ** words, return TRUE if no sync() occurs on the disk files.
49358 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
49359 BtShared *pBt = p->pBt;
49360 int rc;
49361 assert( sqlite3_mutex_held(p->db->mutex) );
49362 sqlite3BtreeEnter(p);
49363 assert( pBt && pBt->pPager );
49364 rc = sqlite3PagerNosync(pBt->pPager);
49365 sqlite3BtreeLeave(p);
49366 return rc;
49370 ** Change the default pages size and the number of reserved bytes per page.
49371 ** Or, if the page size has already been fixed, return SQLITE_READONLY
49372 ** without changing anything.
49374 ** The page size must be a power of 2 between 512 and 65536. If the page
49375 ** size supplied does not meet this constraint then the page size is not
49376 ** changed.
49378 ** Page sizes are constrained to be a power of two so that the region
49379 ** of the database file used for locking (beginning at PENDING_BYTE,
49380 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
49381 ** at the beginning of a page.
49383 ** If parameter nReserve is less than zero, then the number of reserved
49384 ** bytes per page is left unchanged.
49386 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
49387 ** and autovacuum mode can no longer be changed.
49389 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
49390 int rc = SQLITE_OK;
49391 BtShared *pBt = p->pBt;
49392 assert( nReserve>=-1 && nReserve<=255 );
49393 sqlite3BtreeEnter(p);
49394 if( pBt->pageSizeFixed ){
49395 sqlite3BtreeLeave(p);
49396 return SQLITE_READONLY;
49398 if( nReserve<0 ){
49399 nReserve = pBt->pageSize - pBt->usableSize;
49401 assert( nReserve>=0 && nReserve<=255 );
49402 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
49403 ((pageSize-1)&pageSize)==0 ){
49404 assert( (pageSize & 7)==0 );
49405 assert( !pBt->pPage1 && !pBt->pCursor );
49406 pBt->pageSize = (u32)pageSize;
49407 freeTempSpace(pBt);
49409 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
49410 pBt->usableSize = pBt->pageSize - (u16)nReserve;
49411 if( iFix ) pBt->pageSizeFixed = 1;
49412 sqlite3BtreeLeave(p);
49413 return rc;
49417 ** Return the currently defined page size
49419 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
49420 return p->pBt->pageSize;
49423 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
49425 ** Return the number of bytes of space at the end of every page that
49426 ** are intentually left unused. This is the "reserved" space that is
49427 ** sometimes used by extensions.
49429 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
49430 int n;
49431 sqlite3BtreeEnter(p);
49432 n = p->pBt->pageSize - p->pBt->usableSize;
49433 sqlite3BtreeLeave(p);
49434 return n;
49438 ** Set the maximum page count for a database if mxPage is positive.
49439 ** No changes are made if mxPage is 0 or negative.
49440 ** Regardless of the value of mxPage, return the maximum page count.
49442 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
49443 int n;
49444 sqlite3BtreeEnter(p);
49445 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
49446 sqlite3BtreeLeave(p);
49447 return n;
49451 ** Set the secureDelete flag if newFlag is 0 or 1. If newFlag is -1,
49452 ** then make no changes. Always return the value of the secureDelete
49453 ** setting after the change.
49455 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
49456 int b;
49457 if( p==0 ) return 0;
49458 sqlite3BtreeEnter(p);
49459 if( newFlag>=0 ){
49460 p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
49462 b = p->pBt->secureDelete;
49463 sqlite3BtreeLeave(p);
49464 return b;
49466 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
49469 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
49470 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
49471 ** is disabled. The default value for the auto-vacuum property is
49472 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
49474 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
49475 #ifdef SQLITE_OMIT_AUTOVACUUM
49476 return SQLITE_READONLY;
49477 #else
49478 BtShared *pBt = p->pBt;
49479 int rc = SQLITE_OK;
49480 u8 av = (u8)autoVacuum;
49482 sqlite3BtreeEnter(p);
49483 if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
49484 rc = SQLITE_READONLY;
49485 }else{
49486 pBt->autoVacuum = av ?1:0;
49487 pBt->incrVacuum = av==2 ?1:0;
49489 sqlite3BtreeLeave(p);
49490 return rc;
49491 #endif
49495 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
49496 ** enabled 1 is returned. Otherwise 0.
49498 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
49499 #ifdef SQLITE_OMIT_AUTOVACUUM
49500 return BTREE_AUTOVACUUM_NONE;
49501 #else
49502 int rc;
49503 sqlite3BtreeEnter(p);
49504 rc = (
49505 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
49506 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
49507 BTREE_AUTOVACUUM_INCR
49509 sqlite3BtreeLeave(p);
49510 return rc;
49511 #endif
49516 ** Get a reference to pPage1 of the database file. This will
49517 ** also acquire a readlock on that file.
49519 ** SQLITE_OK is returned on success. If the file is not a
49520 ** well-formed database file, then SQLITE_CORRUPT is returned.
49521 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
49522 ** is returned if we run out of memory.
49524 static int lockBtree(BtShared *pBt){
49525 int rc; /* Result code from subfunctions */
49526 MemPage *pPage1; /* Page 1 of the database file */
49527 int nPage; /* Number of pages in the database */
49528 int nPageFile = 0; /* Number of pages in the database file */
49529 int nPageHeader; /* Number of pages in the database according to hdr */
49531 assert( sqlite3_mutex_held(pBt->mutex) );
49532 assert( pBt->pPage1==0 );
49533 rc = sqlite3PagerSharedLock(pBt->pPager);
49534 if( rc!=SQLITE_OK ) return rc;
49535 rc = btreeGetPage(pBt, 1, &pPage1, 0);
49536 if( rc!=SQLITE_OK ) return rc;
49538 /* Do some checking to help insure the file we opened really is
49539 ** a valid database file.
49541 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
49542 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
49543 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
49544 nPage = nPageFile;
49546 if( nPage>0 ){
49547 u32 pageSize;
49548 u32 usableSize;
49549 u8 *page1 = pPage1->aData;
49550 rc = SQLITE_NOTADB;
49551 if( memcmp(page1, zMagicHeader, 16)!=0 ){
49552 goto page1_init_failed;
49555 #ifdef SQLITE_OMIT_WAL
49556 if( page1[18]>1 ){
49557 pBt->readOnly = 1;
49559 if( page1[19]>1 ){
49560 goto page1_init_failed;
49562 #else
49563 if( page1[18]>2 ){
49564 pBt->readOnly = 1;
49566 if( page1[19]>2 ){
49567 goto page1_init_failed;
49570 /* If the write version is set to 2, this database should be accessed
49571 ** in WAL mode. If the log is not already open, open it now. Then
49572 ** return SQLITE_OK and return without populating BtShared.pPage1.
49573 ** The caller detects this and calls this function again. This is
49574 ** required as the version of page 1 currently in the page1 buffer
49575 ** may not be the latest version - there may be a newer one in the log
49576 ** file.
49578 if( page1[19]==2 && pBt->doNotUseWAL==0 ){
49579 int isOpen = 0;
49580 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
49581 if( rc!=SQLITE_OK ){
49582 goto page1_init_failed;
49583 }else if( isOpen==0 ){
49584 releasePage(pPage1);
49585 return SQLITE_OK;
49587 rc = SQLITE_NOTADB;
49589 #endif
49591 /* The maximum embedded fraction must be exactly 25%. And the minimum
49592 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
49593 ** The original design allowed these amounts to vary, but as of
49594 ** version 3.6.0, we require them to be fixed.
49596 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
49597 goto page1_init_failed;
49599 pageSize = (page1[16]<<8) | (page1[17]<<16);
49600 if( ((pageSize-1)&pageSize)!=0
49601 || pageSize>SQLITE_MAX_PAGE_SIZE
49602 || pageSize<=256
49604 goto page1_init_failed;
49606 assert( (pageSize & 7)==0 );
49607 usableSize = pageSize - page1[20];
49608 if( (u32)pageSize!=pBt->pageSize ){
49609 /* After reading the first page of the database assuming a page size
49610 ** of BtShared.pageSize, we have discovered that the page-size is
49611 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
49612 ** zero and return SQLITE_OK. The caller will call this function
49613 ** again with the correct page-size.
49615 releasePage(pPage1);
49616 pBt->usableSize = usableSize;
49617 pBt->pageSize = pageSize;
49618 freeTempSpace(pBt);
49619 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
49620 pageSize-usableSize);
49621 return rc;
49623 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
49624 rc = SQLITE_CORRUPT_BKPT;
49625 goto page1_init_failed;
49627 if( usableSize<480 ){
49628 goto page1_init_failed;
49630 pBt->pageSize = pageSize;
49631 pBt->usableSize = usableSize;
49632 #ifndef SQLITE_OMIT_AUTOVACUUM
49633 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
49634 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
49635 #endif
49638 /* maxLocal is the maximum amount of payload to store locally for
49639 ** a cell. Make sure it is small enough so that at least minFanout
49640 ** cells can will fit on one page. We assume a 10-byte page header.
49641 ** Besides the payload, the cell must store:
49642 ** 2-byte pointer to the cell
49643 ** 4-byte child pointer
49644 ** 9-byte nKey value
49645 ** 4-byte nData value
49646 ** 4-byte overflow page pointer
49647 ** So a cell consists of a 2-byte pointer, a header which is as much as
49648 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
49649 ** page pointer.
49651 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
49652 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
49653 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
49654 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
49655 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
49656 pBt->pPage1 = pPage1;
49657 pBt->nPage = nPage;
49658 return SQLITE_OK;
49660 page1_init_failed:
49661 releasePage(pPage1);
49662 pBt->pPage1 = 0;
49663 return rc;
49667 ** If there are no outstanding cursors and we are not in the middle
49668 ** of a transaction but there is a read lock on the database, then
49669 ** this routine unrefs the first page of the database file which
49670 ** has the effect of releasing the read lock.
49672 ** If there is a transaction in progress, this routine is a no-op.
49674 static void unlockBtreeIfUnused(BtShared *pBt){
49675 assert( sqlite3_mutex_held(pBt->mutex) );
49676 assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
49677 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
49678 assert( pBt->pPage1->aData );
49679 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
49680 assert( pBt->pPage1->aData );
49681 releasePage(pBt->pPage1);
49682 pBt->pPage1 = 0;
49687 ** If pBt points to an empty file then convert that empty file
49688 ** into a new empty database by initializing the first page of
49689 ** the database.
49691 static int newDatabase(BtShared *pBt){
49692 MemPage *pP1;
49693 unsigned char *data;
49694 int rc;
49696 assert( sqlite3_mutex_held(pBt->mutex) );
49697 if( pBt->nPage>0 ){
49698 return SQLITE_OK;
49700 pP1 = pBt->pPage1;
49701 assert( pP1!=0 );
49702 data = pP1->aData;
49703 rc = sqlite3PagerWrite(pP1->pDbPage);
49704 if( rc ) return rc;
49705 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
49706 assert( sizeof(zMagicHeader)==16 );
49707 data[16] = (u8)((pBt->pageSize>>8)&0xff);
49708 data[17] = (u8)((pBt->pageSize>>16)&0xff);
49709 data[18] = 1;
49710 data[19] = 1;
49711 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
49712 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
49713 data[21] = 64;
49714 data[22] = 32;
49715 data[23] = 32;
49716 memset(&data[24], 0, 100-24);
49717 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
49718 pBt->pageSizeFixed = 1;
49719 #ifndef SQLITE_OMIT_AUTOVACUUM
49720 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
49721 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
49722 put4byte(&data[36 + 4*4], pBt->autoVacuum);
49723 put4byte(&data[36 + 7*4], pBt->incrVacuum);
49724 #endif
49725 pBt->nPage = 1;
49726 data[31] = 1;
49727 return SQLITE_OK;
49731 ** Attempt to start a new transaction. A write-transaction
49732 ** is started if the second argument is nonzero, otherwise a read-
49733 ** transaction. If the second argument is 2 or more and exclusive
49734 ** transaction is started, meaning that no other process is allowed
49735 ** to access the database. A preexisting transaction may not be
49736 ** upgraded to exclusive by calling this routine a second time - the
49737 ** exclusivity flag only works for a new transaction.
49739 ** A write-transaction must be started before attempting any
49740 ** changes to the database. None of the following routines
49741 ** will work unless a transaction is started first:
49743 ** sqlite3BtreeCreateTable()
49744 ** sqlite3BtreeCreateIndex()
49745 ** sqlite3BtreeClearTable()
49746 ** sqlite3BtreeDropTable()
49747 ** sqlite3BtreeInsert()
49748 ** sqlite3BtreeDelete()
49749 ** sqlite3BtreeUpdateMeta()
49751 ** If an initial attempt to acquire the lock fails because of lock contention
49752 ** and the database was previously unlocked, then invoke the busy handler
49753 ** if there is one. But if there was previously a read-lock, do not
49754 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
49755 ** returned when there is already a read-lock in order to avoid a deadlock.
49757 ** Suppose there are two processes A and B. A has a read lock and B has
49758 ** a reserved lock. B tries to promote to exclusive but is blocked because
49759 ** of A's read lock. A tries to promote to reserved but is blocked by B.
49760 ** One or the other of the two processes must give way or there can be
49761 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
49762 ** when A already has a read lock, we encourage A to give up and let B
49763 ** proceed.
49765 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
49766 sqlite3 *pBlock = 0;
49767 BtShared *pBt = p->pBt;
49768 int rc = SQLITE_OK;
49770 sqlite3BtreeEnter(p);
49771 btreeIntegrity(p);
49773 /* If the btree is already in a write-transaction, or it
49774 ** is already in a read-transaction and a read-transaction
49775 ** is requested, this is a no-op.
49777 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
49778 goto trans_begun;
49781 /* Write transactions are not possible on a read-only database */
49782 if( pBt->readOnly && wrflag ){
49783 rc = SQLITE_READONLY;
49784 goto trans_begun;
49787 #ifndef SQLITE_OMIT_SHARED_CACHE
49788 /* If another database handle has already opened a write transaction
49789 ** on this shared-btree structure and a second write transaction is
49790 ** requested, return SQLITE_LOCKED.
49792 if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
49793 pBlock = pBt->pWriter->db;
49794 }else if( wrflag>1 ){
49795 BtLock *pIter;
49796 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49797 if( pIter->pBtree!=p ){
49798 pBlock = pIter->pBtree->db;
49799 break;
49803 if( pBlock ){
49804 sqlite3ConnectionBlocked(p->db, pBlock);
49805 rc = SQLITE_LOCKED_SHAREDCACHE;
49806 goto trans_begun;
49808 #endif
49810 /* Any read-only or read-write transaction implies a read-lock on
49811 ** page 1. So if some other shared-cache client already has a write-lock
49812 ** on page 1, the transaction cannot be opened. */
49813 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
49814 if( SQLITE_OK!=rc ) goto trans_begun;
49816 pBt->initiallyEmpty = (u8)(pBt->nPage==0);
49817 do {
49818 /* Call lockBtree() until either pBt->pPage1 is populated or
49819 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
49820 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
49821 ** reading page 1 it discovers that the page-size of the database
49822 ** file is not pBt->pageSize. In this case lockBtree() will update
49823 ** pBt->pageSize to the page-size of the file on disk.
49825 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
49827 if( rc==SQLITE_OK && wrflag ){
49828 if( pBt->readOnly ){
49829 rc = SQLITE_READONLY;
49830 }else{
49831 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
49832 if( rc==SQLITE_OK ){
49833 rc = newDatabase(pBt);
49838 if( rc!=SQLITE_OK ){
49839 unlockBtreeIfUnused(pBt);
49841 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
49842 btreeInvokeBusyHandler(pBt) );
49844 if( rc==SQLITE_OK ){
49845 if( p->inTrans==TRANS_NONE ){
49846 pBt->nTransaction++;
49847 #ifndef SQLITE_OMIT_SHARED_CACHE
49848 if( p->sharable ){
49849 assert( p->lock.pBtree==p && p->lock.iTable==1 );
49850 p->lock.eLock = READ_LOCK;
49851 p->lock.pNext = pBt->pLock;
49852 pBt->pLock = &p->lock;
49854 #endif
49856 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
49857 if( p->inTrans>pBt->inTransaction ){
49858 pBt->inTransaction = p->inTrans;
49860 if( wrflag ){
49861 MemPage *pPage1 = pBt->pPage1;
49862 #ifndef SQLITE_OMIT_SHARED_CACHE
49863 assert( !pBt->pWriter );
49864 pBt->pWriter = p;
49865 pBt->isExclusive = (u8)(wrflag>1);
49866 #endif
49868 /* If the db-size header field is incorrect (as it may be if an old
49869 ** client has been writing the database file), update it now. Doing
49870 ** this sooner rather than later means the database size can safely
49871 ** re-read the database size from page 1 if a savepoint or transaction
49872 ** rollback occurs within the transaction.
49874 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
49875 rc = sqlite3PagerWrite(pPage1->pDbPage);
49876 if( rc==SQLITE_OK ){
49877 put4byte(&pPage1->aData[28], pBt->nPage);
49884 trans_begun:
49885 if( rc==SQLITE_OK && wrflag ){
49886 /* This call makes sure that the pager has the correct number of
49887 ** open savepoints. If the second parameter is greater than 0 and
49888 ** the sub-journal is not already open, then it will be opened here.
49890 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
49893 btreeIntegrity(p);
49894 sqlite3BtreeLeave(p);
49895 return rc;
49898 #ifndef SQLITE_OMIT_AUTOVACUUM
49901 ** Set the pointer-map entries for all children of page pPage. Also, if
49902 ** pPage contains cells that point to overflow pages, set the pointer
49903 ** map entries for the overflow pages as well.
49905 static int setChildPtrmaps(MemPage *pPage){
49906 int i; /* Counter variable */
49907 int nCell; /* Number of cells in page pPage */
49908 int rc; /* Return code */
49909 BtShared *pBt = pPage->pBt;
49910 u8 isInitOrig = pPage->isInit;
49911 Pgno pgno = pPage->pgno;
49913 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49914 rc = btreeInitPage(pPage);
49915 if( rc!=SQLITE_OK ){
49916 goto set_child_ptrmaps_out;
49918 nCell = pPage->nCell;
49920 for(i=0; i<nCell; i++){
49921 u8 *pCell = findCell(pPage, i);
49923 ptrmapPutOvflPtr(pPage, pCell, &rc);
49925 if( !pPage->leaf ){
49926 Pgno childPgno = get4byte(pCell);
49927 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
49931 if( !pPage->leaf ){
49932 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49933 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
49936 set_child_ptrmaps_out:
49937 pPage->isInit = isInitOrig;
49938 return rc;
49942 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
49943 ** that it points to iTo. Parameter eType describes the type of pointer to
49944 ** be modified, as follows:
49946 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
49947 ** page of pPage.
49949 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
49950 ** page pointed to by one of the cells on pPage.
49952 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
49953 ** overflow page in the list.
49955 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
49956 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49957 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49958 if( eType==PTRMAP_OVERFLOW2 ){
49959 /* The pointer is always the first 4 bytes of the page in this case. */
49960 if( get4byte(pPage->aData)!=iFrom ){
49961 return SQLITE_CORRUPT_BKPT;
49963 put4byte(pPage->aData, iTo);
49964 }else{
49965 u8 isInitOrig = pPage->isInit;
49966 int i;
49967 int nCell;
49969 btreeInitPage(pPage);
49970 nCell = pPage->nCell;
49972 for(i=0; i<nCell; i++){
49973 u8 *pCell = findCell(pPage, i);
49974 if( eType==PTRMAP_OVERFLOW1 ){
49975 CellInfo info;
49976 btreeParseCellPtr(pPage, pCell, &info);
49977 if( info.iOverflow ){
49978 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
49979 put4byte(&pCell[info.iOverflow], iTo);
49980 break;
49983 }else{
49984 if( get4byte(pCell)==iFrom ){
49985 put4byte(pCell, iTo);
49986 break;
49991 if( i==nCell ){
49992 if( eType!=PTRMAP_BTREE ||
49993 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
49994 return SQLITE_CORRUPT_BKPT;
49996 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
49999 pPage->isInit = isInitOrig;
50001 return SQLITE_OK;
50006 ** Move the open database page pDbPage to location iFreePage in the
50007 ** database. The pDbPage reference remains valid.
50009 ** The isCommit flag indicates that there is no need to remember that
50010 ** the journal needs to be sync()ed before database page pDbPage->pgno
50011 ** can be written to. The caller has already promised not to write to that
50012 ** page.
50014 static int relocatePage(
50015 BtShared *pBt, /* Btree */
50016 MemPage *pDbPage, /* Open page to move */
50017 u8 eType, /* Pointer map 'type' entry for pDbPage */
50018 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
50019 Pgno iFreePage, /* The location to move pDbPage to */
50020 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
50022 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
50023 Pgno iDbPage = pDbPage->pgno;
50024 Pager *pPager = pBt->pPager;
50025 int rc;
50027 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
50028 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
50029 assert( sqlite3_mutex_held(pBt->mutex) );
50030 assert( pDbPage->pBt==pBt );
50032 /* Move page iDbPage from its current location to page number iFreePage */
50033 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
50034 iDbPage, iFreePage, iPtrPage, eType));
50035 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
50036 if( rc!=SQLITE_OK ){
50037 return rc;
50039 pDbPage->pgno = iFreePage;
50041 /* If pDbPage was a btree-page, then it may have child pages and/or cells
50042 ** that point to overflow pages. The pointer map entries for all these
50043 ** pages need to be changed.
50045 ** If pDbPage is an overflow page, then the first 4 bytes may store a
50046 ** pointer to a subsequent overflow page. If this is the case, then
50047 ** the pointer map needs to be updated for the subsequent overflow page.
50049 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
50050 rc = setChildPtrmaps(pDbPage);
50051 if( rc!=SQLITE_OK ){
50052 return rc;
50054 }else{
50055 Pgno nextOvfl = get4byte(pDbPage->aData);
50056 if( nextOvfl!=0 ){
50057 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
50058 if( rc!=SQLITE_OK ){
50059 return rc;
50064 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
50065 ** that it points at iFreePage. Also fix the pointer map entry for
50066 ** iPtrPage.
50068 if( eType!=PTRMAP_ROOTPAGE ){
50069 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
50070 if( rc!=SQLITE_OK ){
50071 return rc;
50073 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
50074 if( rc!=SQLITE_OK ){
50075 releasePage(pPtrPage);
50076 return rc;
50078 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
50079 releasePage(pPtrPage);
50080 if( rc==SQLITE_OK ){
50081 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
50084 return rc;
50087 /* Forward declaration required by incrVacuumStep(). */
50088 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
50091 ** Perform a single step of an incremental-vacuum. If successful,
50092 ** return SQLITE_OK. If there is no work to do (and therefore no
50093 ** point in calling this function again), return SQLITE_DONE.
50095 ** More specificly, this function attempts to re-organize the
50096 ** database so that the last page of the file currently in use
50097 ** is no longer in use.
50099 ** If the nFin parameter is non-zero, this function assumes
50100 ** that the caller will keep calling incrVacuumStep() until
50101 ** it returns SQLITE_DONE or an error, and that nFin is the
50102 ** number of pages the database file will contain after this
50103 ** process is complete. If nFin is zero, it is assumed that
50104 ** incrVacuumStep() will be called a finite amount of times
50105 ** which may or may not empty the freelist. A full autovacuum
50106 ** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==0.
50108 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
50109 Pgno nFreeList; /* Number of pages still on the free-list */
50110 int rc;
50112 assert( sqlite3_mutex_held(pBt->mutex) );
50113 assert( iLastPg>nFin );
50115 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
50116 u8 eType;
50117 Pgno iPtrPage;
50119 nFreeList = get4byte(&pBt->pPage1->aData[36]);
50120 if( nFreeList==0 ){
50121 return SQLITE_DONE;
50124 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
50125 if( rc!=SQLITE_OK ){
50126 return rc;
50128 if( eType==PTRMAP_ROOTPAGE ){
50129 return SQLITE_CORRUPT_BKPT;
50132 if( eType==PTRMAP_FREEPAGE ){
50133 if( nFin==0 ){
50134 /* Remove the page from the files free-list. This is not required
50135 ** if nFin is non-zero. In that case, the free-list will be
50136 ** truncated to zero after this function returns, so it doesn't
50137 ** matter if it still contains some garbage entries.
50139 Pgno iFreePg;
50140 MemPage *pFreePg;
50141 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
50142 if( rc!=SQLITE_OK ){
50143 return rc;
50145 assert( iFreePg==iLastPg );
50146 releasePage(pFreePg);
50148 } else {
50149 Pgno iFreePg; /* Index of free page to move pLastPg to */
50150 MemPage *pLastPg;
50152 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
50153 if( rc!=SQLITE_OK ){
50154 return rc;
50157 /* If nFin is zero, this loop runs exactly once and page pLastPg
50158 ** is swapped with the first free page pulled off the free list.
50160 ** On the other hand, if nFin is greater than zero, then keep
50161 ** looping until a free-page located within the first nFin pages
50162 ** of the file is found.
50164 do {
50165 MemPage *pFreePg;
50166 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
50167 if( rc!=SQLITE_OK ){
50168 releasePage(pLastPg);
50169 return rc;
50171 releasePage(pFreePg);
50172 }while( nFin!=0 && iFreePg>nFin );
50173 assert( iFreePg<iLastPg );
50175 rc = sqlite3PagerWrite(pLastPg->pDbPage);
50176 if( rc==SQLITE_OK ){
50177 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
50179 releasePage(pLastPg);
50180 if( rc!=SQLITE_OK ){
50181 return rc;
50186 if( nFin==0 ){
50187 iLastPg--;
50188 while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
50189 if( PTRMAP_ISPAGE(pBt, iLastPg) ){
50190 MemPage *pPg;
50191 rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
50192 if( rc!=SQLITE_OK ){
50193 return rc;
50195 rc = sqlite3PagerWrite(pPg->pDbPage);
50196 releasePage(pPg);
50197 if( rc!=SQLITE_OK ){
50198 return rc;
50201 iLastPg--;
50203 sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
50204 pBt->nPage = iLastPg;
50206 return SQLITE_OK;
50210 ** A write-transaction must be opened before calling this function.
50211 ** It performs a single unit of work towards an incremental vacuum.
50213 ** If the incremental vacuum is finished after this function has run,
50214 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
50215 ** SQLITE_OK is returned. Otherwise an SQLite error code.
50217 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
50218 int rc;
50219 BtShared *pBt = p->pBt;
50221 sqlite3BtreeEnter(p);
50222 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
50223 if( !pBt->autoVacuum ){
50224 rc = SQLITE_DONE;
50225 }else{
50226 invalidateAllOverflowCache(pBt);
50227 rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
50228 if( rc==SQLITE_OK ){
50229 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50230 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
50233 sqlite3BtreeLeave(p);
50234 return rc;
50238 ** This routine is called prior to sqlite3PagerCommit when a transaction
50239 ** is commited for an auto-vacuum database.
50241 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
50242 ** the database file should be truncated to during the commit process.
50243 ** i.e. the database has been reorganized so that only the first *pnTrunc
50244 ** pages are in use.
50246 static int autoVacuumCommit(BtShared *pBt){
50247 int rc = SQLITE_OK;
50248 Pager *pPager = pBt->pPager;
50249 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
50251 assert( sqlite3_mutex_held(pBt->mutex) );
50252 invalidateAllOverflowCache(pBt);
50253 assert(pBt->autoVacuum);
50254 if( !pBt->incrVacuum ){
50255 Pgno nFin; /* Number of pages in database after autovacuuming */
50256 Pgno nFree; /* Number of pages on the freelist initially */
50257 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
50258 Pgno iFree; /* The next page to be freed */
50259 int nEntry; /* Number of entries on one ptrmap page */
50260 Pgno nOrig; /* Database size before freeing */
50262 nOrig = btreePagecount(pBt);
50263 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
50264 /* It is not possible to create a database for which the final page
50265 ** is either a pointer-map page or the pending-byte page. If one
50266 ** is encountered, this indicates corruption.
50268 return SQLITE_CORRUPT_BKPT;
50271 nFree = get4byte(&pBt->pPage1->aData[36]);
50272 nEntry = pBt->usableSize/5;
50273 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
50274 nFin = nOrig - nFree - nPtrmap;
50275 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
50276 nFin--;
50278 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
50279 nFin--;
50281 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
50283 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
50284 rc = incrVacuumStep(pBt, nFin, iFree);
50286 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
50287 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50288 put4byte(&pBt->pPage1->aData[32], 0);
50289 put4byte(&pBt->pPage1->aData[36], 0);
50290 put4byte(&pBt->pPage1->aData[28], nFin);
50291 sqlite3PagerTruncateImage(pBt->pPager, nFin);
50292 pBt->nPage = nFin;
50294 if( rc!=SQLITE_OK ){
50295 sqlite3PagerRollback(pPager);
50299 assert( nRef==sqlite3PagerRefcount(pPager) );
50300 return rc;
50303 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
50304 # define setChildPtrmaps(x) SQLITE_OK
50305 #endif
50308 ** This routine does the first phase of a two-phase commit. This routine
50309 ** causes a rollback journal to be created (if it does not already exist)
50310 ** and populated with enough information so that if a power loss occurs
50311 ** the database can be restored to its original state by playing back
50312 ** the journal. Then the contents of the journal are flushed out to
50313 ** the disk. After the journal is safely on oxide, the changes to the
50314 ** database are written into the database file and flushed to oxide.
50315 ** At the end of this call, the rollback journal still exists on the
50316 ** disk and we are still holding all locks, so the transaction has not
50317 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
50318 ** commit process.
50320 ** This call is a no-op if no write-transaction is currently active on pBt.
50322 ** Otherwise, sync the database file for the btree pBt. zMaster points to
50323 ** the name of a master journal file that should be written into the
50324 ** individual journal file, or is NULL, indicating no master journal file
50325 ** (single database transaction).
50327 ** When this is called, the master journal should already have been
50328 ** created, populated with this journal pointer and synced to disk.
50330 ** Once this is routine has returned, the only thing required to commit
50331 ** the write-transaction for this database file is to delete the journal.
50333 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
50334 int rc = SQLITE_OK;
50335 if( p->inTrans==TRANS_WRITE ){
50336 BtShared *pBt = p->pBt;
50337 sqlite3BtreeEnter(p);
50338 #ifndef SQLITE_OMIT_AUTOVACUUM
50339 if( pBt->autoVacuum ){
50340 rc = autoVacuumCommit(pBt);
50341 if( rc!=SQLITE_OK ){
50342 sqlite3BtreeLeave(p);
50343 return rc;
50346 #endif
50347 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
50348 sqlite3BtreeLeave(p);
50350 return rc;
50354 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
50355 ** at the conclusion of a transaction.
50357 static void btreeEndTransaction(Btree *p){
50358 BtShared *pBt = p->pBt;
50359 assert( sqlite3BtreeHoldsMutex(p) );
50361 btreeClearHasContent(pBt);
50362 if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
50363 /* If there are other active statements that belong to this database
50364 ** handle, downgrade to a read-only transaction. The other statements
50365 ** may still be reading from the database. */
50366 downgradeAllSharedCacheTableLocks(p);
50367 p->inTrans = TRANS_READ;
50368 }else{
50369 /* If the handle had any kind of transaction open, decrement the
50370 ** transaction count of the shared btree. If the transaction count
50371 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
50372 ** call below will unlock the pager. */
50373 if( p->inTrans!=TRANS_NONE ){
50374 clearAllSharedCacheTableLocks(p);
50375 pBt->nTransaction--;
50376 if( 0==pBt->nTransaction ){
50377 pBt->inTransaction = TRANS_NONE;
50381 /* Set the current transaction state to TRANS_NONE and unlock the
50382 ** pager if this call closed the only read or write transaction. */
50383 p->inTrans = TRANS_NONE;
50384 unlockBtreeIfUnused(pBt);
50387 btreeIntegrity(p);
50391 ** Commit the transaction currently in progress.
50393 ** This routine implements the second phase of a 2-phase commit. The
50394 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
50395 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
50396 ** routine did all the work of writing information out to disk and flushing the
50397 ** contents so that they are written onto the disk platter. All this
50398 ** routine has to do is delete or truncate or zero the header in the
50399 ** the rollback journal (which causes the transaction to commit) and
50400 ** drop locks.
50402 ** Normally, if an error occurs while the pager layer is attempting to
50403 ** finalize the underlying journal file, this function returns an error and
50404 ** the upper layer will attempt a rollback. However, if the second argument
50405 ** is non-zero then this b-tree transaction is part of a multi-file
50406 ** transaction. In this case, the transaction has already been committed
50407 ** (by deleting a master journal file) and the caller will ignore this
50408 ** functions return code. So, even if an error occurs in the pager layer,
50409 ** reset the b-tree objects internal state to indicate that the write
50410 ** transaction has been closed. This is quite safe, as the pager will have
50411 ** transitioned to the error state.
50413 ** This will release the write lock on the database file. If there
50414 ** are no active cursors, it also releases the read lock.
50416 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
50418 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
50419 sqlite3BtreeEnter(p);
50420 btreeIntegrity(p);
50422 /* If the handle has a write-transaction open, commit the shared-btrees
50423 ** transaction and set the shared state to TRANS_READ.
50425 if( p->inTrans==TRANS_WRITE ){
50426 int rc;
50427 BtShared *pBt = p->pBt;
50428 assert( pBt->inTransaction==TRANS_WRITE );
50429 assert( pBt->nTransaction>0 );
50430 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
50431 if( rc!=SQLITE_OK && bCleanup==0 ){
50432 sqlite3BtreeLeave(p);
50433 return rc;
50435 pBt->inTransaction = TRANS_READ;
50438 btreeEndTransaction(p);
50439 sqlite3BtreeLeave(p);
50440 return SQLITE_OK;
50444 ** Do both phases of a commit.
50446 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
50447 int rc;
50448 sqlite3BtreeEnter(p);
50449 rc = sqlite3BtreeCommitPhaseOne(p, 0);
50450 if( rc==SQLITE_OK ){
50451 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
50453 sqlite3BtreeLeave(p);
50454 return rc;
50457 #ifndef NDEBUG
50459 ** Return the number of write-cursors open on this handle. This is for use
50460 ** in assert() expressions, so it is only compiled if NDEBUG is not
50461 ** defined.
50463 ** For the purposes of this routine, a write-cursor is any cursor that
50464 ** is capable of writing to the databse. That means the cursor was
50465 ** originally opened for writing and the cursor has not be disabled
50466 ** by having its state changed to CURSOR_FAULT.
50468 static int countWriteCursors(BtShared *pBt){
50469 BtCursor *pCur;
50470 int r = 0;
50471 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
50472 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
50474 return r;
50476 #endif
50479 ** This routine sets the state to CURSOR_FAULT and the error
50480 ** code to errCode for every cursor on BtShared that pBtree
50481 ** references.
50483 ** Every cursor is tripped, including cursors that belong
50484 ** to other database connections that happen to be sharing
50485 ** the cache with pBtree.
50487 ** This routine gets called when a rollback occurs.
50488 ** All cursors using the same cache must be tripped
50489 ** to prevent them from trying to use the btree after
50490 ** the rollback. The rollback may have deleted tables
50491 ** or moved root pages, so it is not sufficient to
50492 ** save the state of the cursor. The cursor must be
50493 ** invalidated.
50495 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
50496 BtCursor *p;
50497 sqlite3BtreeEnter(pBtree);
50498 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
50499 int i;
50500 sqlite3BtreeClearCursor(p);
50501 p->eState = CURSOR_FAULT;
50502 p->skipNext = errCode;
50503 for(i=0; i<=p->iPage; i++){
50504 releasePage(p->apPage[i]);
50505 p->apPage[i] = 0;
50508 sqlite3BtreeLeave(pBtree);
50512 ** Rollback the transaction in progress. All cursors will be
50513 ** invalided by this operation. Any attempt to use a cursor
50514 ** that was open at the beginning of this operation will result
50515 ** in an error.
50517 ** This will release the write lock on the database file. If there
50518 ** are no active cursors, it also releases the read lock.
50520 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
50521 int rc;
50522 BtShared *pBt = p->pBt;
50523 MemPage *pPage1;
50525 sqlite3BtreeEnter(p);
50526 rc = saveAllCursors(pBt, 0, 0);
50527 #ifndef SQLITE_OMIT_SHARED_CACHE
50528 if( rc!=SQLITE_OK ){
50529 /* This is a horrible situation. An IO or malloc() error occurred whilst
50530 ** trying to save cursor positions. If this is an automatic rollback (as
50531 ** the result of a constraint, malloc() failure or IO error) then
50532 ** the cache may be internally inconsistent (not contain valid trees) so
50533 ** we cannot simply return the error to the caller. Instead, abort
50534 ** all queries that may be using any of the cursors that failed to save.
50536 sqlite3BtreeTripAllCursors(p, rc);
50538 #endif
50539 btreeIntegrity(p);
50541 if( p->inTrans==TRANS_WRITE ){
50542 int rc2;
50544 assert( TRANS_WRITE==pBt->inTransaction );
50545 rc2 = sqlite3PagerRollback(pBt->pPager);
50546 if( rc2!=SQLITE_OK ){
50547 rc = rc2;
50550 /* The rollback may have destroyed the pPage1->aData value. So
50551 ** call btreeGetPage() on page 1 again to make
50552 ** sure pPage1->aData is set correctly. */
50553 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
50554 int nPage = get4byte(28+(u8*)pPage1->aData);
50555 testcase( nPage==0 );
50556 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
50557 testcase( pBt->nPage!=nPage );
50558 pBt->nPage = nPage;
50559 releasePage(pPage1);
50561 assert( countWriteCursors(pBt)==0 );
50562 pBt->inTransaction = TRANS_READ;
50565 btreeEndTransaction(p);
50566 sqlite3BtreeLeave(p);
50567 return rc;
50571 ** Start a statement subtransaction. The subtransaction can can be rolled
50572 ** back independently of the main transaction. You must start a transaction
50573 ** before starting a subtransaction. The subtransaction is ended automatically
50574 ** if the main transaction commits or rolls back.
50576 ** Statement subtransactions are used around individual SQL statements
50577 ** that are contained within a BEGIN...COMMIT block. If a constraint
50578 ** error occurs within the statement, the effect of that one statement
50579 ** can be rolled back without having to rollback the entire transaction.
50581 ** A statement sub-transaction is implemented as an anonymous savepoint. The
50582 ** value passed as the second parameter is the total number of savepoints,
50583 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
50584 ** are no active savepoints and no other statement-transactions open,
50585 ** iStatement is 1. This anonymous savepoint can be released or rolled back
50586 ** using the sqlite3BtreeSavepoint() function.
50588 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
50589 int rc;
50590 BtShared *pBt = p->pBt;
50591 sqlite3BtreeEnter(p);
50592 assert( p->inTrans==TRANS_WRITE );
50593 assert( pBt->readOnly==0 );
50594 assert( iStatement>0 );
50595 assert( iStatement>p->db->nSavepoint );
50596 assert( pBt->inTransaction==TRANS_WRITE );
50597 /* At the pager level, a statement transaction is a savepoint with
50598 ** an index greater than all savepoints created explicitly using
50599 ** SQL statements. It is illegal to open, release or rollback any
50600 ** such savepoints while the statement transaction savepoint is active.
50602 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
50603 sqlite3BtreeLeave(p);
50604 return rc;
50608 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
50609 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
50610 ** savepoint identified by parameter iSavepoint, depending on the value
50611 ** of op.
50613 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
50614 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
50615 ** contents of the entire transaction are rolled back. This is different
50616 ** from a normal transaction rollback, as no locks are released and the
50617 ** transaction remains open.
50619 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
50620 int rc = SQLITE_OK;
50621 if( p && p->inTrans==TRANS_WRITE ){
50622 BtShared *pBt = p->pBt;
50623 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
50624 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
50625 sqlite3BtreeEnter(p);
50626 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
50627 if( rc==SQLITE_OK ){
50628 if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
50629 rc = newDatabase(pBt);
50630 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
50632 /* The database size was written into the offset 28 of the header
50633 ** when the transaction started, so we know that the value at offset
50634 ** 28 is nonzero. */
50635 assert( pBt->nPage>0 );
50637 sqlite3BtreeLeave(p);
50639 return rc;
50643 ** Create a new cursor for the BTree whose root is on the page
50644 ** iTable. If a read-only cursor is requested, it is assumed that
50645 ** the caller already has at least a read-only transaction open
50646 ** on the database already. If a write-cursor is requested, then
50647 ** the caller is assumed to have an open write transaction.
50649 ** If wrFlag==0, then the cursor can only be used for reading.
50650 ** If wrFlag==1, then the cursor can be used for reading or for
50651 ** writing if other conditions for writing are also met. These
50652 ** are the conditions that must be met in order for writing to
50653 ** be allowed:
50655 ** 1: The cursor must have been opened with wrFlag==1
50657 ** 2: Other database connections that share the same pager cache
50658 ** but which are not in the READ_UNCOMMITTED state may not have
50659 ** cursors open with wrFlag==0 on the same table. Otherwise
50660 ** the changes made by this write cursor would be visible to
50661 ** the read cursors in the other database connection.
50663 ** 3: The database must be writable (not on read-only media)
50665 ** 4: There must be an active transaction.
50667 ** No checking is done to make sure that page iTable really is the
50668 ** root page of a b-tree. If it is not, then the cursor acquired
50669 ** will not work correctly.
50671 ** It is assumed that the sqlite3BtreeCursorZero() has been called
50672 ** on pCur to initialize the memory space prior to invoking this routine.
50674 static int btreeCursor(
50675 Btree *p, /* The btree */
50676 int iTable, /* Root page of table to open */
50677 int wrFlag, /* 1 to write. 0 read-only */
50678 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
50679 BtCursor *pCur /* Space for new cursor */
50681 BtShared *pBt = p->pBt; /* Shared b-tree handle */
50683 assert( sqlite3BtreeHoldsMutex(p) );
50684 assert( wrFlag==0 || wrFlag==1 );
50686 /* The following assert statements verify that if this is a sharable
50687 ** b-tree database, the connection is holding the required table locks,
50688 ** and that no other connection has any open cursor that conflicts with
50689 ** this lock. */
50690 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
50691 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
50693 /* Assert that the caller has opened the required transaction. */
50694 assert( p->inTrans>TRANS_NONE );
50695 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
50696 assert( pBt->pPage1 && pBt->pPage1->aData );
50698 if( NEVER(wrFlag && pBt->readOnly) ){
50699 return SQLITE_READONLY;
50701 if( iTable==1 && btreePagecount(pBt)==0 ){
50702 return SQLITE_EMPTY;
50705 /* Now that no other errors can occur, finish filling in the BtCursor
50706 ** variables and link the cursor into the BtShared list. */
50707 pCur->pgnoRoot = (Pgno)iTable;
50708 pCur->iPage = -1;
50709 pCur->pKeyInfo = pKeyInfo;
50710 pCur->pBtree = p;
50711 pCur->pBt = pBt;
50712 pCur->wrFlag = (u8)wrFlag;
50713 pCur->pNext = pBt->pCursor;
50714 if( pCur->pNext ){
50715 pCur->pNext->pPrev = pCur;
50717 pBt->pCursor = pCur;
50718 pCur->eState = CURSOR_INVALID;
50719 pCur->cachedRowid = 0;
50720 return SQLITE_OK;
50722 SQLITE_PRIVATE int sqlite3BtreeCursor(
50723 Btree *p, /* The btree */
50724 int iTable, /* Root page of table to open */
50725 int wrFlag, /* 1 to write. 0 read-only */
50726 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
50727 BtCursor *pCur /* Write new cursor here */
50729 int rc;
50730 sqlite3BtreeEnter(p);
50731 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
50732 sqlite3BtreeLeave(p);
50733 return rc;
50737 ** Return the size of a BtCursor object in bytes.
50739 ** This interfaces is needed so that users of cursors can preallocate
50740 ** sufficient storage to hold a cursor. The BtCursor object is opaque
50741 ** to users so they cannot do the sizeof() themselves - they must call
50742 ** this routine.
50744 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
50745 return ROUND8(sizeof(BtCursor));
50749 ** Initialize memory that will be converted into a BtCursor object.
50751 ** The simple approach here would be to memset() the entire object
50752 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
50753 ** do not need to be zeroed and they are large, so we can save a lot
50754 ** of run-time by skipping the initialization of those elements.
50756 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
50757 memset(p, 0, offsetof(BtCursor, iPage));
50761 ** Set the cached rowid value of every cursor in the same database file
50762 ** as pCur and having the same root page number as pCur. The value is
50763 ** set to iRowid.
50765 ** Only positive rowid values are considered valid for this cache.
50766 ** The cache is initialized to zero, indicating an invalid cache.
50767 ** A btree will work fine with zero or negative rowids. We just cannot
50768 ** cache zero or negative rowids, which means tables that use zero or
50769 ** negative rowids might run a little slower. But in practice, zero
50770 ** or negative rowids are very uncommon so this should not be a problem.
50772 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
50773 BtCursor *p;
50774 for(p=pCur->pBt->pCursor; p; p=p->pNext){
50775 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
50777 assert( pCur->cachedRowid==iRowid );
50781 ** Return the cached rowid for the given cursor. A negative or zero
50782 ** return value indicates that the rowid cache is invalid and should be
50783 ** ignored. If the rowid cache has never before been set, then a
50784 ** zero is returned.
50786 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
50787 return pCur->cachedRowid;
50791 ** Close a cursor. The read lock on the database file is released
50792 ** when the last cursor is closed.
50794 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
50795 Btree *pBtree = pCur->pBtree;
50796 if( pBtree ){
50797 int i;
50798 BtShared *pBt = pCur->pBt;
50799 sqlite3BtreeEnter(pBtree);
50800 sqlite3BtreeClearCursor(pCur);
50801 if( pCur->pPrev ){
50802 pCur->pPrev->pNext = pCur->pNext;
50803 }else{
50804 pBt->pCursor = pCur->pNext;
50806 if( pCur->pNext ){
50807 pCur->pNext->pPrev = pCur->pPrev;
50809 for(i=0; i<=pCur->iPage; i++){
50810 releasePage(pCur->apPage[i]);
50812 unlockBtreeIfUnused(pBt);
50813 invalidateOverflowCache(pCur);
50814 /* sqlite3_free(pCur); */
50815 sqlite3BtreeLeave(pBtree);
50817 return SQLITE_OK;
50821 ** Make sure the BtCursor* given in the argument has a valid
50822 ** BtCursor.info structure. If it is not already valid, call
50823 ** btreeParseCell() to fill it in.
50825 ** BtCursor.info is a cache of the information in the current cell.
50826 ** Using this cache reduces the number of calls to btreeParseCell().
50828 ** 2007-06-25: There is a bug in some versions of MSVC that cause the
50829 ** compiler to crash when getCellInfo() is implemented as a macro.
50830 ** But there is a measureable speed advantage to using the macro on gcc
50831 ** (when less compiler optimizations like -Os or -O0 are used and the
50832 ** compiler is not doing agressive inlining.) So we use a real function
50833 ** for MSVC and a macro for everything else. Ticket #2457.
50835 #ifndef NDEBUG
50836 static void assertCellInfo(BtCursor *pCur){
50837 CellInfo info;
50838 int iPage = pCur->iPage;
50839 memset(&info, 0, sizeof(info));
50840 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
50841 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
50843 #else
50844 #define assertCellInfo(x)
50845 #endif
50846 #ifdef _MSC_VER
50847 /* Use a real function in MSVC to work around bugs in that compiler. */
50848 static void getCellInfo(BtCursor *pCur){
50849 if( pCur->info.nSize==0 ){
50850 int iPage = pCur->iPage;
50851 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
50852 pCur->validNKey = 1;
50853 }else{
50854 assertCellInfo(pCur);
50857 #else /* if not _MSC_VER */
50858 /* Use a macro in all other compilers so that the function is inlined */
50859 #define getCellInfo(pCur) \
50860 if( pCur->info.nSize==0 ){ \
50861 int iPage = pCur->iPage; \
50862 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
50863 pCur->validNKey = 1; \
50864 }else{ \
50865 assertCellInfo(pCur); \
50867 #endif /* _MSC_VER */
50869 #ifndef NDEBUG /* The next routine used only within assert() statements */
50871 ** Return true if the given BtCursor is valid. A valid cursor is one
50872 ** that is currently pointing to a row in a (non-empty) table.
50873 ** This is a verification routine is used only within assert() statements.
50875 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
50876 return pCur && pCur->eState==CURSOR_VALID;
50878 #endif /* NDEBUG */
50881 ** Set *pSize to the size of the buffer needed to hold the value of
50882 ** the key for the current entry. If the cursor is not pointing
50883 ** to a valid entry, *pSize is set to 0.
50885 ** For a table with the INTKEY flag set, this routine returns the key
50886 ** itself, not the number of bytes in the key.
50888 ** The caller must position the cursor prior to invoking this routine.
50890 ** This routine cannot fail. It always returns SQLITE_OK.
50892 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
50893 assert( cursorHoldsMutex(pCur) );
50894 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
50895 if( pCur->eState!=CURSOR_VALID ){
50896 *pSize = 0;
50897 }else{
50898 getCellInfo(pCur);
50899 *pSize = pCur->info.nKey;
50901 return SQLITE_OK;
50905 ** Set *pSize to the number of bytes of data in the entry the
50906 ** cursor currently points to.
50908 ** The caller must guarantee that the cursor is pointing to a non-NULL
50909 ** valid entry. In other words, the calling procedure must guarantee
50910 ** that the cursor has Cursor.eState==CURSOR_VALID.
50912 ** Failure is not possible. This function always returns SQLITE_OK.
50913 ** It might just as well be a procedure (returning void) but we continue
50914 ** to return an integer result code for historical reasons.
50916 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
50917 assert( cursorHoldsMutex(pCur) );
50918 assert( pCur->eState==CURSOR_VALID );
50919 getCellInfo(pCur);
50920 *pSize = pCur->info.nData;
50921 return SQLITE_OK;
50925 ** Given the page number of an overflow page in the database (parameter
50926 ** ovfl), this function finds the page number of the next page in the
50927 ** linked list of overflow pages. If possible, it uses the auto-vacuum
50928 ** pointer-map data instead of reading the content of page ovfl to do so.
50930 ** If an error occurs an SQLite error code is returned. Otherwise:
50932 ** The page number of the next overflow page in the linked list is
50933 ** written to *pPgnoNext. If page ovfl is the last page in its linked
50934 ** list, *pPgnoNext is set to zero.
50936 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
50937 ** to page number pOvfl was obtained, then *ppPage is set to point to that
50938 ** reference. It is the responsibility of the caller to call releasePage()
50939 ** on *ppPage to free the reference. In no reference was obtained (because
50940 ** the pointer-map was used to obtain the value for *pPgnoNext), then
50941 ** *ppPage is set to zero.
50943 static int getOverflowPage(
50944 BtShared *pBt, /* The database file */
50945 Pgno ovfl, /* Current overflow page number */
50946 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
50947 Pgno *pPgnoNext /* OUT: Next overflow page number */
50949 Pgno next = 0;
50950 MemPage *pPage = 0;
50951 int rc = SQLITE_OK;
50953 assert( sqlite3_mutex_held(pBt->mutex) );
50954 assert(pPgnoNext);
50956 #ifndef SQLITE_OMIT_AUTOVACUUM
50957 /* Try to find the next page in the overflow list using the
50958 ** autovacuum pointer-map pages. Guess that the next page in
50959 ** the overflow list is page number (ovfl+1). If that guess turns
50960 ** out to be wrong, fall back to loading the data of page
50961 ** number ovfl to determine the next page number.
50963 if( pBt->autoVacuum ){
50964 Pgno pgno;
50965 Pgno iGuess = ovfl+1;
50966 u8 eType;
50968 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
50969 iGuess++;
50972 if( iGuess<=btreePagecount(pBt) ){
50973 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
50974 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
50975 next = iGuess;
50976 rc = SQLITE_DONE;
50980 #endif
50982 assert( next==0 || rc==SQLITE_DONE );
50983 if( rc==SQLITE_OK ){
50984 rc = btreeGetPage(pBt, ovfl, &pPage, 0);
50985 assert( rc==SQLITE_OK || pPage==0 );
50986 if( rc==SQLITE_OK ){
50987 next = get4byte(pPage->aData);
50991 *pPgnoNext = next;
50992 if( ppPage ){
50993 *ppPage = pPage;
50994 }else{
50995 releasePage(pPage);
50997 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
51001 ** Copy data from a buffer to a page, or from a page to a buffer.
51003 ** pPayload is a pointer to data stored on database page pDbPage.
51004 ** If argument eOp is false, then nByte bytes of data are copied
51005 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
51006 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
51007 ** of data are copied from the buffer pBuf to pPayload.
51009 ** SQLITE_OK is returned on success, otherwise an error code.
51011 static int copyPayload(
51012 void *pPayload, /* Pointer to page data */
51013 void *pBuf, /* Pointer to buffer */
51014 int nByte, /* Number of bytes to copy */
51015 int eOp, /* 0 -> copy from page, 1 -> copy to page */
51016 DbPage *pDbPage /* Page containing pPayload */
51018 if( eOp ){
51019 /* Copy data from buffer to page (a write operation) */
51020 int rc = sqlite3PagerWrite(pDbPage);
51021 if( rc!=SQLITE_OK ){
51022 return rc;
51024 memcpy(pPayload, pBuf, nByte);
51025 }else{
51026 /* Copy data from page to buffer (a read operation) */
51027 memcpy(pBuf, pPayload, nByte);
51029 return SQLITE_OK;
51033 ** This function is used to read or overwrite payload information
51034 ** for the entry that the pCur cursor is pointing to. If the eOp
51035 ** parameter is 0, this is a read operation (data copied into
51036 ** buffer pBuf). If it is non-zero, a write (data copied from
51037 ** buffer pBuf).
51039 ** A total of "amt" bytes are read or written beginning at "offset".
51040 ** Data is read to or from the buffer pBuf.
51042 ** The content being read or written might appear on the main page
51043 ** or be scattered out on multiple overflow pages.
51045 ** If the BtCursor.isIncrblobHandle flag is set, and the current
51046 ** cursor entry uses one or more overflow pages, this function
51047 ** allocates space for and lazily popluates the overflow page-list
51048 ** cache array (BtCursor.aOverflow). Subsequent calls use this
51049 ** cache to make seeking to the supplied offset more efficient.
51051 ** Once an overflow page-list cache has been allocated, it may be
51052 ** invalidated if some other cursor writes to the same table, or if
51053 ** the cursor is moved to a different row. Additionally, in auto-vacuum
51054 ** mode, the following events may invalidate an overflow page-list cache.
51056 ** * An incremental vacuum,
51057 ** * A commit in auto_vacuum="full" mode,
51058 ** * Creating a table (may require moving an overflow page).
51060 static int accessPayload(
51061 BtCursor *pCur, /* Cursor pointing to entry to read from */
51062 u32 offset, /* Begin reading this far into payload */
51063 u32 amt, /* Read this many bytes */
51064 unsigned char *pBuf, /* Write the bytes into this buffer */
51065 int eOp /* zero to read. non-zero to write. */
51067 unsigned char *aPayload;
51068 int rc = SQLITE_OK;
51069 u32 nKey;
51070 int iIdx = 0;
51071 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
51072 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
51074 assert( pPage );
51075 assert( pCur->eState==CURSOR_VALID );
51076 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51077 assert( cursorHoldsMutex(pCur) );
51079 getCellInfo(pCur);
51080 aPayload = pCur->info.pCell + pCur->info.nHeader;
51081 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
51083 if( NEVER(offset+amt > nKey+pCur->info.nData)
51084 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
51086 /* Trying to read or write past the end of the data is an error */
51087 return SQLITE_CORRUPT_BKPT;
51090 /* Check if data must be read/written to/from the btree page itself. */
51091 if( offset<pCur->info.nLocal ){
51092 int a = amt;
51093 if( a+offset>pCur->info.nLocal ){
51094 a = pCur->info.nLocal - offset;
51096 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
51097 offset = 0;
51098 pBuf += a;
51099 amt -= a;
51100 }else{
51101 offset -= pCur->info.nLocal;
51104 if( rc==SQLITE_OK && amt>0 ){
51105 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
51106 Pgno nextPage;
51108 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
51110 #ifndef SQLITE_OMIT_INCRBLOB
51111 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
51112 ** has not been allocated, allocate it now. The array is sized at
51113 ** one entry for each overflow page in the overflow chain. The
51114 ** page number of the first overflow page is stored in aOverflow[0],
51115 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
51116 ** (the cache is lazily populated).
51118 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
51119 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
51120 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
51121 /* nOvfl is always positive. If it were zero, fetchPayload would have
51122 ** been used instead of this routine. */
51123 if( ALWAYS(nOvfl) && !pCur->aOverflow ){
51124 rc = SQLITE_NOMEM;
51128 /* If the overflow page-list cache has been allocated and the
51129 ** entry for the first required overflow page is valid, skip
51130 ** directly to it.
51132 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
51133 iIdx = (offset/ovflSize);
51134 nextPage = pCur->aOverflow[iIdx];
51135 offset = (offset%ovflSize);
51137 #endif
51139 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
51141 #ifndef SQLITE_OMIT_INCRBLOB
51142 /* If required, populate the overflow page-list cache. */
51143 if( pCur->aOverflow ){
51144 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
51145 pCur->aOverflow[iIdx] = nextPage;
51147 #endif
51149 if( offset>=ovflSize ){
51150 /* The only reason to read this page is to obtain the page
51151 ** number for the next page in the overflow chain. The page
51152 ** data is not required. So first try to lookup the overflow
51153 ** page-list cache, if any, then fall back to the getOverflowPage()
51154 ** function.
51156 #ifndef SQLITE_OMIT_INCRBLOB
51157 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
51158 nextPage = pCur->aOverflow[iIdx+1];
51159 } else
51160 #endif
51161 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
51162 offset -= ovflSize;
51163 }else{
51164 /* Need to read this page properly. It contains some of the
51165 ** range of data that is being read (eOp==0) or written (eOp!=0).
51167 DbPage *pDbPage;
51168 int a = amt;
51169 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
51170 if( rc==SQLITE_OK ){
51171 aPayload = sqlite3PagerGetData(pDbPage);
51172 nextPage = get4byte(aPayload);
51173 if( a + offset > ovflSize ){
51174 a = ovflSize - offset;
51176 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
51177 sqlite3PagerUnref(pDbPage);
51178 offset = 0;
51179 amt -= a;
51180 pBuf += a;
51186 if( rc==SQLITE_OK && amt>0 ){
51187 return SQLITE_CORRUPT_BKPT;
51189 return rc;
51193 ** Read part of the key associated with cursor pCur. Exactly
51194 ** "amt" bytes will be transfered into pBuf[]. The transfer
51195 ** begins at "offset".
51197 ** The caller must ensure that pCur is pointing to a valid row
51198 ** in the table.
51200 ** Return SQLITE_OK on success or an error code if anything goes
51201 ** wrong. An error is returned if "offset+amt" is larger than
51202 ** the available payload.
51204 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
51205 assert( cursorHoldsMutex(pCur) );
51206 assert( pCur->eState==CURSOR_VALID );
51207 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
51208 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51209 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
51213 ** Read part of the data associated with cursor pCur. Exactly
51214 ** "amt" bytes will be transfered into pBuf[]. The transfer
51215 ** begins at "offset".
51217 ** Return SQLITE_OK on success or an error code if anything goes
51218 ** wrong. An error is returned if "offset+amt" is larger than
51219 ** the available payload.
51221 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
51222 int rc;
51224 #ifndef SQLITE_OMIT_INCRBLOB
51225 if ( pCur->eState==CURSOR_INVALID ){
51226 return SQLITE_ABORT;
51228 #endif
51230 assert( cursorHoldsMutex(pCur) );
51231 rc = restoreCursorPosition(pCur);
51232 if( rc==SQLITE_OK ){
51233 assert( pCur->eState==CURSOR_VALID );
51234 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
51235 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51236 rc = accessPayload(pCur, offset, amt, pBuf, 0);
51238 return rc;
51242 ** Return a pointer to payload information from the entry that the
51243 ** pCur cursor is pointing to. The pointer is to the beginning of
51244 ** the key if skipKey==0 and it points to the beginning of data if
51245 ** skipKey==1. The number of bytes of available key/data is written
51246 ** into *pAmt. If *pAmt==0, then the value returned will not be
51247 ** a valid pointer.
51249 ** This routine is an optimization. It is common for the entire key
51250 ** and data to fit on the local page and for there to be no overflow
51251 ** pages. When that is so, this routine can be used to access the
51252 ** key and data without making a copy. If the key and/or data spills
51253 ** onto overflow pages, then accessPayload() must be used to reassemble
51254 ** the key/data and copy it into a preallocated buffer.
51256 ** The pointer returned by this routine looks directly into the cached
51257 ** page of the database. The data might change or move the next time
51258 ** any btree routine is called.
51260 static const unsigned char *fetchPayload(
51261 BtCursor *pCur, /* Cursor pointing to entry to read from */
51262 int *pAmt, /* Write the number of available bytes here */
51263 int skipKey /* read beginning at data if this is true */
51265 unsigned char *aPayload;
51266 MemPage *pPage;
51267 u32 nKey;
51268 u32 nLocal;
51270 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
51271 assert( pCur->eState==CURSOR_VALID );
51272 assert( cursorHoldsMutex(pCur) );
51273 pPage = pCur->apPage[pCur->iPage];
51274 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51275 if( NEVER(pCur->info.nSize==0) ){
51276 btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
51277 &pCur->info);
51279 aPayload = pCur->info.pCell;
51280 aPayload += pCur->info.nHeader;
51281 if( pPage->intKey ){
51282 nKey = 0;
51283 }else{
51284 nKey = (int)pCur->info.nKey;
51286 if( skipKey ){
51287 aPayload += nKey;
51288 nLocal = pCur->info.nLocal - nKey;
51289 }else{
51290 nLocal = pCur->info.nLocal;
51291 assert( nLocal<=nKey );
51293 *pAmt = nLocal;
51294 return aPayload;
51299 ** For the entry that cursor pCur is point to, return as
51300 ** many bytes of the key or data as are available on the local
51301 ** b-tree page. Write the number of available bytes into *pAmt.
51303 ** The pointer returned is ephemeral. The key/data may move
51304 ** or be destroyed on the next call to any Btree routine,
51305 ** including calls from other threads against the same cache.
51306 ** Hence, a mutex on the BtShared should be held prior to calling
51307 ** this routine.
51309 ** These routines is used to get quick access to key and data
51310 ** in the common case where no overflow pages are used.
51312 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
51313 const void *p = 0;
51314 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51315 assert( cursorHoldsMutex(pCur) );
51316 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51317 p = (const void*)fetchPayload(pCur, pAmt, 0);
51319 return p;
51321 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
51322 const void *p = 0;
51323 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51324 assert( cursorHoldsMutex(pCur) );
51325 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51326 p = (const void*)fetchPayload(pCur, pAmt, 1);
51328 return p;
51333 ** Move the cursor down to a new child page. The newPgno argument is the
51334 ** page number of the child page to move to.
51336 ** This function returns SQLITE_CORRUPT if the page-header flags field of
51337 ** the new child page does not match the flags field of the parent (i.e.
51338 ** if an intkey page appears to be the parent of a non-intkey page, or
51339 ** vice-versa).
51341 static int moveToChild(BtCursor *pCur, u32 newPgno){
51342 int rc;
51343 int i = pCur->iPage;
51344 MemPage *pNewPage;
51345 BtShared *pBt = pCur->pBt;
51347 assert( cursorHoldsMutex(pCur) );
51348 assert( pCur->eState==CURSOR_VALID );
51349 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
51350 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
51351 return SQLITE_CORRUPT_BKPT;
51353 rc = getAndInitPage(pBt, newPgno, &pNewPage);
51354 if( rc ) return rc;
51355 pCur->apPage[i+1] = pNewPage;
51356 pCur->aiIdx[i+1] = 0;
51357 pCur->iPage++;
51359 pCur->info.nSize = 0;
51360 pCur->validNKey = 0;
51361 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
51362 return SQLITE_CORRUPT_BKPT;
51364 return SQLITE_OK;
51367 #ifndef NDEBUG
51369 ** Page pParent is an internal (non-leaf) tree page. This function
51370 ** asserts that page number iChild is the left-child if the iIdx'th
51371 ** cell in page pParent. Or, if iIdx is equal to the total number of
51372 ** cells in pParent, that page number iChild is the right-child of
51373 ** the page.
51375 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
51376 assert( iIdx<=pParent->nCell );
51377 if( iIdx==pParent->nCell ){
51378 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
51379 }else{
51380 assert( get4byte(findCell(pParent, iIdx))==iChild );
51383 #else
51384 # define assertParentIndex(x,y,z)
51385 #endif
51388 ** Move the cursor up to the parent page.
51390 ** pCur->idx is set to the cell index that contains the pointer
51391 ** to the page we are coming from. If we are coming from the
51392 ** right-most child page then pCur->idx is set to one more than
51393 ** the largest cell index.
51395 static void moveToParent(BtCursor *pCur){
51396 assert( cursorHoldsMutex(pCur) );
51397 assert( pCur->eState==CURSOR_VALID );
51398 assert( pCur->iPage>0 );
51399 assert( pCur->apPage[pCur->iPage] );
51400 assertParentIndex(
51401 pCur->apPage[pCur->iPage-1],
51402 pCur->aiIdx[pCur->iPage-1],
51403 pCur->apPage[pCur->iPage]->pgno
51405 releasePage(pCur->apPage[pCur->iPage]);
51406 pCur->iPage--;
51407 pCur->info.nSize = 0;
51408 pCur->validNKey = 0;
51412 ** Move the cursor to point to the root page of its b-tree structure.
51414 ** If the table has a virtual root page, then the cursor is moved to point
51415 ** to the virtual root page instead of the actual root page. A table has a
51416 ** virtual root page when the actual root page contains no cells and a
51417 ** single child page. This can only happen with the table rooted at page 1.
51419 ** If the b-tree structure is empty, the cursor state is set to
51420 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
51421 ** cell located on the root (or virtual root) page and the cursor state
51422 ** is set to CURSOR_VALID.
51424 ** If this function returns successfully, it may be assumed that the
51425 ** page-header flags indicate that the [virtual] root-page is the expected
51426 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
51427 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
51428 ** indicating a table b-tree, or if the caller did specify a KeyInfo
51429 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
51430 ** b-tree).
51432 static int moveToRoot(BtCursor *pCur){
51433 MemPage *pRoot;
51434 int rc = SQLITE_OK;
51435 Btree *p = pCur->pBtree;
51436 BtShared *pBt = p->pBt;
51438 assert( cursorHoldsMutex(pCur) );
51439 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
51440 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
51441 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
51442 if( pCur->eState>=CURSOR_REQUIRESEEK ){
51443 if( pCur->eState==CURSOR_FAULT ){
51444 assert( pCur->skipNext!=SQLITE_OK );
51445 return pCur->skipNext;
51447 sqlite3BtreeClearCursor(pCur);
51450 if( pCur->iPage>=0 ){
51451 int i;
51452 for(i=1; i<=pCur->iPage; i++){
51453 releasePage(pCur->apPage[i]);
51455 pCur->iPage = 0;
51456 }else{
51457 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
51458 if( rc!=SQLITE_OK ){
51459 pCur->eState = CURSOR_INVALID;
51460 return rc;
51462 pCur->iPage = 0;
51464 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
51465 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
51466 ** NULL, the caller expects a table b-tree. If this is not the case,
51467 ** return an SQLITE_CORRUPT error. */
51468 assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
51469 if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
51470 return SQLITE_CORRUPT_BKPT;
51474 /* Assert that the root page is of the correct type. This must be the
51475 ** case as the call to this function that loaded the root-page (either
51476 ** this call or a previous invocation) would have detected corruption
51477 ** if the assumption were not true, and it is not possible for the flags
51478 ** byte to have been modified while this cursor is holding a reference
51479 ** to the page. */
51480 pRoot = pCur->apPage[0];
51481 assert( pRoot->pgno==pCur->pgnoRoot );
51482 assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
51484 pCur->aiIdx[0] = 0;
51485 pCur->info.nSize = 0;
51486 pCur->atLast = 0;
51487 pCur->validNKey = 0;
51489 if( pRoot->nCell==0 && !pRoot->leaf ){
51490 Pgno subpage;
51491 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
51492 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
51493 pCur->eState = CURSOR_VALID;
51494 rc = moveToChild(pCur, subpage);
51495 }else{
51496 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
51498 return rc;
51502 ** Move the cursor down to the left-most leaf entry beneath the
51503 ** entry to which it is currently pointing.
51505 ** The left-most leaf is the one with the smallest key - the first
51506 ** in ascending order.
51508 static int moveToLeftmost(BtCursor *pCur){
51509 Pgno pgno;
51510 int rc = SQLITE_OK;
51511 MemPage *pPage;
51513 assert( cursorHoldsMutex(pCur) );
51514 assert( pCur->eState==CURSOR_VALID );
51515 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51516 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51517 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
51518 rc = moveToChild(pCur, pgno);
51520 return rc;
51524 ** Move the cursor down to the right-most leaf entry beneath the
51525 ** page to which it is currently pointing. Notice the difference
51526 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
51527 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
51528 ** finds the right-most entry beneath the *page*.
51530 ** The right-most entry is the one with the largest key - the last
51531 ** key in ascending order.
51533 static int moveToRightmost(BtCursor *pCur){
51534 Pgno pgno;
51535 int rc = SQLITE_OK;
51536 MemPage *pPage = 0;
51538 assert( cursorHoldsMutex(pCur) );
51539 assert( pCur->eState==CURSOR_VALID );
51540 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51541 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51542 pCur->aiIdx[pCur->iPage] = pPage->nCell;
51543 rc = moveToChild(pCur, pgno);
51545 if( rc==SQLITE_OK ){
51546 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
51547 pCur->info.nSize = 0;
51548 pCur->validNKey = 0;
51550 return rc;
51553 /* Move the cursor to the first entry in the table. Return SQLITE_OK
51554 ** on success. Set *pRes to 0 if the cursor actually points to something
51555 ** or set *pRes to 1 if the table is empty.
51557 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
51558 int rc;
51560 assert( cursorHoldsMutex(pCur) );
51561 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51562 rc = moveToRoot(pCur);
51563 if( rc==SQLITE_OK ){
51564 if( pCur->eState==CURSOR_INVALID ){
51565 assert( pCur->apPage[pCur->iPage]->nCell==0 );
51566 *pRes = 1;
51567 }else{
51568 assert( pCur->apPage[pCur->iPage]->nCell>0 );
51569 *pRes = 0;
51570 rc = moveToLeftmost(pCur);
51573 return rc;
51576 /* Move the cursor to the last entry in the table. Return SQLITE_OK
51577 ** on success. Set *pRes to 0 if the cursor actually points to something
51578 ** or set *pRes to 1 if the table is empty.
51580 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
51581 int rc;
51583 assert( cursorHoldsMutex(pCur) );
51584 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51586 /* If the cursor already points to the last entry, this is a no-op. */
51587 if( CURSOR_VALID==pCur->eState && pCur->atLast ){
51588 #ifdef SQLITE_DEBUG
51589 /* This block serves to assert() that the cursor really does point
51590 ** to the last entry in the b-tree. */
51591 int ii;
51592 for(ii=0; ii<pCur->iPage; ii++){
51593 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
51595 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
51596 assert( pCur->apPage[pCur->iPage]->leaf );
51597 #endif
51598 return SQLITE_OK;
51601 rc = moveToRoot(pCur);
51602 if( rc==SQLITE_OK ){
51603 if( CURSOR_INVALID==pCur->eState ){
51604 assert( pCur->apPage[pCur->iPage]->nCell==0 );
51605 *pRes = 1;
51606 }else{
51607 assert( pCur->eState==CURSOR_VALID );
51608 *pRes = 0;
51609 rc = moveToRightmost(pCur);
51610 pCur->atLast = rc==SQLITE_OK ?1:0;
51613 return rc;
51616 /* Move the cursor so that it points to an entry near the key
51617 ** specified by pIdxKey or intKey. Return a success code.
51619 ** For INTKEY tables, the intKey parameter is used. pIdxKey
51620 ** must be NULL. For index tables, pIdxKey is used and intKey
51621 ** is ignored.
51623 ** If an exact match is not found, then the cursor is always
51624 ** left pointing at a leaf page which would hold the entry if it
51625 ** were present. The cursor might point to an entry that comes
51626 ** before or after the key.
51628 ** An integer is written into *pRes which is the result of
51629 ** comparing the key with the entry to which the cursor is
51630 ** pointing. The meaning of the integer written into
51631 ** *pRes is as follows:
51633 ** *pRes<0 The cursor is left pointing at an entry that
51634 ** is smaller than intKey/pIdxKey or if the table is empty
51635 ** and the cursor is therefore left point to nothing.
51637 ** *pRes==0 The cursor is left pointing at an entry that
51638 ** exactly matches intKey/pIdxKey.
51640 ** *pRes>0 The cursor is left pointing at an entry that
51641 ** is larger than intKey/pIdxKey.
51644 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
51645 BtCursor *pCur, /* The cursor to be moved */
51646 UnpackedRecord *pIdxKey, /* Unpacked index key */
51647 i64 intKey, /* The table key */
51648 int biasRight, /* If true, bias the search to the high end */
51649 int *pRes /* Write search results here */
51651 int rc;
51653 assert( cursorHoldsMutex(pCur) );
51654 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51655 assert( pRes );
51656 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
51658 /* If the cursor is already positioned at the point we are trying
51659 ** to move to, then just return without doing any work */
51660 if( pCur->eState==CURSOR_VALID && pCur->validNKey
51661 && pCur->apPage[0]->intKey
51663 if( pCur->info.nKey==intKey ){
51664 *pRes = 0;
51665 return SQLITE_OK;
51667 if( pCur->atLast && pCur->info.nKey<intKey ){
51668 *pRes = -1;
51669 return SQLITE_OK;
51673 rc = moveToRoot(pCur);
51674 if( rc ){
51675 return rc;
51677 assert( pCur->apPage[pCur->iPage] );
51678 assert( pCur->apPage[pCur->iPage]->isInit );
51679 assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
51680 if( pCur->eState==CURSOR_INVALID ){
51681 *pRes = -1;
51682 assert( pCur->apPage[pCur->iPage]->nCell==0 );
51683 return SQLITE_OK;
51685 assert( pCur->apPage[0]->intKey || pIdxKey );
51686 for(;;){
51687 int lwr, upr;
51688 Pgno chldPg;
51689 MemPage *pPage = pCur->apPage[pCur->iPage];
51690 int c;
51692 /* pPage->nCell must be greater than zero. If this is the root-page
51693 ** the cursor would have been INVALID above and this for(;;) loop
51694 ** not run. If this is not the root-page, then the moveToChild() routine
51695 ** would have already detected db corruption. Similarly, pPage must
51696 ** be the right kind (index or table) of b-tree page. Otherwise
51697 ** a moveToChild() or moveToRoot() call would have detected corruption. */
51698 assert( pPage->nCell>0 );
51699 assert( pPage->intKey==(pIdxKey==0) );
51700 lwr = 0;
51701 upr = pPage->nCell-1;
51702 if( biasRight ){
51703 pCur->aiIdx[pCur->iPage] = (u16)upr;
51704 }else{
51705 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
51707 for(;;){
51708 int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
51709 u8 *pCell; /* Pointer to current cell in pPage */
51711 pCur->info.nSize = 0;
51712 pCell = findCell(pPage, idx) + pPage->childPtrSize;
51713 if( pPage->intKey ){
51714 i64 nCellKey;
51715 if( pPage->hasData ){
51716 u32 dummy;
51717 pCell += getVarint32(pCell, dummy);
51719 getVarint(pCell, (u64*)&nCellKey);
51720 if( nCellKey==intKey ){
51721 c = 0;
51722 }else if( nCellKey<intKey ){
51723 c = -1;
51724 }else{
51725 assert( nCellKey>intKey );
51726 c = +1;
51728 pCur->validNKey = 1;
51729 pCur->info.nKey = nCellKey;
51730 }else{
51731 /* The maximum supported page-size is 65536 bytes. This means that
51732 ** the maximum number of record bytes stored on an index B-Tree
51733 ** page is less than 16384 bytes and may be stored as a 2-byte
51734 ** varint. This information is used to attempt to avoid parsing
51735 ** the entire cell by checking for the cases where the record is
51736 ** stored entirely within the b-tree page by inspecting the first
51737 ** 2 bytes of the cell.
51739 int nCell = pCell[0];
51740 if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
51741 /* This branch runs if the record-size field of the cell is a
51742 ** single byte varint and the record fits entirely on the main
51743 ** b-tree page. */
51744 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
51745 }else if( !(pCell[1] & 0x80)
51746 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
51748 /* The record-size field is a 2 byte varint and the record
51749 ** fits entirely on the main b-tree page. */
51750 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
51751 }else{
51752 /* The record flows over onto one or more overflow pages. In
51753 ** this case the whole cell needs to be parsed, a buffer allocated
51754 ** and accessPayload() used to retrieve the record into the
51755 ** buffer before VdbeRecordCompare() can be called. */
51756 void *pCellKey;
51757 u8 * const pCellBody = pCell - pPage->childPtrSize;
51758 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
51759 nCell = (int)pCur->info.nKey;
51760 pCellKey = sqlite3Malloc( nCell );
51761 if( pCellKey==0 ){
51762 rc = SQLITE_NOMEM;
51763 goto moveto_finish;
51765 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
51766 if( rc ){
51767 sqlite3_free(pCellKey);
51768 goto moveto_finish;
51770 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
51771 sqlite3_free(pCellKey);
51774 if( c==0 ){
51775 if( pPage->intKey && !pPage->leaf ){
51776 lwr = idx;
51777 upr = lwr - 1;
51778 break;
51779 }else{
51780 *pRes = 0;
51781 rc = SQLITE_OK;
51782 goto moveto_finish;
51785 if( c<0 ){
51786 lwr = idx+1;
51787 }else{
51788 upr = idx-1;
51790 if( lwr>upr ){
51791 break;
51793 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
51795 assert( lwr==upr+1 );
51796 assert( pPage->isInit );
51797 if( pPage->leaf ){
51798 chldPg = 0;
51799 }else if( lwr>=pPage->nCell ){
51800 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51801 }else{
51802 chldPg = get4byte(findCell(pPage, lwr));
51804 if( chldPg==0 ){
51805 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51806 *pRes = c;
51807 rc = SQLITE_OK;
51808 goto moveto_finish;
51810 pCur->aiIdx[pCur->iPage] = (u16)lwr;
51811 pCur->info.nSize = 0;
51812 pCur->validNKey = 0;
51813 rc = moveToChild(pCur, chldPg);
51814 if( rc ) goto moveto_finish;
51816 moveto_finish:
51817 return rc;
51822 ** Return TRUE if the cursor is not pointing at an entry of the table.
51824 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
51825 ** past the last entry in the table or sqlite3BtreePrev() moves past
51826 ** the first entry. TRUE is also returned if the table is empty.
51828 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
51829 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
51830 ** have been deleted? This API will need to change to return an error code
51831 ** as well as the boolean result value.
51833 return (CURSOR_VALID!=pCur->eState);
51837 ** Advance the cursor to the next entry in the database. If
51838 ** successful then set *pRes=0. If the cursor
51839 ** was already pointing to the last entry in the database before
51840 ** this routine was called, then set *pRes=1.
51842 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
51843 int rc;
51844 int idx;
51845 MemPage *pPage;
51847 assert( cursorHoldsMutex(pCur) );
51848 rc = restoreCursorPosition(pCur);
51849 if( rc!=SQLITE_OK ){
51850 return rc;
51852 assert( pRes!=0 );
51853 if( CURSOR_INVALID==pCur->eState ){
51854 *pRes = 1;
51855 return SQLITE_OK;
51857 if( pCur->skipNext>0 ){
51858 pCur->skipNext = 0;
51859 *pRes = 0;
51860 return SQLITE_OK;
51862 pCur->skipNext = 0;
51864 pPage = pCur->apPage[pCur->iPage];
51865 idx = ++pCur->aiIdx[pCur->iPage];
51866 assert( pPage->isInit );
51867 assert( idx<=pPage->nCell );
51869 pCur->info.nSize = 0;
51870 pCur->validNKey = 0;
51871 if( idx>=pPage->nCell ){
51872 if( !pPage->leaf ){
51873 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
51874 if( rc ) return rc;
51875 rc = moveToLeftmost(pCur);
51876 *pRes = 0;
51877 return rc;
51880 if( pCur->iPage==0 ){
51881 *pRes = 1;
51882 pCur->eState = CURSOR_INVALID;
51883 return SQLITE_OK;
51885 moveToParent(pCur);
51886 pPage = pCur->apPage[pCur->iPage];
51887 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
51888 *pRes = 0;
51889 if( pPage->intKey ){
51890 rc = sqlite3BtreeNext(pCur, pRes);
51891 }else{
51892 rc = SQLITE_OK;
51894 return rc;
51896 *pRes = 0;
51897 if( pPage->leaf ){
51898 return SQLITE_OK;
51900 rc = moveToLeftmost(pCur);
51901 return rc;
51906 ** Step the cursor to the back to the previous entry in the database. If
51907 ** successful then set *pRes=0. If the cursor
51908 ** was already pointing to the first entry in the database before
51909 ** this routine was called, then set *pRes=1.
51911 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
51912 int rc;
51913 MemPage *pPage;
51915 assert( cursorHoldsMutex(pCur) );
51916 rc = restoreCursorPosition(pCur);
51917 if( rc!=SQLITE_OK ){
51918 return rc;
51920 pCur->atLast = 0;
51921 if( CURSOR_INVALID==pCur->eState ){
51922 *pRes = 1;
51923 return SQLITE_OK;
51925 if( pCur->skipNext<0 ){
51926 pCur->skipNext = 0;
51927 *pRes = 0;
51928 return SQLITE_OK;
51930 pCur->skipNext = 0;
51932 pPage = pCur->apPage[pCur->iPage];
51933 assert( pPage->isInit );
51934 if( !pPage->leaf ){
51935 int idx = pCur->aiIdx[pCur->iPage];
51936 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
51937 if( rc ){
51938 return rc;
51940 rc = moveToRightmost(pCur);
51941 }else{
51942 while( pCur->aiIdx[pCur->iPage]==0 ){
51943 if( pCur->iPage==0 ){
51944 pCur->eState = CURSOR_INVALID;
51945 *pRes = 1;
51946 return SQLITE_OK;
51948 moveToParent(pCur);
51950 pCur->info.nSize = 0;
51951 pCur->validNKey = 0;
51953 pCur->aiIdx[pCur->iPage]--;
51954 pPage = pCur->apPage[pCur->iPage];
51955 if( pPage->intKey && !pPage->leaf ){
51956 rc = sqlite3BtreePrevious(pCur, pRes);
51957 }else{
51958 rc = SQLITE_OK;
51961 *pRes = 0;
51962 return rc;
51966 ** Allocate a new page from the database file.
51968 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
51969 ** has already been called on the new page.) The new page has also
51970 ** been referenced and the calling routine is responsible for calling
51971 ** sqlite3PagerUnref() on the new page when it is done.
51973 ** SQLITE_OK is returned on success. Any other return value indicates
51974 ** an error. *ppPage and *pPgno are undefined in the event of an error.
51975 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
51977 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
51978 ** locate a page close to the page number "nearby". This can be used in an
51979 ** attempt to keep related pages close to each other in the database file,
51980 ** which in turn can make database access faster.
51982 ** If the "exact" parameter is not 0, and the page-number nearby exists
51983 ** anywhere on the free-list, then it is guarenteed to be returned. This
51984 ** is only used by auto-vacuum databases when allocating a new table.
51986 static int allocateBtreePage(
51987 BtShared *pBt,
51988 MemPage **ppPage,
51989 Pgno *pPgno,
51990 Pgno nearby,
51991 u8 exact
51993 MemPage *pPage1;
51994 int rc;
51995 u32 n; /* Number of pages on the freelist */
51996 u32 k; /* Number of leaves on the trunk of the freelist */
51997 MemPage *pTrunk = 0;
51998 MemPage *pPrevTrunk = 0;
51999 Pgno mxPage; /* Total size of the database file */
52001 assert( sqlite3_mutex_held(pBt->mutex) );
52002 pPage1 = pBt->pPage1;
52003 mxPage = btreePagecount(pBt);
52004 n = get4byte(&pPage1->aData[36]);
52005 testcase( n==mxPage-1 );
52006 if( n>=mxPage ){
52007 return SQLITE_CORRUPT_BKPT;
52009 if( n>0 ){
52010 /* There are pages on the freelist. Reuse one of those pages. */
52011 Pgno iTrunk;
52012 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
52014 /* If the 'exact' parameter was true and a query of the pointer-map
52015 ** shows that the page 'nearby' is somewhere on the free-list, then
52016 ** the entire-list will be searched for that page.
52018 #ifndef SQLITE_OMIT_AUTOVACUUM
52019 if( exact && nearby<=mxPage ){
52020 u8 eType;
52021 assert( nearby>0 );
52022 assert( pBt->autoVacuum );
52023 rc = ptrmapGet(pBt, nearby, &eType, 0);
52024 if( rc ) return rc;
52025 if( eType==PTRMAP_FREEPAGE ){
52026 searchList = 1;
52028 *pPgno = nearby;
52030 #endif
52032 /* Decrement the free-list count by 1. Set iTrunk to the index of the
52033 ** first free-list trunk page. iPrevTrunk is initially 1.
52035 rc = sqlite3PagerWrite(pPage1->pDbPage);
52036 if( rc ) return rc;
52037 put4byte(&pPage1->aData[36], n-1);
52039 /* The code within this loop is run only once if the 'searchList' variable
52040 ** is not true. Otherwise, it runs once for each trunk-page on the
52041 ** free-list until the page 'nearby' is located.
52043 do {
52044 pPrevTrunk = pTrunk;
52045 if( pPrevTrunk ){
52046 iTrunk = get4byte(&pPrevTrunk->aData[0]);
52047 }else{
52048 iTrunk = get4byte(&pPage1->aData[32]);
52050 testcase( iTrunk==mxPage );
52051 if( iTrunk>mxPage ){
52052 rc = SQLITE_CORRUPT_BKPT;
52053 }else{
52054 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
52056 if( rc ){
52057 pTrunk = 0;
52058 goto end_allocate_page;
52061 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
52062 if( k==0 && !searchList ){
52063 /* The trunk has no leaves and the list is not being searched.
52064 ** So extract the trunk page itself and use it as the newly
52065 ** allocated page */
52066 assert( pPrevTrunk==0 );
52067 rc = sqlite3PagerWrite(pTrunk->pDbPage);
52068 if( rc ){
52069 goto end_allocate_page;
52071 *pPgno = iTrunk;
52072 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
52073 *ppPage = pTrunk;
52074 pTrunk = 0;
52075 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
52076 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
52077 /* Value of k is out of range. Database corruption */
52078 rc = SQLITE_CORRUPT_BKPT;
52079 goto end_allocate_page;
52080 #ifndef SQLITE_OMIT_AUTOVACUUM
52081 }else if( searchList && nearby==iTrunk ){
52082 /* The list is being searched and this trunk page is the page
52083 ** to allocate, regardless of whether it has leaves.
52085 assert( *pPgno==iTrunk );
52086 *ppPage = pTrunk;
52087 searchList = 0;
52088 rc = sqlite3PagerWrite(pTrunk->pDbPage);
52089 if( rc ){
52090 goto end_allocate_page;
52092 if( k==0 ){
52093 if( !pPrevTrunk ){
52094 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
52095 }else{
52096 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
52097 if( rc!=SQLITE_OK ){
52098 goto end_allocate_page;
52100 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
52102 }else{
52103 /* The trunk page is required by the caller but it contains
52104 ** pointers to free-list leaves. The first leaf becomes a trunk
52105 ** page in this case.
52107 MemPage *pNewTrunk;
52108 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
52109 if( iNewTrunk>mxPage ){
52110 rc = SQLITE_CORRUPT_BKPT;
52111 goto end_allocate_page;
52113 testcase( iNewTrunk==mxPage );
52114 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
52115 if( rc!=SQLITE_OK ){
52116 goto end_allocate_page;
52118 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
52119 if( rc!=SQLITE_OK ){
52120 releasePage(pNewTrunk);
52121 goto end_allocate_page;
52123 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
52124 put4byte(&pNewTrunk->aData[4], k-1);
52125 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
52126 releasePage(pNewTrunk);
52127 if( !pPrevTrunk ){
52128 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
52129 put4byte(&pPage1->aData[32], iNewTrunk);
52130 }else{
52131 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
52132 if( rc ){
52133 goto end_allocate_page;
52135 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
52138 pTrunk = 0;
52139 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
52140 #endif
52141 }else if( k>0 ){
52142 /* Extract a leaf from the trunk */
52143 u32 closest;
52144 Pgno iPage;
52145 unsigned char *aData = pTrunk->aData;
52146 if( nearby>0 ){
52147 u32 i;
52148 int dist;
52149 closest = 0;
52150 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
52151 for(i=1; i<k; i++){
52152 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
52153 if( d2<dist ){
52154 closest = i;
52155 dist = d2;
52158 }else{
52159 closest = 0;
52162 iPage = get4byte(&aData[8+closest*4]);
52163 testcase( iPage==mxPage );
52164 if( iPage>mxPage ){
52165 rc = SQLITE_CORRUPT_BKPT;
52166 goto end_allocate_page;
52168 testcase( iPage==mxPage );
52169 if( !searchList || iPage==nearby ){
52170 int noContent;
52171 *pPgno = iPage;
52172 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
52173 ": %d more free pages\n",
52174 *pPgno, closest+1, k, pTrunk->pgno, n-1));
52175 rc = sqlite3PagerWrite(pTrunk->pDbPage);
52176 if( rc ) goto end_allocate_page;
52177 if( closest<k-1 ){
52178 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
52180 put4byte(&aData[4], k-1);
52181 noContent = !btreeGetHasContent(pBt, *pPgno);
52182 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
52183 if( rc==SQLITE_OK ){
52184 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
52185 if( rc!=SQLITE_OK ){
52186 releasePage(*ppPage);
52189 searchList = 0;
52192 releasePage(pPrevTrunk);
52193 pPrevTrunk = 0;
52194 }while( searchList );
52195 }else{
52196 /* There are no pages on the freelist, so create a new page at the
52197 ** end of the file */
52198 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52199 if( rc ) return rc;
52200 pBt->nPage++;
52201 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
52203 #ifndef SQLITE_OMIT_AUTOVACUUM
52204 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
52205 /* If *pPgno refers to a pointer-map page, allocate two new pages
52206 ** at the end of the file instead of one. The first allocated page
52207 ** becomes a new pointer-map page, the second is used by the caller.
52209 MemPage *pPg = 0;
52210 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
52211 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
52212 rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
52213 if( rc==SQLITE_OK ){
52214 rc = sqlite3PagerWrite(pPg->pDbPage);
52215 releasePage(pPg);
52217 if( rc ) return rc;
52218 pBt->nPage++;
52219 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
52221 #endif
52222 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
52223 *pPgno = pBt->nPage;
52225 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
52226 rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
52227 if( rc ) return rc;
52228 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
52229 if( rc!=SQLITE_OK ){
52230 releasePage(*ppPage);
52232 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
52235 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
52237 end_allocate_page:
52238 releasePage(pTrunk);
52239 releasePage(pPrevTrunk);
52240 if( rc==SQLITE_OK ){
52241 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
52242 releasePage(*ppPage);
52243 return SQLITE_CORRUPT_BKPT;
52245 (*ppPage)->isInit = 0;
52246 }else{
52247 *ppPage = 0;
52249 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
52250 return rc;
52254 ** This function is used to add page iPage to the database file free-list.
52255 ** It is assumed that the page is not already a part of the free-list.
52257 ** The value passed as the second argument to this function is optional.
52258 ** If the caller happens to have a pointer to the MemPage object
52259 ** corresponding to page iPage handy, it may pass it as the second value.
52260 ** Otherwise, it may pass NULL.
52262 ** If a pointer to a MemPage object is passed as the second argument,
52263 ** its reference count is not altered by this function.
52265 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
52266 MemPage *pTrunk = 0; /* Free-list trunk page */
52267 Pgno iTrunk = 0; /* Page number of free-list trunk page */
52268 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
52269 MemPage *pPage; /* Page being freed. May be NULL. */
52270 int rc; /* Return Code */
52271 int nFree; /* Initial number of pages on free-list */
52273 assert( sqlite3_mutex_held(pBt->mutex) );
52274 assert( iPage>1 );
52275 assert( !pMemPage || pMemPage->pgno==iPage );
52277 if( pMemPage ){
52278 pPage = pMemPage;
52279 sqlite3PagerRef(pPage->pDbPage);
52280 }else{
52281 pPage = btreePageLookup(pBt, iPage);
52284 /* Increment the free page count on pPage1 */
52285 rc = sqlite3PagerWrite(pPage1->pDbPage);
52286 if( rc ) goto freepage_out;
52287 nFree = get4byte(&pPage1->aData[36]);
52288 put4byte(&pPage1->aData[36], nFree+1);
52290 if( pBt->secureDelete ){
52291 /* If the secure_delete option is enabled, then
52292 ** always fully overwrite deleted information with zeros.
52294 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
52295 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
52297 goto freepage_out;
52299 memset(pPage->aData, 0, pPage->pBt->pageSize);
52302 /* If the database supports auto-vacuum, write an entry in the pointer-map
52303 ** to indicate that the page is free.
52305 if( ISAUTOVACUUM ){
52306 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
52307 if( rc ) goto freepage_out;
52310 /* Now manipulate the actual database free-list structure. There are two
52311 ** possibilities. If the free-list is currently empty, or if the first
52312 ** trunk page in the free-list is full, then this page will become a
52313 ** new free-list trunk page. Otherwise, it will become a leaf of the
52314 ** first trunk page in the current free-list. This block tests if it
52315 ** is possible to add the page as a new free-list leaf.
52317 if( nFree!=0 ){
52318 u32 nLeaf; /* Initial number of leaf cells on trunk page */
52320 iTrunk = get4byte(&pPage1->aData[32]);
52321 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
52322 if( rc!=SQLITE_OK ){
52323 goto freepage_out;
52326 nLeaf = get4byte(&pTrunk->aData[4]);
52327 assert( pBt->usableSize>32 );
52328 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
52329 rc = SQLITE_CORRUPT_BKPT;
52330 goto freepage_out;
52332 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
52333 /* In this case there is room on the trunk page to insert the page
52334 ** being freed as a new leaf.
52336 ** Note that the trunk page is not really full until it contains
52337 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
52338 ** coded. But due to a coding error in versions of SQLite prior to
52339 ** 3.6.0, databases with freelist trunk pages holding more than
52340 ** usableSize/4 - 8 entries will be reported as corrupt. In order
52341 ** to maintain backwards compatibility with older versions of SQLite,
52342 ** we will continue to restrict the number of entries to usableSize/4 - 8
52343 ** for now. At some point in the future (once everyone has upgraded
52344 ** to 3.6.0 or later) we should consider fixing the conditional above
52345 ** to read "usableSize/4-2" instead of "usableSize/4-8".
52347 rc = sqlite3PagerWrite(pTrunk->pDbPage);
52348 if( rc==SQLITE_OK ){
52349 put4byte(&pTrunk->aData[4], nLeaf+1);
52350 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
52351 if( pPage && !pBt->secureDelete ){
52352 sqlite3PagerDontWrite(pPage->pDbPage);
52354 rc = btreeSetHasContent(pBt, iPage);
52356 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
52357 goto freepage_out;
52361 /* If control flows to this point, then it was not possible to add the
52362 ** the page being freed as a leaf page of the first trunk in the free-list.
52363 ** Possibly because the free-list is empty, or possibly because the
52364 ** first trunk in the free-list is full. Either way, the page being freed
52365 ** will become the new first trunk page in the free-list.
52367 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
52368 goto freepage_out;
52370 rc = sqlite3PagerWrite(pPage->pDbPage);
52371 if( rc!=SQLITE_OK ){
52372 goto freepage_out;
52374 put4byte(pPage->aData, iTrunk);
52375 put4byte(&pPage->aData[4], 0);
52376 put4byte(&pPage1->aData[32], iPage);
52377 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
52379 freepage_out:
52380 if( pPage ){
52381 pPage->isInit = 0;
52383 releasePage(pPage);
52384 releasePage(pTrunk);
52385 return rc;
52387 static void freePage(MemPage *pPage, int *pRC){
52388 if( (*pRC)==SQLITE_OK ){
52389 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
52394 ** Free any overflow pages associated with the given Cell.
52396 static int clearCell(MemPage *pPage, unsigned char *pCell){
52397 BtShared *pBt = pPage->pBt;
52398 CellInfo info;
52399 Pgno ovflPgno;
52400 int rc;
52401 int nOvfl;
52402 u32 ovflPageSize;
52404 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52405 btreeParseCellPtr(pPage, pCell, &info);
52406 if( info.iOverflow==0 ){
52407 return SQLITE_OK; /* No overflow pages. Return without doing anything */
52409 ovflPgno = get4byte(&pCell[info.iOverflow]);
52410 assert( pBt->usableSize > 4 );
52411 ovflPageSize = pBt->usableSize - 4;
52412 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
52413 assert( ovflPgno==0 || nOvfl>0 );
52414 while( nOvfl-- ){
52415 Pgno iNext = 0;
52416 MemPage *pOvfl = 0;
52417 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
52418 /* 0 is not a legal page number and page 1 cannot be an
52419 ** overflow page. Therefore if ovflPgno<2 or past the end of the
52420 ** file the database must be corrupt. */
52421 return SQLITE_CORRUPT_BKPT;
52423 if( nOvfl ){
52424 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
52425 if( rc ) return rc;
52428 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
52429 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
52431 /* There is no reason any cursor should have an outstanding reference
52432 ** to an overflow page belonging to a cell that is being deleted/updated.
52433 ** So if there exists more than one reference to this page, then it
52434 ** must not really be an overflow page and the database must be corrupt.
52435 ** It is helpful to detect this before calling freePage2(), as
52436 ** freePage2() may zero the page contents if secure-delete mode is
52437 ** enabled. If this 'overflow' page happens to be a page that the
52438 ** caller is iterating through or using in some other way, this
52439 ** can be problematic.
52441 rc = SQLITE_CORRUPT_BKPT;
52442 }else{
52443 rc = freePage2(pBt, pOvfl, ovflPgno);
52446 if( pOvfl ){
52447 sqlite3PagerUnref(pOvfl->pDbPage);
52449 if( rc ) return rc;
52450 ovflPgno = iNext;
52452 return SQLITE_OK;
52456 ** Create the byte sequence used to represent a cell on page pPage
52457 ** and write that byte sequence into pCell[]. Overflow pages are
52458 ** allocated and filled in as necessary. The calling procedure
52459 ** is responsible for making sure sufficient space has been allocated
52460 ** for pCell[].
52462 ** Note that pCell does not necessary need to point to the pPage->aData
52463 ** area. pCell might point to some temporary storage. The cell will
52464 ** be constructed in this temporary area then copied into pPage->aData
52465 ** later.
52467 static int fillInCell(
52468 MemPage *pPage, /* The page that contains the cell */
52469 unsigned char *pCell, /* Complete text of the cell */
52470 const void *pKey, i64 nKey, /* The key */
52471 const void *pData,int nData, /* The data */
52472 int nZero, /* Extra zero bytes to append to pData */
52473 int *pnSize /* Write cell size here */
52475 int nPayload;
52476 const u8 *pSrc;
52477 int nSrc, n, rc;
52478 int spaceLeft;
52479 MemPage *pOvfl = 0;
52480 MemPage *pToRelease = 0;
52481 unsigned char *pPrior;
52482 unsigned char *pPayload;
52483 BtShared *pBt = pPage->pBt;
52484 Pgno pgnoOvfl = 0;
52485 int nHeader;
52486 CellInfo info;
52488 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52490 /* pPage is not necessarily writeable since pCell might be auxiliary
52491 ** buffer space that is separate from the pPage buffer area */
52492 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
52493 || sqlite3PagerIswriteable(pPage->pDbPage) );
52495 /* Fill in the header. */
52496 nHeader = 0;
52497 if( !pPage->leaf ){
52498 nHeader += 4;
52500 if( pPage->hasData ){
52501 nHeader += putVarint(&pCell[nHeader], nData+nZero);
52502 }else{
52503 nData = nZero = 0;
52505 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
52506 btreeParseCellPtr(pPage, pCell, &info);
52507 assert( info.nHeader==nHeader );
52508 assert( info.nKey==nKey );
52509 assert( info.nData==(u32)(nData+nZero) );
52511 /* Fill in the payload */
52512 nPayload = nData + nZero;
52513 if( pPage->intKey ){
52514 pSrc = pData;
52515 nSrc = nData;
52516 nData = 0;
52517 }else{
52518 if( NEVER(nKey>0x7fffffff || pKey==0) ){
52519 return SQLITE_CORRUPT_BKPT;
52521 nPayload += (int)nKey;
52522 pSrc = pKey;
52523 nSrc = (int)nKey;
52525 *pnSize = info.nSize;
52526 spaceLeft = info.nLocal;
52527 pPayload = &pCell[nHeader];
52528 pPrior = &pCell[info.iOverflow];
52530 while( nPayload>0 ){
52531 if( spaceLeft==0 ){
52532 #ifndef SQLITE_OMIT_AUTOVACUUM
52533 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
52534 if( pBt->autoVacuum ){
52536 pgnoOvfl++;
52537 } while(
52538 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
52541 #endif
52542 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
52543 #ifndef SQLITE_OMIT_AUTOVACUUM
52544 /* If the database supports auto-vacuum, and the second or subsequent
52545 ** overflow page is being allocated, add an entry to the pointer-map
52546 ** for that page now.
52548 ** If this is the first overflow page, then write a partial entry
52549 ** to the pointer-map. If we write nothing to this pointer-map slot,
52550 ** then the optimistic overflow chain processing in clearCell()
52551 ** may misinterpret the uninitialised values and delete the
52552 ** wrong pages from the database.
52554 if( pBt->autoVacuum && rc==SQLITE_OK ){
52555 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
52556 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
52557 if( rc ){
52558 releasePage(pOvfl);
52561 #endif
52562 if( rc ){
52563 releasePage(pToRelease);
52564 return rc;
52567 /* If pToRelease is not zero than pPrior points into the data area
52568 ** of pToRelease. Make sure pToRelease is still writeable. */
52569 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52571 /* If pPrior is part of the data area of pPage, then make sure pPage
52572 ** is still writeable */
52573 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
52574 || sqlite3PagerIswriteable(pPage->pDbPage) );
52576 put4byte(pPrior, pgnoOvfl);
52577 releasePage(pToRelease);
52578 pToRelease = pOvfl;
52579 pPrior = pOvfl->aData;
52580 put4byte(pPrior, 0);
52581 pPayload = &pOvfl->aData[4];
52582 spaceLeft = pBt->usableSize - 4;
52584 n = nPayload;
52585 if( n>spaceLeft ) n = spaceLeft;
52587 /* If pToRelease is not zero than pPayload points into the data area
52588 ** of pToRelease. Make sure pToRelease is still writeable. */
52589 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52591 /* If pPayload is part of the data area of pPage, then make sure pPage
52592 ** is still writeable */
52593 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
52594 || sqlite3PagerIswriteable(pPage->pDbPage) );
52596 if( nSrc>0 ){
52597 if( n>nSrc ) n = nSrc;
52598 assert( pSrc );
52599 memcpy(pPayload, pSrc, n);
52600 }else{
52601 memset(pPayload, 0, n);
52603 nPayload -= n;
52604 pPayload += n;
52605 pSrc += n;
52606 nSrc -= n;
52607 spaceLeft -= n;
52608 if( nSrc==0 ){
52609 nSrc = nData;
52610 pSrc = pData;
52613 releasePage(pToRelease);
52614 return SQLITE_OK;
52618 ** Remove the i-th cell from pPage. This routine effects pPage only.
52619 ** The cell content is not freed or deallocated. It is assumed that
52620 ** the cell content has been copied someplace else. This routine just
52621 ** removes the reference to the cell from pPage.
52623 ** "sz" must be the number of bytes in the cell.
52625 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
52626 int i; /* Loop counter */
52627 u32 pc; /* Offset to cell content of cell being deleted */
52628 u8 *data; /* pPage->aData */
52629 u8 *ptr; /* Used to move bytes around within data[] */
52630 int rc; /* The return code */
52631 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
52633 if( *pRC ) return;
52635 assert( idx>=0 && idx<pPage->nCell );
52636 assert( sz==cellSize(pPage, idx) );
52637 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52638 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52639 data = pPage->aData;
52640 ptr = &data[pPage->cellOffset + 2*idx];
52641 pc = get2byte(ptr);
52642 hdr = pPage->hdrOffset;
52643 testcase( pc==get2byte(&data[hdr+5]) );
52644 testcase( pc+sz==pPage->pBt->usableSize );
52645 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
52646 *pRC = SQLITE_CORRUPT_BKPT;
52647 return;
52649 rc = freeSpace(pPage, pc, sz);
52650 if( rc ){
52651 *pRC = rc;
52652 return;
52654 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
52655 ptr[0] = ptr[2];
52656 ptr[1] = ptr[3];
52658 pPage->nCell--;
52659 put2byte(&data[hdr+3], pPage->nCell);
52660 pPage->nFree += 2;
52664 ** Insert a new cell on pPage at cell index "i". pCell points to the
52665 ** content of the cell.
52667 ** If the cell content will fit on the page, then put it there. If it
52668 ** will not fit, then make a copy of the cell content into pTemp if
52669 ** pTemp is not null. Regardless of pTemp, allocate a new entry
52670 ** in pPage->aOvfl[] and make it point to the cell content (either
52671 ** in pTemp or the original pCell) and also record its index.
52672 ** Allocating a new entry in pPage->aCell[] implies that
52673 ** pPage->nOverflow is incremented.
52675 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
52676 ** cell. The caller will overwrite them after this function returns. If
52677 ** nSkip is non-zero, then pCell may not point to an invalid memory location
52678 ** (but pCell+nSkip is always valid).
52680 static void insertCell(
52681 MemPage *pPage, /* Page into which we are copying */
52682 int i, /* New cell becomes the i-th cell of the page */
52683 u8 *pCell, /* Content of the new cell */
52684 int sz, /* Bytes of content in pCell */
52685 u8 *pTemp, /* Temp storage space for pCell, if needed */
52686 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
52687 int *pRC /* Read and write return code from here */
52689 int idx = 0; /* Where to write new cell content in data[] */
52690 int j; /* Loop counter */
52691 int end; /* First byte past the last cell pointer in data[] */
52692 int ins; /* Index in data[] where new cell pointer is inserted */
52693 int cellOffset; /* Address of first cell pointer in data[] */
52694 u8 *data; /* The content of the whole page */
52695 u8 *ptr; /* Used for moving information around in data[] */
52697 int nSkip = (iChild ? 4 : 0);
52699 if( *pRC ) return;
52701 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
52702 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
52703 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
52704 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52705 /* The cell should normally be sized correctly. However, when moving a
52706 ** malformed cell from a leaf page to an interior page, if the cell size
52707 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
52708 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
52709 ** the term after the || in the following assert(). */
52710 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
52711 if( pPage->nOverflow || sz+2>pPage->nFree ){
52712 if( pTemp ){
52713 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
52714 pCell = pTemp;
52716 if( iChild ){
52717 put4byte(pCell, iChild);
52719 j = pPage->nOverflow++;
52720 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
52721 pPage->aOvfl[j].pCell = pCell;
52722 pPage->aOvfl[j].idx = (u16)i;
52723 }else{
52724 int rc = sqlite3PagerWrite(pPage->pDbPage);
52725 if( rc!=SQLITE_OK ){
52726 *pRC = rc;
52727 return;
52729 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52730 data = pPage->aData;
52731 cellOffset = pPage->cellOffset;
52732 end = cellOffset + 2*pPage->nCell;
52733 ins = cellOffset + 2*i;
52734 rc = allocateSpace(pPage, sz, &idx);
52735 if( rc ){ *pRC = rc; return; }
52736 /* The allocateSpace() routine guarantees the following two properties
52737 ** if it returns success */
52738 assert( idx >= end+2 );
52739 assert( idx+sz <= (int)pPage->pBt->usableSize );
52740 pPage->nCell++;
52741 pPage->nFree -= (u16)(2 + sz);
52742 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
52743 if( iChild ){
52744 put4byte(&data[idx], iChild);
52746 for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
52747 ptr[0] = ptr[-2];
52748 ptr[1] = ptr[-1];
52750 put2byte(&data[ins], idx);
52751 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
52752 #ifndef SQLITE_OMIT_AUTOVACUUM
52753 if( pPage->pBt->autoVacuum ){
52754 /* The cell may contain a pointer to an overflow page. If so, write
52755 ** the entry for the overflow page into the pointer map.
52757 ptrmapPutOvflPtr(pPage, pCell, pRC);
52759 #endif
52764 ** Add a list of cells to a page. The page should be initially empty.
52765 ** The cells are guaranteed to fit on the page.
52767 static void assemblePage(
52768 MemPage *pPage, /* The page to be assemblied */
52769 int nCell, /* The number of cells to add to this page */
52770 u8 **apCell, /* Pointers to cell bodies */
52771 u16 *aSize /* Sizes of the cells */
52773 int i; /* Loop counter */
52774 u8 *pCellptr; /* Address of next cell pointer */
52775 int cellbody; /* Address of next cell body */
52776 u8 * const data = pPage->aData; /* Pointer to data for pPage */
52777 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
52778 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
52780 assert( pPage->nOverflow==0 );
52781 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52782 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
52783 && (int)MX_CELL(pPage->pBt)<=10921);
52784 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52786 /* Check that the page has just been zeroed by zeroPage() */
52787 assert( pPage->nCell==0 );
52788 assert( get2byteNotZero(&data[hdr+5])==nUsable );
52790 pCellptr = &data[pPage->cellOffset + nCell*2];
52791 cellbody = nUsable;
52792 for(i=nCell-1; i>=0; i--){
52793 pCellptr -= 2;
52794 cellbody -= aSize[i];
52795 put2byte(pCellptr, cellbody);
52796 memcpy(&data[cellbody], apCell[i], aSize[i]);
52798 put2byte(&data[hdr+3], nCell);
52799 put2byte(&data[hdr+5], cellbody);
52800 pPage->nFree -= (nCell*2 + nUsable - cellbody);
52801 pPage->nCell = (u16)nCell;
52805 ** The following parameters determine how many adjacent pages get involved
52806 ** in a balancing operation. NN is the number of neighbors on either side
52807 ** of the page that participate in the balancing operation. NB is the
52808 ** total number of pages that participate, including the target page and
52809 ** NN neighbors on either side.
52811 ** The minimum value of NN is 1 (of course). Increasing NN above 1
52812 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
52813 ** in exchange for a larger degradation in INSERT and UPDATE performance.
52814 ** The value of NN appears to give the best results overall.
52816 #define NN 1 /* Number of neighbors on either side of pPage */
52817 #define NB (NN*2+1) /* Total pages involved in the balance */
52820 #ifndef SQLITE_OMIT_QUICKBALANCE
52822 ** This version of balance() handles the common special case where
52823 ** a new entry is being inserted on the extreme right-end of the
52824 ** tree, in other words, when the new entry will become the largest
52825 ** entry in the tree.
52827 ** Instead of trying to balance the 3 right-most leaf pages, just add
52828 ** a new page to the right-hand side and put the one new entry in
52829 ** that page. This leaves the right side of the tree somewhat
52830 ** unbalanced. But odds are that we will be inserting new entries
52831 ** at the end soon afterwards so the nearly empty page will quickly
52832 ** fill up. On average.
52834 ** pPage is the leaf page which is the right-most page in the tree.
52835 ** pParent is its parent. pPage must have a single overflow entry
52836 ** which is also the right-most entry on the page.
52838 ** The pSpace buffer is used to store a temporary copy of the divider
52839 ** cell that will be inserted into pParent. Such a cell consists of a 4
52840 ** byte page number followed by a variable length integer. In other
52841 ** words, at most 13 bytes. Hence the pSpace buffer must be at
52842 ** least 13 bytes in size.
52844 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
52845 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
52846 MemPage *pNew; /* Newly allocated page */
52847 int rc; /* Return Code */
52848 Pgno pgnoNew; /* Page number of pNew */
52850 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52851 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
52852 assert( pPage->nOverflow==1 );
52854 /* This error condition is now caught prior to reaching this function */
52855 if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
52857 /* Allocate a new page. This page will become the right-sibling of
52858 ** pPage. Make the parent page writable, so that the new divider cell
52859 ** may be inserted. If both these operations are successful, proceed.
52861 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
52863 if( rc==SQLITE_OK ){
52865 u8 *pOut = &pSpace[4];
52866 u8 *pCell = pPage->aOvfl[0].pCell;
52867 u16 szCell = cellSizePtr(pPage, pCell);
52868 u8 *pStop;
52870 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
52871 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
52872 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
52873 assemblePage(pNew, 1, &pCell, &szCell);
52875 /* If this is an auto-vacuum database, update the pointer map
52876 ** with entries for the new page, and any pointer from the
52877 ** cell on the page to an overflow page. If either of these
52878 ** operations fails, the return code is set, but the contents
52879 ** of the parent page are still manipulated by thh code below.
52880 ** That is Ok, at this point the parent page is guaranteed to
52881 ** be marked as dirty. Returning an error code will cause a
52882 ** rollback, undoing any changes made to the parent page.
52884 if( ISAUTOVACUUM ){
52885 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
52886 if( szCell>pNew->minLocal ){
52887 ptrmapPutOvflPtr(pNew, pCell, &rc);
52891 /* Create a divider cell to insert into pParent. The divider cell
52892 ** consists of a 4-byte page number (the page number of pPage) and
52893 ** a variable length key value (which must be the same value as the
52894 ** largest key on pPage).
52896 ** To find the largest key value on pPage, first find the right-most
52897 ** cell on pPage. The first two fields of this cell are the
52898 ** record-length (a variable length integer at most 32-bits in size)
52899 ** and the key value (a variable length integer, may have any value).
52900 ** The first of the while(...) loops below skips over the record-length
52901 ** field. The second while(...) loop copies the key value from the
52902 ** cell on pPage into the pSpace buffer.
52904 pCell = findCell(pPage, pPage->nCell-1);
52905 pStop = &pCell[9];
52906 while( (*(pCell++)&0x80) && pCell<pStop );
52907 pStop = &pCell[9];
52908 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
52910 /* Insert the new divider cell into pParent. */
52911 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
52912 0, pPage->pgno, &rc);
52914 /* Set the right-child pointer of pParent to point to the new page. */
52915 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
52917 /* Release the reference to the new page. */
52918 releasePage(pNew);
52921 return rc;
52923 #endif /* SQLITE_OMIT_QUICKBALANCE */
52925 #if 0
52927 ** This function does not contribute anything to the operation of SQLite.
52928 ** it is sometimes activated temporarily while debugging code responsible
52929 ** for setting pointer-map entries.
52931 static int ptrmapCheckPages(MemPage **apPage, int nPage){
52932 int i, j;
52933 for(i=0; i<nPage; i++){
52934 Pgno n;
52935 u8 e;
52936 MemPage *pPage = apPage[i];
52937 BtShared *pBt = pPage->pBt;
52938 assert( pPage->isInit );
52940 for(j=0; j<pPage->nCell; j++){
52941 CellInfo info;
52942 u8 *z;
52944 z = findCell(pPage, j);
52945 btreeParseCellPtr(pPage, z, &info);
52946 if( info.iOverflow ){
52947 Pgno ovfl = get4byte(&z[info.iOverflow]);
52948 ptrmapGet(pBt, ovfl, &e, &n);
52949 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
52951 if( !pPage->leaf ){
52952 Pgno child = get4byte(z);
52953 ptrmapGet(pBt, child, &e, &n);
52954 assert( n==pPage->pgno && e==PTRMAP_BTREE );
52957 if( !pPage->leaf ){
52958 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52959 ptrmapGet(pBt, child, &e, &n);
52960 assert( n==pPage->pgno && e==PTRMAP_BTREE );
52963 return 1;
52965 #endif
52968 ** This function is used to copy the contents of the b-tree node stored
52969 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
52970 ** the pointer-map entries for each child page are updated so that the
52971 ** parent page stored in the pointer map is page pTo. If pFrom contained
52972 ** any cells with overflow page pointers, then the corresponding pointer
52973 ** map entries are also updated so that the parent page is page pTo.
52975 ** If pFrom is currently carrying any overflow cells (entries in the
52976 ** MemPage.aOvfl[] array), they are not copied to pTo.
52978 ** Before returning, page pTo is reinitialized using btreeInitPage().
52980 ** The performance of this function is not critical. It is only used by
52981 ** the balance_shallower() and balance_deeper() procedures, neither of
52982 ** which are called often under normal circumstances.
52984 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
52985 if( (*pRC)==SQLITE_OK ){
52986 BtShared * const pBt = pFrom->pBt;
52987 u8 * const aFrom = pFrom->aData;
52988 u8 * const aTo = pTo->aData;
52989 int const iFromHdr = pFrom->hdrOffset;
52990 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
52991 int rc;
52992 int iData;
52995 assert( pFrom->isInit );
52996 assert( pFrom->nFree>=iToHdr );
52997 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
52999 /* Copy the b-tree node content from page pFrom to page pTo. */
53000 iData = get2byte(&aFrom[iFromHdr+5]);
53001 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
53002 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
53004 /* Reinitialize page pTo so that the contents of the MemPage structure
53005 ** match the new data. The initialization of pTo can actually fail under
53006 ** fairly obscure circumstances, even though it is a copy of initialized
53007 ** page pFrom.
53009 pTo->isInit = 0;
53010 rc = btreeInitPage(pTo);
53011 if( rc!=SQLITE_OK ){
53012 *pRC = rc;
53013 return;
53016 /* If this is an auto-vacuum database, update the pointer-map entries
53017 ** for any b-tree or overflow pages that pTo now contains the pointers to.
53019 if( ISAUTOVACUUM ){
53020 *pRC = setChildPtrmaps(pTo);
53026 ** This routine redistributes cells on the iParentIdx'th child of pParent
53027 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
53028 ** same amount of free space. Usually a single sibling on either side of the
53029 ** page are used in the balancing, though both siblings might come from one
53030 ** side if the page is the first or last child of its parent. If the page
53031 ** has fewer than 2 siblings (something which can only happen if the page
53032 ** is a root page or a child of a root page) then all available siblings
53033 ** participate in the balancing.
53035 ** The number of siblings of the page might be increased or decreased by
53036 ** one or two in an effort to keep pages nearly full but not over full.
53038 ** Note that when this routine is called, some of the cells on the page
53039 ** might not actually be stored in MemPage.aData[]. This can happen
53040 ** if the page is overfull. This routine ensures that all cells allocated
53041 ** to the page and its siblings fit into MemPage.aData[] before returning.
53043 ** In the course of balancing the page and its siblings, cells may be
53044 ** inserted into or removed from the parent page (pParent). Doing so
53045 ** may cause the parent page to become overfull or underfull. If this
53046 ** happens, it is the responsibility of the caller to invoke the correct
53047 ** balancing routine to fix this problem (see the balance() routine).
53049 ** If this routine fails for any reason, it might leave the database
53050 ** in a corrupted state. So if this routine fails, the database should
53051 ** be rolled back.
53053 ** The third argument to this function, aOvflSpace, is a pointer to a
53054 ** buffer big enough to hold one page. If while inserting cells into the parent
53055 ** page (pParent) the parent page becomes overfull, this buffer is
53056 ** used to store the parent's overflow cells. Because this function inserts
53057 ** a maximum of four divider cells into the parent page, and the maximum
53058 ** size of a cell stored within an internal node is always less than 1/4
53059 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
53060 ** enough for all overflow cells.
53062 ** If aOvflSpace is set to a null pointer, this function returns
53063 ** SQLITE_NOMEM.
53065 static int balance_nonroot(
53066 MemPage *pParent, /* Parent page of siblings being balanced */
53067 int iParentIdx, /* Index of "the page" in pParent */
53068 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
53069 int isRoot /* True if pParent is a root-page */
53071 BtShared *pBt; /* The whole database */
53072 int nCell = 0; /* Number of cells in apCell[] */
53073 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
53074 int nNew = 0; /* Number of pages in apNew[] */
53075 int nOld; /* Number of pages in apOld[] */
53076 int i, j, k; /* Loop counters */
53077 int nxDiv; /* Next divider slot in pParent->aCell[] */
53078 int rc = SQLITE_OK; /* The return code */
53079 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
53080 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
53081 int usableSpace; /* Bytes in pPage beyond the header */
53082 int pageFlags; /* Value of pPage->aData[0] */
53083 int subtotal; /* Subtotal of bytes in cells on one page */
53084 int iSpace1 = 0; /* First unused byte of aSpace1[] */
53085 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
53086 int szScratch; /* Size of scratch memory requested */
53087 MemPage *apOld[NB]; /* pPage and up to two siblings */
53088 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
53089 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
53090 u8 *pRight; /* Location in parent of right-sibling pointer */
53091 u8 *apDiv[NB-1]; /* Divider cells in pParent */
53092 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
53093 int szNew[NB+2]; /* Combined size of cells place on i-th page */
53094 u8 **apCell = 0; /* All cells begin balanced */
53095 u16 *szCell; /* Local size of all cells in apCell[] */
53096 u8 *aSpace1; /* Space for copies of dividers cells */
53097 Pgno pgno; /* Temp var to store a page number in */
53099 pBt = pParent->pBt;
53100 assert( sqlite3_mutex_held(pBt->mutex) );
53101 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53103 #if 0
53104 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
53105 #endif
53107 /* At this point pParent may have at most one overflow cell. And if
53108 ** this overflow cell is present, it must be the cell with
53109 ** index iParentIdx. This scenario comes about when this function
53110 ** is called (indirectly) from sqlite3BtreeDelete().
53112 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
53113 assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
53115 if( !aOvflSpace ){
53116 return SQLITE_NOMEM;
53119 /* Find the sibling pages to balance. Also locate the cells in pParent
53120 ** that divide the siblings. An attempt is made to find NN siblings on
53121 ** either side of pPage. More siblings are taken from one side, however,
53122 ** if there are fewer than NN siblings on the other side. If pParent
53123 ** has NB or fewer children then all children of pParent are taken.
53125 ** This loop also drops the divider cells from the parent page. This
53126 ** way, the remainder of the function does not have to deal with any
53127 ** overflow cells in the parent page, since if any existed they will
53128 ** have already been removed.
53130 i = pParent->nOverflow + pParent->nCell;
53131 if( i<2 ){
53132 nxDiv = 0;
53133 nOld = i+1;
53134 }else{
53135 nOld = 3;
53136 if( iParentIdx==0 ){
53137 nxDiv = 0;
53138 }else if( iParentIdx==i ){
53139 nxDiv = i-2;
53140 }else{
53141 nxDiv = iParentIdx-1;
53143 i = 2;
53145 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
53146 pRight = &pParent->aData[pParent->hdrOffset+8];
53147 }else{
53148 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
53150 pgno = get4byte(pRight);
53151 while( 1 ){
53152 rc = getAndInitPage(pBt, pgno, &apOld[i]);
53153 if( rc ){
53154 memset(apOld, 0, (i+1)*sizeof(MemPage*));
53155 goto balance_cleanup;
53157 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
53158 if( (i--)==0 ) break;
53160 if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
53161 apDiv[i] = pParent->aOvfl[0].pCell;
53162 pgno = get4byte(apDiv[i]);
53163 szNew[i] = cellSizePtr(pParent, apDiv[i]);
53164 pParent->nOverflow = 0;
53165 }else{
53166 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
53167 pgno = get4byte(apDiv[i]);
53168 szNew[i] = cellSizePtr(pParent, apDiv[i]);
53170 /* Drop the cell from the parent page. apDiv[i] still points to
53171 ** the cell within the parent, even though it has been dropped.
53172 ** This is safe because dropping a cell only overwrites the first
53173 ** four bytes of it, and this function does not need the first
53174 ** four bytes of the divider cell. So the pointer is safe to use
53175 ** later on.
53177 ** Unless SQLite is compiled in secure-delete mode. In this case,
53178 ** the dropCell() routine will overwrite the entire cell with zeroes.
53179 ** In this case, temporarily copy the cell into the aOvflSpace[]
53180 ** buffer. It will be copied out again as soon as the aSpace[] buffer
53181 ** is allocated. */
53182 if( pBt->secureDelete ){
53183 int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
53184 if( (iOff+szNew[i])>(int)pBt->usableSize ){
53185 rc = SQLITE_CORRUPT_BKPT;
53186 memset(apOld, 0, (i+1)*sizeof(MemPage*));
53187 goto balance_cleanup;
53188 }else{
53189 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
53190 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
53193 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
53197 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
53198 ** alignment */
53199 nMaxCells = (nMaxCells + 3)&~3;
53202 ** Allocate space for memory structures
53204 k = pBt->pageSize + ROUND8(sizeof(MemPage));
53205 szScratch =
53206 nMaxCells*sizeof(u8*) /* apCell */
53207 + nMaxCells*sizeof(u16) /* szCell */
53208 + pBt->pageSize /* aSpace1 */
53209 + k*nOld; /* Page copies (apCopy) */
53210 apCell = sqlite3ScratchMalloc( szScratch );
53211 if( apCell==0 ){
53212 rc = SQLITE_NOMEM;
53213 goto balance_cleanup;
53215 szCell = (u16*)&apCell[nMaxCells];
53216 aSpace1 = (u8*)&szCell[nMaxCells];
53217 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
53220 ** Load pointers to all cells on sibling pages and the divider cells
53221 ** into the local apCell[] array. Make copies of the divider cells
53222 ** into space obtained from aSpace1[] and remove the the divider Cells
53223 ** from pParent.
53225 ** If the siblings are on leaf pages, then the child pointers of the
53226 ** divider cells are stripped from the cells before they are copied
53227 ** into aSpace1[]. In this way, all cells in apCell[] are without
53228 ** child pointers. If siblings are not leaves, then all cell in
53229 ** apCell[] include child pointers. Either way, all cells in apCell[]
53230 ** are alike.
53232 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
53233 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
53235 leafCorrection = apOld[0]->leaf*4;
53236 leafData = apOld[0]->hasData;
53237 for(i=0; i<nOld; i++){
53238 int limit;
53240 /* Before doing anything else, take a copy of the i'th original sibling
53241 ** The rest of this function will use data from the copies rather
53242 ** that the original pages since the original pages will be in the
53243 ** process of being overwritten. */
53244 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
53245 memcpy(pOld, apOld[i], sizeof(MemPage));
53246 pOld->aData = (void*)&pOld[1];
53247 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
53249 limit = pOld->nCell+pOld->nOverflow;
53250 for(j=0; j<limit; j++){
53251 assert( nCell<nMaxCells );
53252 apCell[nCell] = findOverflowCell(pOld, j);
53253 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
53254 nCell++;
53256 if( i<nOld-1 && !leafData){
53257 u16 sz = (u16)szNew[i];
53258 u8 *pTemp;
53259 assert( nCell<nMaxCells );
53260 szCell[nCell] = sz;
53261 pTemp = &aSpace1[iSpace1];
53262 iSpace1 += sz;
53263 assert( sz<=pBt->maxLocal+23 );
53264 assert( iSpace1 <= (int)pBt->pageSize );
53265 memcpy(pTemp, apDiv[i], sz);
53266 apCell[nCell] = pTemp+leafCorrection;
53267 assert( leafCorrection==0 || leafCorrection==4 );
53268 szCell[nCell] = szCell[nCell] - leafCorrection;
53269 if( !pOld->leaf ){
53270 assert( leafCorrection==0 );
53271 assert( pOld->hdrOffset==0 );
53272 /* The right pointer of the child page pOld becomes the left
53273 ** pointer of the divider cell */
53274 memcpy(apCell[nCell], &pOld->aData[8], 4);
53275 }else{
53276 assert( leafCorrection==4 );
53277 if( szCell[nCell]<4 ){
53278 /* Do not allow any cells smaller than 4 bytes. */
53279 szCell[nCell] = 4;
53282 nCell++;
53287 ** Figure out the number of pages needed to hold all nCell cells.
53288 ** Store this number in "k". Also compute szNew[] which is the total
53289 ** size of all cells on the i-th page and cntNew[] which is the index
53290 ** in apCell[] of the cell that divides page i from page i+1.
53291 ** cntNew[k] should equal nCell.
53293 ** Values computed by this block:
53295 ** k: The total number of sibling pages
53296 ** szNew[i]: Spaced used on the i-th sibling page.
53297 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
53298 ** the right of the i-th sibling page.
53299 ** usableSpace: Number of bytes of space available on each sibling.
53302 usableSpace = pBt->usableSize - 12 + leafCorrection;
53303 for(subtotal=k=i=0; i<nCell; i++){
53304 assert( i<nMaxCells );
53305 subtotal += szCell[i] + 2;
53306 if( subtotal > usableSpace ){
53307 szNew[k] = subtotal - szCell[i];
53308 cntNew[k] = i;
53309 if( leafData ){ i--; }
53310 subtotal = 0;
53311 k++;
53312 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
53315 szNew[k] = subtotal;
53316 cntNew[k] = nCell;
53317 k++;
53320 ** The packing computed by the previous block is biased toward the siblings
53321 ** on the left side. The left siblings are always nearly full, while the
53322 ** right-most sibling might be nearly empty. This block of code attempts
53323 ** to adjust the packing of siblings to get a better balance.
53325 ** This adjustment is more than an optimization. The packing above might
53326 ** be so out of balance as to be illegal. For example, the right-most
53327 ** sibling might be completely empty. This adjustment is not optional.
53329 for(i=k-1; i>0; i--){
53330 int szRight = szNew[i]; /* Size of sibling on the right */
53331 int szLeft = szNew[i-1]; /* Size of sibling on the left */
53332 int r; /* Index of right-most cell in left sibling */
53333 int d; /* Index of first cell to the left of right sibling */
53335 r = cntNew[i-1] - 1;
53336 d = r + 1 - leafData;
53337 assert( d<nMaxCells );
53338 assert( r<nMaxCells );
53339 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
53340 szRight += szCell[d] + 2;
53341 szLeft -= szCell[r] + 2;
53342 cntNew[i-1]--;
53343 r = cntNew[i-1] - 1;
53344 d = r + 1 - leafData;
53346 szNew[i] = szRight;
53347 szNew[i-1] = szLeft;
53350 /* Either we found one or more cells (cntnew[0])>0) or pPage is
53351 ** a virtual root page. A virtual root page is when the real root
53352 ** page is page 1 and we are the only child of that page.
53354 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
53356 TRACE(("BALANCE: old: %d %d %d ",
53357 apOld[0]->pgno,
53358 nOld>=2 ? apOld[1]->pgno : 0,
53359 nOld>=3 ? apOld[2]->pgno : 0
53363 ** Allocate k new pages. Reuse old pages where possible.
53365 if( apOld[0]->pgno<=1 ){
53366 rc = SQLITE_CORRUPT_BKPT;
53367 goto balance_cleanup;
53369 pageFlags = apOld[0]->aData[0];
53370 for(i=0; i<k; i++){
53371 MemPage *pNew;
53372 if( i<nOld ){
53373 pNew = apNew[i] = apOld[i];
53374 apOld[i] = 0;
53375 rc = sqlite3PagerWrite(pNew->pDbPage);
53376 nNew++;
53377 if( rc ) goto balance_cleanup;
53378 }else{
53379 assert( i>0 );
53380 rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
53381 if( rc ) goto balance_cleanup;
53382 apNew[i] = pNew;
53383 nNew++;
53385 /* Set the pointer-map entry for the new sibling page. */
53386 if( ISAUTOVACUUM ){
53387 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
53388 if( rc!=SQLITE_OK ){
53389 goto balance_cleanup;
53395 /* Free any old pages that were not reused as new pages.
53397 while( i<nOld ){
53398 freePage(apOld[i], &rc);
53399 if( rc ) goto balance_cleanup;
53400 releasePage(apOld[i]);
53401 apOld[i] = 0;
53402 i++;
53406 ** Put the new pages in accending order. This helps to
53407 ** keep entries in the disk file in order so that a scan
53408 ** of the table is a linear scan through the file. That
53409 ** in turn helps the operating system to deliver pages
53410 ** from the disk more rapidly.
53412 ** An O(n^2) insertion sort algorithm is used, but since
53413 ** n is never more than NB (a small constant), that should
53414 ** not be a problem.
53416 ** When NB==3, this one optimization makes the database
53417 ** about 25% faster for large insertions and deletions.
53419 for(i=0; i<k-1; i++){
53420 int minV = apNew[i]->pgno;
53421 int minI = i;
53422 for(j=i+1; j<k; j++){
53423 if( apNew[j]->pgno<(unsigned)minV ){
53424 minI = j;
53425 minV = apNew[j]->pgno;
53428 if( minI>i ){
53429 MemPage *pT;
53430 pT = apNew[i];
53431 apNew[i] = apNew[minI];
53432 apNew[minI] = pT;
53435 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
53436 apNew[0]->pgno, szNew[0],
53437 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
53438 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
53439 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
53440 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
53442 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53443 put4byte(pRight, apNew[nNew-1]->pgno);
53446 ** Evenly distribute the data in apCell[] across the new pages.
53447 ** Insert divider cells into pParent as necessary.
53449 j = 0;
53450 for(i=0; i<nNew; i++){
53451 /* Assemble the new sibling page. */
53452 MemPage *pNew = apNew[i];
53453 assert( j<nMaxCells );
53454 zeroPage(pNew, pageFlags);
53455 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
53456 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
53457 assert( pNew->nOverflow==0 );
53459 j = cntNew[i];
53461 /* If the sibling page assembled above was not the right-most sibling,
53462 ** insert a divider cell into the parent page.
53464 assert( i<nNew-1 || j==nCell );
53465 if( j<nCell ){
53466 u8 *pCell;
53467 u8 *pTemp;
53468 int sz;
53470 assert( j<nMaxCells );
53471 pCell = apCell[j];
53472 sz = szCell[j] + leafCorrection;
53473 pTemp = &aOvflSpace[iOvflSpace];
53474 if( !pNew->leaf ){
53475 memcpy(&pNew->aData[8], pCell, 4);
53476 }else if( leafData ){
53477 /* If the tree is a leaf-data tree, and the siblings are leaves,
53478 ** then there is no divider cell in apCell[]. Instead, the divider
53479 ** cell consists of the integer key for the right-most cell of
53480 ** the sibling-page assembled above only.
53482 CellInfo info;
53483 j--;
53484 btreeParseCellPtr(pNew, apCell[j], &info);
53485 pCell = pTemp;
53486 sz = 4 + putVarint(&pCell[4], info.nKey);
53487 pTemp = 0;
53488 }else{
53489 pCell -= 4;
53490 /* Obscure case for non-leaf-data trees: If the cell at pCell was
53491 ** previously stored on a leaf node, and its reported size was 4
53492 ** bytes, then it may actually be smaller than this
53493 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
53494 ** any cell). But it is important to pass the correct size to
53495 ** insertCell(), so reparse the cell now.
53497 ** Note that this can never happen in an SQLite data file, as all
53498 ** cells are at least 4 bytes. It only happens in b-trees used
53499 ** to evaluate "IN (SELECT ...)" and similar clauses.
53501 if( szCell[j]==4 ){
53502 assert(leafCorrection==4);
53503 sz = cellSizePtr(pParent, pCell);
53506 iOvflSpace += sz;
53507 assert( sz<=pBt->maxLocal+23 );
53508 assert( iOvflSpace <= (int)pBt->pageSize );
53509 insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
53510 if( rc!=SQLITE_OK ) goto balance_cleanup;
53511 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53513 j++;
53514 nxDiv++;
53517 assert( j==nCell );
53518 assert( nOld>0 );
53519 assert( nNew>0 );
53520 if( (pageFlags & PTF_LEAF)==0 ){
53521 u8 *zChild = &apCopy[nOld-1]->aData[8];
53522 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
53525 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
53526 /* The root page of the b-tree now contains no cells. The only sibling
53527 ** page is the right-child of the parent. Copy the contents of the
53528 ** child page into the parent, decreasing the overall height of the
53529 ** b-tree structure by one. This is described as the "balance-shallower"
53530 ** sub-algorithm in some documentation.
53532 ** If this is an auto-vacuum database, the call to copyNodeContent()
53533 ** sets all pointer-map entries corresponding to database image pages
53534 ** for which the pointer is stored within the content being copied.
53536 ** The second assert below verifies that the child page is defragmented
53537 ** (it must be, as it was just reconstructed using assemblePage()). This
53538 ** is important if the parent page happens to be page 1 of the database
53539 ** image. */
53540 assert( nNew==1 );
53541 assert( apNew[0]->nFree ==
53542 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
53544 copyNodeContent(apNew[0], pParent, &rc);
53545 freePage(apNew[0], &rc);
53546 }else if( ISAUTOVACUUM ){
53547 /* Fix the pointer-map entries for all the cells that were shifted around.
53548 ** There are several different types of pointer-map entries that need to
53549 ** be dealt with by this routine. Some of these have been set already, but
53550 ** many have not. The following is a summary:
53552 ** 1) The entries associated with new sibling pages that were not
53553 ** siblings when this function was called. These have already
53554 ** been set. We don't need to worry about old siblings that were
53555 ** moved to the free-list - the freePage() code has taken care
53556 ** of those.
53558 ** 2) The pointer-map entries associated with the first overflow
53559 ** page in any overflow chains used by new divider cells. These
53560 ** have also already been taken care of by the insertCell() code.
53562 ** 3) If the sibling pages are not leaves, then the child pages of
53563 ** cells stored on the sibling pages may need to be updated.
53565 ** 4) If the sibling pages are not internal intkey nodes, then any
53566 ** overflow pages used by these cells may need to be updated
53567 ** (internal intkey nodes never contain pointers to overflow pages).
53569 ** 5) If the sibling pages are not leaves, then the pointer-map
53570 ** entries for the right-child pages of each sibling may need
53571 ** to be updated.
53573 ** Cases 1 and 2 are dealt with above by other code. The next
53574 ** block deals with cases 3 and 4 and the one after that, case 5. Since
53575 ** setting a pointer map entry is a relatively expensive operation, this
53576 ** code only sets pointer map entries for child or overflow pages that have
53577 ** actually moved between pages. */
53578 MemPage *pNew = apNew[0];
53579 MemPage *pOld = apCopy[0];
53580 int nOverflow = pOld->nOverflow;
53581 int iNextOld = pOld->nCell + nOverflow;
53582 int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
53583 j = 0; /* Current 'old' sibling page */
53584 k = 0; /* Current 'new' sibling page */
53585 for(i=0; i<nCell; i++){
53586 int isDivider = 0;
53587 while( i==iNextOld ){
53588 /* Cell i is the cell immediately following the last cell on old
53589 ** sibling page j. If the siblings are not leaf pages of an
53590 ** intkey b-tree, then cell i was a divider cell. */
53591 pOld = apCopy[++j];
53592 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
53593 if( pOld->nOverflow ){
53594 nOverflow = pOld->nOverflow;
53595 iOverflow = i + !leafData + pOld->aOvfl[0].idx;
53597 isDivider = !leafData;
53600 assert(nOverflow>0 || iOverflow<i );
53601 assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
53602 assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
53603 if( i==iOverflow ){
53604 isDivider = 1;
53605 if( (--nOverflow)>0 ){
53606 iOverflow++;
53610 if( i==cntNew[k] ){
53611 /* Cell i is the cell immediately following the last cell on new
53612 ** sibling page k. If the siblings are not leaf pages of an
53613 ** intkey b-tree, then cell i is a divider cell. */
53614 pNew = apNew[++k];
53615 if( !leafData ) continue;
53617 assert( j<nOld );
53618 assert( k<nNew );
53620 /* If the cell was originally divider cell (and is not now) or
53621 ** an overflow cell, or if the cell was located on a different sibling
53622 ** page before the balancing, then the pointer map entries associated
53623 ** with any child or overflow pages need to be updated. */
53624 if( isDivider || pOld->pgno!=pNew->pgno ){
53625 if( !leafCorrection ){
53626 ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
53628 if( szCell[i]>pNew->minLocal ){
53629 ptrmapPutOvflPtr(pNew, apCell[i], &rc);
53634 if( !leafCorrection ){
53635 for(i=0; i<nNew; i++){
53636 u32 key = get4byte(&apNew[i]->aData[8]);
53637 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
53641 #if 0
53642 /* The ptrmapCheckPages() contains assert() statements that verify that
53643 ** all pointer map pages are set correctly. This is helpful while
53644 ** debugging. This is usually disabled because a corrupt database may
53645 ** cause an assert() statement to fail. */
53646 ptrmapCheckPages(apNew, nNew);
53647 ptrmapCheckPages(&pParent, 1);
53648 #endif
53651 assert( pParent->isInit );
53652 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
53653 nOld, nNew, nCell));
53656 ** Cleanup before returning.
53658 balance_cleanup:
53659 sqlite3ScratchFree(apCell);
53660 for(i=0; i<nOld; i++){
53661 releasePage(apOld[i]);
53663 for(i=0; i<nNew; i++){
53664 releasePage(apNew[i]);
53667 return rc;
53672 ** This function is called when the root page of a b-tree structure is
53673 ** overfull (has one or more overflow pages).
53675 ** A new child page is allocated and the contents of the current root
53676 ** page, including overflow cells, are copied into the child. The root
53677 ** page is then overwritten to make it an empty page with the right-child
53678 ** pointer pointing to the new page.
53680 ** Before returning, all pointer-map entries corresponding to pages
53681 ** that the new child-page now contains pointers to are updated. The
53682 ** entry corresponding to the new right-child pointer of the root
53683 ** page is also updated.
53685 ** If successful, *ppChild is set to contain a reference to the child
53686 ** page and SQLITE_OK is returned. In this case the caller is required
53687 ** to call releasePage() on *ppChild exactly once. If an error occurs,
53688 ** an error code is returned and *ppChild is set to 0.
53690 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
53691 int rc; /* Return value from subprocedures */
53692 MemPage *pChild = 0; /* Pointer to a new child page */
53693 Pgno pgnoChild = 0; /* Page number of the new child page */
53694 BtShared *pBt = pRoot->pBt; /* The BTree */
53696 assert( pRoot->nOverflow>0 );
53697 assert( sqlite3_mutex_held(pBt->mutex) );
53699 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
53700 ** page that will become the new right-child of pPage. Copy the contents
53701 ** of the node stored on pRoot into the new child page.
53703 rc = sqlite3PagerWrite(pRoot->pDbPage);
53704 if( rc==SQLITE_OK ){
53705 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
53706 copyNodeContent(pRoot, pChild, &rc);
53707 if( ISAUTOVACUUM ){
53708 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
53711 if( rc ){
53712 *ppChild = 0;
53713 releasePage(pChild);
53714 return rc;
53716 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
53717 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
53718 assert( pChild->nCell==pRoot->nCell );
53720 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
53722 /* Copy the overflow cells from pRoot to pChild */
53723 memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
53724 pChild->nOverflow = pRoot->nOverflow;
53726 /* Zero the contents of pRoot. Then install pChild as the right-child. */
53727 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
53728 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
53730 *ppChild = pChild;
53731 return SQLITE_OK;
53735 ** The page that pCur currently points to has just been modified in
53736 ** some way. This function figures out if this modification means the
53737 ** tree needs to be balanced, and if so calls the appropriate balancing
53738 ** routine. Balancing routines are:
53740 ** balance_quick()
53741 ** balance_deeper()
53742 ** balance_nonroot()
53744 static int balance(BtCursor *pCur){
53745 int rc = SQLITE_OK;
53746 const int nMin = pCur->pBt->usableSize * 2 / 3;
53747 u8 aBalanceQuickSpace[13];
53748 u8 *pFree = 0;
53750 TESTONLY( int balance_quick_called = 0 );
53751 TESTONLY( int balance_deeper_called = 0 );
53753 do {
53754 int iPage = pCur->iPage;
53755 MemPage *pPage = pCur->apPage[iPage];
53757 if( iPage==0 ){
53758 if( pPage->nOverflow ){
53759 /* The root page of the b-tree is overfull. In this case call the
53760 ** balance_deeper() function to create a new child for the root-page
53761 ** and copy the current contents of the root-page to it. The
53762 ** next iteration of the do-loop will balance the child page.
53764 assert( (balance_deeper_called++)==0 );
53765 rc = balance_deeper(pPage, &pCur->apPage[1]);
53766 if( rc==SQLITE_OK ){
53767 pCur->iPage = 1;
53768 pCur->aiIdx[0] = 0;
53769 pCur->aiIdx[1] = 0;
53770 assert( pCur->apPage[1]->nOverflow );
53772 }else{
53773 break;
53775 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
53776 break;
53777 }else{
53778 MemPage * const pParent = pCur->apPage[iPage-1];
53779 int const iIdx = pCur->aiIdx[iPage-1];
53781 rc = sqlite3PagerWrite(pParent->pDbPage);
53782 if( rc==SQLITE_OK ){
53783 #ifndef SQLITE_OMIT_QUICKBALANCE
53784 if( pPage->hasData
53785 && pPage->nOverflow==1
53786 && pPage->aOvfl[0].idx==pPage->nCell
53787 && pParent->pgno!=1
53788 && pParent->nCell==iIdx
53790 /* Call balance_quick() to create a new sibling of pPage on which
53791 ** to store the overflow cell. balance_quick() inserts a new cell
53792 ** into pParent, which may cause pParent overflow. If this
53793 ** happens, the next interation of the do-loop will balance pParent
53794 ** use either balance_nonroot() or balance_deeper(). Until this
53795 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
53796 ** buffer.
53798 ** The purpose of the following assert() is to check that only a
53799 ** single call to balance_quick() is made for each call to this
53800 ** function. If this were not verified, a subtle bug involving reuse
53801 ** of the aBalanceQuickSpace[] might sneak in.
53803 assert( (balance_quick_called++)==0 );
53804 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
53805 }else
53806 #endif
53808 /* In this case, call balance_nonroot() to redistribute cells
53809 ** between pPage and up to 2 of its sibling pages. This involves
53810 ** modifying the contents of pParent, which may cause pParent to
53811 ** become overfull or underfull. The next iteration of the do-loop
53812 ** will balance the parent page to correct this.
53814 ** If the parent page becomes overfull, the overflow cell or cells
53815 ** are stored in the pSpace buffer allocated immediately below.
53816 ** A subsequent iteration of the do-loop will deal with this by
53817 ** calling balance_nonroot() (balance_deeper() may be called first,
53818 ** but it doesn't deal with overflow cells - just moves them to a
53819 ** different page). Once this subsequent call to balance_nonroot()
53820 ** has completed, it is safe to release the pSpace buffer used by
53821 ** the previous call, as the overflow cell data will have been
53822 ** copied either into the body of a database page or into the new
53823 ** pSpace buffer passed to the latter call to balance_nonroot().
53825 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
53826 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
53827 if( pFree ){
53828 /* If pFree is not NULL, it points to the pSpace buffer used
53829 ** by a previous call to balance_nonroot(). Its contents are
53830 ** now stored either on real database pages or within the
53831 ** new pSpace buffer, so it may be safely freed here. */
53832 sqlite3PageFree(pFree);
53835 /* The pSpace buffer will be freed after the next call to
53836 ** balance_nonroot(), or just before this function returns, whichever
53837 ** comes first. */
53838 pFree = pSpace;
53842 pPage->nOverflow = 0;
53844 /* The next iteration of the do-loop balances the parent page. */
53845 releasePage(pPage);
53846 pCur->iPage--;
53848 }while( rc==SQLITE_OK );
53850 if( pFree ){
53851 sqlite3PageFree(pFree);
53853 return rc;
53858 ** Insert a new record into the BTree. The key is given by (pKey,nKey)
53859 ** and the data is given by (pData,nData). The cursor is used only to
53860 ** define what table the record should be inserted into. The cursor
53861 ** is left pointing at a random location.
53863 ** For an INTKEY table, only the nKey value of the key is used. pKey is
53864 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
53866 ** If the seekResult parameter is non-zero, then a successful call to
53867 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
53868 ** been performed. seekResult is the search result returned (a negative
53869 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
53870 ** a positive value if pCur points at an etry that is larger than
53871 ** (pKey, nKey)).
53873 ** If the seekResult parameter is non-zero, then the caller guarantees that
53874 ** cursor pCur is pointing at the existing copy of a row that is to be
53875 ** overwritten. If the seekResult parameter is 0, then cursor pCur may
53876 ** point to any entry or to no entry at all and so this function has to seek
53877 ** the cursor before the new key can be inserted.
53879 SQLITE_PRIVATE int sqlite3BtreeInsert(
53880 BtCursor *pCur, /* Insert data into the table of this cursor */
53881 const void *pKey, i64 nKey, /* The key of the new record */
53882 const void *pData, int nData, /* The data of the new record */
53883 int nZero, /* Number of extra 0 bytes to append to data */
53884 int appendBias, /* True if this is likely an append */
53885 int seekResult /* Result of prior MovetoUnpacked() call */
53887 int rc;
53888 int loc = seekResult; /* -1: before desired location +1: after */
53889 int szNew = 0;
53890 int idx;
53891 MemPage *pPage;
53892 Btree *p = pCur->pBtree;
53893 BtShared *pBt = p->pBt;
53894 unsigned char *oldCell;
53895 unsigned char *newCell = 0;
53897 if( pCur->eState==CURSOR_FAULT ){
53898 assert( pCur->skipNext!=SQLITE_OK );
53899 return pCur->skipNext;
53902 assert( cursorHoldsMutex(pCur) );
53903 assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
53904 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
53906 /* Assert that the caller has been consistent. If this cursor was opened
53907 ** expecting an index b-tree, then the caller should be inserting blob
53908 ** keys with no associated data. If the cursor was opened expecting an
53909 ** intkey table, the caller should be inserting integer keys with a
53910 ** blob of associated data. */
53911 assert( (pKey==0)==(pCur->pKeyInfo==0) );
53913 /* If this is an insert into a table b-tree, invalidate any incrblob
53914 ** cursors open on the row being replaced (assuming this is a replace
53915 ** operation - if it is not, the following is a no-op). */
53916 if( pCur->pKeyInfo==0 ){
53917 invalidateIncrblobCursors(p, nKey, 0);
53920 /* Save the positions of any other cursors open on this table.
53922 ** In some cases, the call to btreeMoveto() below is a no-op. For
53923 ** example, when inserting data into a table with auto-generated integer
53924 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
53925 ** integer key to use. It then calls this function to actually insert the
53926 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
53927 ** that the cursor is already where it needs to be and returns without
53928 ** doing any work. To avoid thwarting these optimizations, it is important
53929 ** not to clear the cursor here.
53931 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
53932 if( rc ) return rc;
53933 if( !loc ){
53934 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
53935 if( rc ) return rc;
53937 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
53939 pPage = pCur->apPage[pCur->iPage];
53940 assert( pPage->intKey || nKey>=0 );
53941 assert( pPage->leaf || !pPage->intKey );
53943 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
53944 pCur->pgnoRoot, nKey, nData, pPage->pgno,
53945 loc==0 ? "overwrite" : "new entry"));
53946 assert( pPage->isInit );
53947 allocateTempSpace(pBt);
53948 newCell = pBt->pTmpSpace;
53949 if( newCell==0 ) return SQLITE_NOMEM;
53950 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
53951 if( rc ) goto end_insert;
53952 assert( szNew==cellSizePtr(pPage, newCell) );
53953 assert( szNew <= MX_CELL_SIZE(pBt) );
53954 idx = pCur->aiIdx[pCur->iPage];
53955 if( loc==0 ){
53956 u16 szOld;
53957 assert( idx<pPage->nCell );
53958 rc = sqlite3PagerWrite(pPage->pDbPage);
53959 if( rc ){
53960 goto end_insert;
53962 oldCell = findCell(pPage, idx);
53963 if( !pPage->leaf ){
53964 memcpy(newCell, oldCell, 4);
53966 szOld = cellSizePtr(pPage, oldCell);
53967 rc = clearCell(pPage, oldCell);
53968 dropCell(pPage, idx, szOld, &rc);
53969 if( rc ) goto end_insert;
53970 }else if( loc<0 && pPage->nCell>0 ){
53971 assert( pPage->leaf );
53972 idx = ++pCur->aiIdx[pCur->iPage];
53973 }else{
53974 assert( pPage->leaf );
53976 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
53977 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
53979 /* If no error has occured and pPage has an overflow cell, call balance()
53980 ** to redistribute the cells within the tree. Since balance() may move
53981 ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
53982 ** variables.
53984 ** Previous versions of SQLite called moveToRoot() to move the cursor
53985 ** back to the root page as balance() used to invalidate the contents
53986 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
53987 ** set the cursor state to "invalid". This makes common insert operations
53988 ** slightly faster.
53990 ** There is a subtle but important optimization here too. When inserting
53991 ** multiple records into an intkey b-tree using a single cursor (as can
53992 ** happen while processing an "INSERT INTO ... SELECT" statement), it
53993 ** is advantageous to leave the cursor pointing to the last entry in
53994 ** the b-tree if possible. If the cursor is left pointing to the last
53995 ** entry in the table, and the next row inserted has an integer key
53996 ** larger than the largest existing key, it is possible to insert the
53997 ** row without seeking the cursor. This can be a big performance boost.
53999 pCur->info.nSize = 0;
54000 pCur->validNKey = 0;
54001 if( rc==SQLITE_OK && pPage->nOverflow ){
54002 rc = balance(pCur);
54004 /* Must make sure nOverflow is reset to zero even if the balance()
54005 ** fails. Internal data structure corruption will result otherwise.
54006 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
54007 ** from trying to save the current position of the cursor. */
54008 pCur->apPage[pCur->iPage]->nOverflow = 0;
54009 pCur->eState = CURSOR_INVALID;
54011 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
54013 end_insert:
54014 return rc;
54018 ** Delete the entry that the cursor is pointing to. The cursor
54019 ** is left pointing at a arbitrary location.
54021 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
54022 Btree *p = pCur->pBtree;
54023 BtShared *pBt = p->pBt;
54024 int rc; /* Return code */
54025 MemPage *pPage; /* Page to delete cell from */
54026 unsigned char *pCell; /* Pointer to cell to delete */
54027 int iCellIdx; /* Index of cell to delete */
54028 int iCellDepth; /* Depth of node containing pCell */
54030 assert( cursorHoldsMutex(pCur) );
54031 assert( pBt->inTransaction==TRANS_WRITE );
54032 assert( !pBt->readOnly );
54033 assert( pCur->wrFlag );
54034 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
54035 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
54037 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
54038 || NEVER(pCur->eState!=CURSOR_VALID)
54040 return SQLITE_ERROR; /* Something has gone awry. */
54043 /* If this is a delete operation to remove a row from a table b-tree,
54044 ** invalidate any incrblob cursors open on the row being deleted. */
54045 if( pCur->pKeyInfo==0 ){
54046 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
54049 iCellDepth = pCur->iPage;
54050 iCellIdx = pCur->aiIdx[iCellDepth];
54051 pPage = pCur->apPage[iCellDepth];
54052 pCell = findCell(pPage, iCellIdx);
54054 /* If the page containing the entry to delete is not a leaf page, move
54055 ** the cursor to the largest entry in the tree that is smaller than
54056 ** the entry being deleted. This cell will replace the cell being deleted
54057 ** from the internal node. The 'previous' entry is used for this instead
54058 ** of the 'next' entry, as the previous entry is always a part of the
54059 ** sub-tree headed by the child page of the cell being deleted. This makes
54060 ** balancing the tree following the delete operation easier. */
54061 if( !pPage->leaf ){
54062 int notUsed;
54063 rc = sqlite3BtreePrevious(pCur, &notUsed);
54064 if( rc ) return rc;
54067 /* Save the positions of any other cursors open on this table before
54068 ** making any modifications. Make the page containing the entry to be
54069 ** deleted writable. Then free any overflow pages associated with the
54070 ** entry and finally remove the cell itself from within the page.
54072 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
54073 if( rc ) return rc;
54074 rc = sqlite3PagerWrite(pPage->pDbPage);
54075 if( rc ) return rc;
54076 rc = clearCell(pPage, pCell);
54077 dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
54078 if( rc ) return rc;
54080 /* If the cell deleted was not located on a leaf page, then the cursor
54081 ** is currently pointing to the largest entry in the sub-tree headed
54082 ** by the child-page of the cell that was just deleted from an internal
54083 ** node. The cell from the leaf node needs to be moved to the internal
54084 ** node to replace the deleted cell. */
54085 if( !pPage->leaf ){
54086 MemPage *pLeaf = pCur->apPage[pCur->iPage];
54087 int nCell;
54088 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
54089 unsigned char *pTmp;
54091 pCell = findCell(pLeaf, pLeaf->nCell-1);
54092 nCell = cellSizePtr(pLeaf, pCell);
54093 assert( MX_CELL_SIZE(pBt) >= nCell );
54095 allocateTempSpace(pBt);
54096 pTmp = pBt->pTmpSpace;
54098 rc = sqlite3PagerWrite(pLeaf->pDbPage);
54099 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
54100 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
54101 if( rc ) return rc;
54104 /* Balance the tree. If the entry deleted was located on a leaf page,
54105 ** then the cursor still points to that page. In this case the first
54106 ** call to balance() repairs the tree, and the if(...) condition is
54107 ** never true.
54109 ** Otherwise, if the entry deleted was on an internal node page, then
54110 ** pCur is pointing to the leaf page from which a cell was removed to
54111 ** replace the cell deleted from the internal node. This is slightly
54112 ** tricky as the leaf node may be underfull, and the internal node may
54113 ** be either under or overfull. In this case run the balancing algorithm
54114 ** on the leaf node first. If the balance proceeds far enough up the
54115 ** tree that we can be sure that any problem in the internal node has
54116 ** been corrected, so be it. Otherwise, after balancing the leaf node,
54117 ** walk the cursor up the tree to the internal node and balance it as
54118 ** well. */
54119 rc = balance(pCur);
54120 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
54121 while( pCur->iPage>iCellDepth ){
54122 releasePage(pCur->apPage[pCur->iPage--]);
54124 rc = balance(pCur);
54127 if( rc==SQLITE_OK ){
54128 moveToRoot(pCur);
54130 return rc;
54134 ** Create a new BTree table. Write into *piTable the page
54135 ** number for the root page of the new table.
54137 ** The type of type is determined by the flags parameter. Only the
54138 ** following values of flags are currently in use. Other values for
54139 ** flags might not work:
54141 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
54142 ** BTREE_ZERODATA Used for SQL indices
54144 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
54145 BtShared *pBt = p->pBt;
54146 MemPage *pRoot;
54147 Pgno pgnoRoot;
54148 int rc;
54149 int ptfFlags; /* Page-type flage for the root page of new table */
54151 assert( sqlite3BtreeHoldsMutex(p) );
54152 assert( pBt->inTransaction==TRANS_WRITE );
54153 assert( !pBt->readOnly );
54155 #ifdef SQLITE_OMIT_AUTOVACUUM
54156 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
54157 if( rc ){
54158 return rc;
54160 #else
54161 if( pBt->autoVacuum ){
54162 Pgno pgnoMove; /* Move a page here to make room for the root-page */
54163 MemPage *pPageMove; /* The page to move to. */
54165 /* Creating a new table may probably require moving an existing database
54166 ** to make room for the new tables root page. In case this page turns
54167 ** out to be an overflow page, delete all overflow page-map caches
54168 ** held by open cursors.
54170 invalidateAllOverflowCache(pBt);
54172 /* Read the value of meta[3] from the database to determine where the
54173 ** root page of the new table should go. meta[3] is the largest root-page
54174 ** created so far, so the new root-page is (meta[3]+1).
54176 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
54177 pgnoRoot++;
54179 /* The new root-page may not be allocated on a pointer-map page, or the
54180 ** PENDING_BYTE page.
54182 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
54183 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
54184 pgnoRoot++;
54186 assert( pgnoRoot>=3 );
54188 /* Allocate a page. The page that currently resides at pgnoRoot will
54189 ** be moved to the allocated page (unless the allocated page happens
54190 ** to reside at pgnoRoot).
54192 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
54193 if( rc!=SQLITE_OK ){
54194 return rc;
54197 if( pgnoMove!=pgnoRoot ){
54198 /* pgnoRoot is the page that will be used for the root-page of
54199 ** the new table (assuming an error did not occur). But we were
54200 ** allocated pgnoMove. If required (i.e. if it was not allocated
54201 ** by extending the file), the current page at position pgnoMove
54202 ** is already journaled.
54204 u8 eType = 0;
54205 Pgno iPtrPage = 0;
54207 releasePage(pPageMove);
54209 /* Move the page currently at pgnoRoot to pgnoMove. */
54210 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
54211 if( rc!=SQLITE_OK ){
54212 return rc;
54214 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
54215 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
54216 rc = SQLITE_CORRUPT_BKPT;
54218 if( rc!=SQLITE_OK ){
54219 releasePage(pRoot);
54220 return rc;
54222 assert( eType!=PTRMAP_ROOTPAGE );
54223 assert( eType!=PTRMAP_FREEPAGE );
54224 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
54225 releasePage(pRoot);
54227 /* Obtain the page at pgnoRoot */
54228 if( rc!=SQLITE_OK ){
54229 return rc;
54231 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
54232 if( rc!=SQLITE_OK ){
54233 return rc;
54235 rc = sqlite3PagerWrite(pRoot->pDbPage);
54236 if( rc!=SQLITE_OK ){
54237 releasePage(pRoot);
54238 return rc;
54240 }else{
54241 pRoot = pPageMove;
54244 /* Update the pointer-map and meta-data with the new root-page number. */
54245 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
54246 if( rc ){
54247 releasePage(pRoot);
54248 return rc;
54251 /* When the new root page was allocated, page 1 was made writable in
54252 ** order either to increase the database filesize, or to decrement the
54253 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
54255 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
54256 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
54257 if( NEVER(rc) ){
54258 releasePage(pRoot);
54259 return rc;
54262 }else{
54263 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
54264 if( rc ) return rc;
54266 #endif
54267 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
54268 if( createTabFlags & BTREE_INTKEY ){
54269 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
54270 }else{
54271 ptfFlags = PTF_ZERODATA | PTF_LEAF;
54273 zeroPage(pRoot, ptfFlags);
54274 sqlite3PagerUnref(pRoot->pDbPage);
54275 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
54276 *piTable = (int)pgnoRoot;
54277 return SQLITE_OK;
54279 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
54280 int rc;
54281 sqlite3BtreeEnter(p);
54282 rc = btreeCreateTable(p, piTable, flags);
54283 sqlite3BtreeLeave(p);
54284 return rc;
54288 ** Erase the given database page and all its children. Return
54289 ** the page to the freelist.
54291 static int clearDatabasePage(
54292 BtShared *pBt, /* The BTree that contains the table */
54293 Pgno pgno, /* Page number to clear */
54294 int freePageFlag, /* Deallocate page if true */
54295 int *pnChange /* Add number of Cells freed to this counter */
54297 MemPage *pPage;
54298 int rc;
54299 unsigned char *pCell;
54300 int i;
54302 assert( sqlite3_mutex_held(pBt->mutex) );
54303 if( pgno>btreePagecount(pBt) ){
54304 return SQLITE_CORRUPT_BKPT;
54307 rc = getAndInitPage(pBt, pgno, &pPage);
54308 if( rc ) return rc;
54309 for(i=0; i<pPage->nCell; i++){
54310 pCell = findCell(pPage, i);
54311 if( !pPage->leaf ){
54312 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
54313 if( rc ) goto cleardatabasepage_out;
54315 rc = clearCell(pPage, pCell);
54316 if( rc ) goto cleardatabasepage_out;
54318 if( !pPage->leaf ){
54319 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
54320 if( rc ) goto cleardatabasepage_out;
54321 }else if( pnChange ){
54322 assert( pPage->intKey );
54323 *pnChange += pPage->nCell;
54325 if( freePageFlag ){
54326 freePage(pPage, &rc);
54327 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
54328 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
54331 cleardatabasepage_out:
54332 releasePage(pPage);
54333 return rc;
54337 ** Delete all information from a single table in the database. iTable is
54338 ** the page number of the root of the table. After this routine returns,
54339 ** the root page is empty, but still exists.
54341 ** This routine will fail with SQLITE_LOCKED if there are any open
54342 ** read cursors on the table. Open write cursors are moved to the
54343 ** root of the table.
54345 ** If pnChange is not NULL, then table iTable must be an intkey table. The
54346 ** integer value pointed to by pnChange is incremented by the number of
54347 ** entries in the table.
54349 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
54350 int rc;
54351 BtShared *pBt = p->pBt;
54352 sqlite3BtreeEnter(p);
54353 assert( p->inTrans==TRANS_WRITE );
54355 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
54356 ** is the root of a table b-tree - if it is not, the following call is
54357 ** a no-op). */
54358 invalidateIncrblobCursors(p, 0, 1);
54360 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
54361 if( SQLITE_OK==rc ){
54362 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
54364 sqlite3BtreeLeave(p);
54365 return rc;
54369 ** Erase all information in a table and add the root of the table to
54370 ** the freelist. Except, the root of the principle table (the one on
54371 ** page 1) is never added to the freelist.
54373 ** This routine will fail with SQLITE_LOCKED if there are any open
54374 ** cursors on the table.
54376 ** If AUTOVACUUM is enabled and the page at iTable is not the last
54377 ** root page in the database file, then the last root page
54378 ** in the database file is moved into the slot formerly occupied by
54379 ** iTable and that last slot formerly occupied by the last root page
54380 ** is added to the freelist instead of iTable. In this say, all
54381 ** root pages are kept at the beginning of the database file, which
54382 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
54383 ** page number that used to be the last root page in the file before
54384 ** the move. If no page gets moved, *piMoved is set to 0.
54385 ** The last root page is recorded in meta[3] and the value of
54386 ** meta[3] is updated by this procedure.
54388 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
54389 int rc;
54390 MemPage *pPage = 0;
54391 BtShared *pBt = p->pBt;
54393 assert( sqlite3BtreeHoldsMutex(p) );
54394 assert( p->inTrans==TRANS_WRITE );
54396 /* It is illegal to drop a table if any cursors are open on the
54397 ** database. This is because in auto-vacuum mode the backend may
54398 ** need to move another root-page to fill a gap left by the deleted
54399 ** root page. If an open cursor was using this page a problem would
54400 ** occur.
54402 ** This error is caught long before control reaches this point.
54404 if( NEVER(pBt->pCursor) ){
54405 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
54406 return SQLITE_LOCKED_SHAREDCACHE;
54409 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
54410 if( rc ) return rc;
54411 rc = sqlite3BtreeClearTable(p, iTable, 0);
54412 if( rc ){
54413 releasePage(pPage);
54414 return rc;
54417 *piMoved = 0;
54419 if( iTable>1 ){
54420 #ifdef SQLITE_OMIT_AUTOVACUUM
54421 freePage(pPage, &rc);
54422 releasePage(pPage);
54423 #else
54424 if( pBt->autoVacuum ){
54425 Pgno maxRootPgno;
54426 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
54428 if( iTable==maxRootPgno ){
54429 /* If the table being dropped is the table with the largest root-page
54430 ** number in the database, put the root page on the free list.
54432 freePage(pPage, &rc);
54433 releasePage(pPage);
54434 if( rc!=SQLITE_OK ){
54435 return rc;
54437 }else{
54438 /* The table being dropped does not have the largest root-page
54439 ** number in the database. So move the page that does into the
54440 ** gap left by the deleted root-page.
54442 MemPage *pMove;
54443 releasePage(pPage);
54444 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54445 if( rc!=SQLITE_OK ){
54446 return rc;
54448 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
54449 releasePage(pMove);
54450 if( rc!=SQLITE_OK ){
54451 return rc;
54453 pMove = 0;
54454 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54455 freePage(pMove, &rc);
54456 releasePage(pMove);
54457 if( rc!=SQLITE_OK ){
54458 return rc;
54460 *piMoved = maxRootPgno;
54463 /* Set the new 'max-root-page' value in the database header. This
54464 ** is the old value less one, less one more if that happens to
54465 ** be a root-page number, less one again if that is the
54466 ** PENDING_BYTE_PAGE.
54468 maxRootPgno--;
54469 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
54470 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
54471 maxRootPgno--;
54473 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
54475 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
54476 }else{
54477 freePage(pPage, &rc);
54478 releasePage(pPage);
54480 #endif
54481 }else{
54482 /* If sqlite3BtreeDropTable was called on page 1.
54483 ** This really never should happen except in a corrupt
54484 ** database.
54486 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
54487 releasePage(pPage);
54489 return rc;
54491 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
54492 int rc;
54493 sqlite3BtreeEnter(p);
54494 rc = btreeDropTable(p, iTable, piMoved);
54495 sqlite3BtreeLeave(p);
54496 return rc;
54501 ** This function may only be called if the b-tree connection already
54502 ** has a read or write transaction open on the database.
54504 ** Read the meta-information out of a database file. Meta[0]
54505 ** is the number of free pages currently in the database. Meta[1]
54506 ** through meta[15] are available for use by higher layers. Meta[0]
54507 ** is read-only, the others are read/write.
54509 ** The schema layer numbers meta values differently. At the schema
54510 ** layer (and the SetCookie and ReadCookie opcodes) the number of
54511 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
54513 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
54514 BtShared *pBt = p->pBt;
54516 sqlite3BtreeEnter(p);
54517 assert( p->inTrans>TRANS_NONE );
54518 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
54519 assert( pBt->pPage1 );
54520 assert( idx>=0 && idx<=15 );
54522 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
54524 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
54525 ** database, mark the database as read-only. */
54526 #ifdef SQLITE_OMIT_AUTOVACUUM
54527 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
54528 #endif
54530 sqlite3BtreeLeave(p);
54534 ** Write meta-information back into the database. Meta[0] is
54535 ** read-only and may not be written.
54537 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
54538 BtShared *pBt = p->pBt;
54539 unsigned char *pP1;
54540 int rc;
54541 assert( idx>=1 && idx<=15 );
54542 sqlite3BtreeEnter(p);
54543 assert( p->inTrans==TRANS_WRITE );
54544 assert( pBt->pPage1!=0 );
54545 pP1 = pBt->pPage1->aData;
54546 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54547 if( rc==SQLITE_OK ){
54548 put4byte(&pP1[36 + idx*4], iMeta);
54549 #ifndef SQLITE_OMIT_AUTOVACUUM
54550 if( idx==BTREE_INCR_VACUUM ){
54551 assert( pBt->autoVacuum || iMeta==0 );
54552 assert( iMeta==0 || iMeta==1 );
54553 pBt->incrVacuum = (u8)iMeta;
54555 #endif
54557 sqlite3BtreeLeave(p);
54558 return rc;
54561 #ifndef SQLITE_OMIT_BTREECOUNT
54563 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
54564 ** number of entries in the b-tree and write the result to *pnEntry.
54566 ** SQLITE_OK is returned if the operation is successfully executed.
54567 ** Otherwise, if an error is encountered (i.e. an IO error or database
54568 ** corruption) an SQLite error code is returned.
54570 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
54571 i64 nEntry = 0; /* Value to return in *pnEntry */
54572 int rc; /* Return code */
54573 rc = moveToRoot(pCur);
54575 /* Unless an error occurs, the following loop runs one iteration for each
54576 ** page in the B-Tree structure (not including overflow pages).
54578 while( rc==SQLITE_OK ){
54579 int iIdx; /* Index of child node in parent */
54580 MemPage *pPage; /* Current page of the b-tree */
54582 /* If this is a leaf page or the tree is not an int-key tree, then
54583 ** this page contains countable entries. Increment the entry counter
54584 ** accordingly.
54586 pPage = pCur->apPage[pCur->iPage];
54587 if( pPage->leaf || !pPage->intKey ){
54588 nEntry += pPage->nCell;
54591 /* pPage is a leaf node. This loop navigates the cursor so that it
54592 ** points to the first interior cell that it points to the parent of
54593 ** the next page in the tree that has not yet been visited. The
54594 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
54595 ** of the page, or to the number of cells in the page if the next page
54596 ** to visit is the right-child of its parent.
54598 ** If all pages in the tree have been visited, return SQLITE_OK to the
54599 ** caller.
54601 if( pPage->leaf ){
54602 do {
54603 if( pCur->iPage==0 ){
54604 /* All pages of the b-tree have been visited. Return successfully. */
54605 *pnEntry = nEntry;
54606 return SQLITE_OK;
54608 moveToParent(pCur);
54609 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
54611 pCur->aiIdx[pCur->iPage]++;
54612 pPage = pCur->apPage[pCur->iPage];
54615 /* Descend to the child node of the cell that the cursor currently
54616 ** points at. This is the right-child if (iIdx==pPage->nCell).
54618 iIdx = pCur->aiIdx[pCur->iPage];
54619 if( iIdx==pPage->nCell ){
54620 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54621 }else{
54622 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
54626 /* An error has occurred. Return an error code. */
54627 return rc;
54629 #endif
54632 ** Return the pager associated with a BTree. This routine is used for
54633 ** testing and debugging only.
54635 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
54636 return p->pBt->pPager;
54639 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54641 ** Append a message to the error message string.
54643 static void checkAppendMsg(
54644 IntegrityCk *pCheck,
54645 char *zMsg1,
54646 const char *zFormat,
54649 va_list ap;
54650 if( !pCheck->mxErr ) return;
54651 pCheck->mxErr--;
54652 pCheck->nErr++;
54653 va_start(ap, zFormat);
54654 if( pCheck->errMsg.nChar ){
54655 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
54657 if( zMsg1 ){
54658 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
54660 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
54661 va_end(ap);
54662 if( pCheck->errMsg.mallocFailed ){
54663 pCheck->mallocFailed = 1;
54666 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54668 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54670 ** Add 1 to the reference count for page iPage. If this is the second
54671 ** reference to the page, add an error message to pCheck->zErrMsg.
54672 ** Return 1 if there are 2 ore more references to the page and 0 if
54673 ** if this is the first reference to the page.
54675 ** Also check that the page number is in bounds.
54677 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
54678 if( iPage==0 ) return 1;
54679 if( iPage>pCheck->nPage ){
54680 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
54681 return 1;
54683 if( pCheck->anRef[iPage]==1 ){
54684 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
54685 return 1;
54687 return (pCheck->anRef[iPage]++)>1;
54690 #ifndef SQLITE_OMIT_AUTOVACUUM
54692 ** Check that the entry in the pointer-map for page iChild maps to
54693 ** page iParent, pointer type ptrType. If not, append an error message
54694 ** to pCheck.
54696 static void checkPtrmap(
54697 IntegrityCk *pCheck, /* Integrity check context */
54698 Pgno iChild, /* Child page number */
54699 u8 eType, /* Expected pointer map type */
54700 Pgno iParent, /* Expected pointer map parent page number */
54701 char *zContext /* Context description (used for error msg) */
54703 int rc;
54704 u8 ePtrmapType;
54705 Pgno iPtrmapParent;
54707 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
54708 if( rc!=SQLITE_OK ){
54709 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
54710 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
54711 return;
54714 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
54715 checkAppendMsg(pCheck, zContext,
54716 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
54717 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
54720 #endif
54723 ** Check the integrity of the freelist or of an overflow page list.
54724 ** Verify that the number of pages on the list is N.
54726 static void checkList(
54727 IntegrityCk *pCheck, /* Integrity checking context */
54728 int isFreeList, /* True for a freelist. False for overflow page list */
54729 int iPage, /* Page number for first page in the list */
54730 int N, /* Expected number of pages in the list */
54731 char *zContext /* Context for error messages */
54733 int i;
54734 int expected = N;
54735 int iFirst = iPage;
54736 while( N-- > 0 && pCheck->mxErr ){
54737 DbPage *pOvflPage;
54738 unsigned char *pOvflData;
54739 if( iPage<1 ){
54740 checkAppendMsg(pCheck, zContext,
54741 "%d of %d pages missing from overflow list starting at %d",
54742 N+1, expected, iFirst);
54743 break;
54745 if( checkRef(pCheck, iPage, zContext) ) break;
54746 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
54747 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
54748 break;
54750 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
54751 if( isFreeList ){
54752 int n = get4byte(&pOvflData[4]);
54753 #ifndef SQLITE_OMIT_AUTOVACUUM
54754 if( pCheck->pBt->autoVacuum ){
54755 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
54757 #endif
54758 if( n>(int)pCheck->pBt->usableSize/4-2 ){
54759 checkAppendMsg(pCheck, zContext,
54760 "freelist leaf count too big on page %d", iPage);
54761 N--;
54762 }else{
54763 for(i=0; i<n; i++){
54764 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
54765 #ifndef SQLITE_OMIT_AUTOVACUUM
54766 if( pCheck->pBt->autoVacuum ){
54767 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
54769 #endif
54770 checkRef(pCheck, iFreePage, zContext);
54772 N -= n;
54775 #ifndef SQLITE_OMIT_AUTOVACUUM
54776 else{
54777 /* If this database supports auto-vacuum and iPage is not the last
54778 ** page in this overflow list, check that the pointer-map entry for
54779 ** the following page matches iPage.
54781 if( pCheck->pBt->autoVacuum && N>0 ){
54782 i = get4byte(pOvflData);
54783 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
54786 #endif
54787 iPage = get4byte(pOvflData);
54788 sqlite3PagerUnref(pOvflPage);
54791 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54793 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54795 ** Do various sanity checks on a single page of a tree. Return
54796 ** the tree depth. Root pages return 0. Parents of root pages
54797 ** return 1, and so forth.
54799 ** These checks are done:
54801 ** 1. Make sure that cells and freeblocks do not overlap
54802 ** but combine to completely cover the page.
54803 ** NO 2. Make sure cell keys are in order.
54804 ** NO 3. Make sure no key is less than or equal to zLowerBound.
54805 ** NO 4. Make sure no key is greater than or equal to zUpperBound.
54806 ** 5. Check the integrity of overflow pages.
54807 ** 6. Recursively call checkTreePage on all children.
54808 ** 7. Verify that the depth of all children is the same.
54809 ** 8. Make sure this page is at least 33% full or else it is
54810 ** the root of the tree.
54812 static int checkTreePage(
54813 IntegrityCk *pCheck, /* Context for the sanity check */
54814 int iPage, /* Page number of the page to check */
54815 char *zParentContext, /* Parent context */
54816 i64 *pnParentMinKey,
54817 i64 *pnParentMaxKey
54819 MemPage *pPage;
54820 int i, rc, depth, d2, pgno, cnt;
54821 int hdr, cellStart;
54822 int nCell;
54823 u8 *data;
54824 BtShared *pBt;
54825 int usableSize;
54826 char zContext[100];
54827 char *hit = 0;
54828 i64 nMinKey = 0;
54829 i64 nMaxKey = 0;
54831 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
54833 /* Check that the page exists
54835 pBt = pCheck->pBt;
54836 usableSize = pBt->usableSize;
54837 if( iPage==0 ) return 0;
54838 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
54839 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
54840 checkAppendMsg(pCheck, zContext,
54841 "unable to get the page. error code=%d", rc);
54842 return 0;
54845 /* Clear MemPage.isInit to make sure the corruption detection code in
54846 ** btreeInitPage() is executed. */
54847 pPage->isInit = 0;
54848 if( (rc = btreeInitPage(pPage))!=0 ){
54849 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
54850 checkAppendMsg(pCheck, zContext,
54851 "btreeInitPage() returns error code %d", rc);
54852 releasePage(pPage);
54853 return 0;
54856 /* Check out all the cells.
54858 depth = 0;
54859 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
54860 u8 *pCell;
54861 u32 sz;
54862 CellInfo info;
54864 /* Check payload overflow pages
54866 sqlite3_snprintf(sizeof(zContext), zContext,
54867 "On tree page %d cell %d: ", iPage, i);
54868 pCell = findCell(pPage,i);
54869 btreeParseCellPtr(pPage, pCell, &info);
54870 sz = info.nData;
54871 if( !pPage->intKey ) sz += (int)info.nKey;
54872 /* For intKey pages, check that the keys are in order.
54874 else if( i==0 ) nMinKey = nMaxKey = info.nKey;
54875 else{
54876 if( info.nKey <= nMaxKey ){
54877 checkAppendMsg(pCheck, zContext,
54878 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
54880 nMaxKey = info.nKey;
54882 assert( sz==info.nPayload );
54883 if( (sz>info.nLocal)
54884 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
54886 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
54887 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
54888 #ifndef SQLITE_OMIT_AUTOVACUUM
54889 if( pBt->autoVacuum ){
54890 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
54892 #endif
54893 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
54896 /* Check sanity of left child page.
54898 if( !pPage->leaf ){
54899 pgno = get4byte(pCell);
54900 #ifndef SQLITE_OMIT_AUTOVACUUM
54901 if( pBt->autoVacuum ){
54902 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
54904 #endif
54905 d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
54906 if( i>0 && d2!=depth ){
54907 checkAppendMsg(pCheck, zContext, "Child page depth differs");
54909 depth = d2;
54913 if( !pPage->leaf ){
54914 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54915 sqlite3_snprintf(sizeof(zContext), zContext,
54916 "On page %d at right child: ", iPage);
54917 #ifndef SQLITE_OMIT_AUTOVACUUM
54918 if( pBt->autoVacuum ){
54919 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
54921 #endif
54922 checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
54925 /* For intKey leaf pages, check that the min/max keys are in order
54926 ** with any left/parent/right pages.
54928 if( pPage->leaf && pPage->intKey ){
54929 /* if we are a left child page */
54930 if( pnParentMinKey ){
54931 /* if we are the left most child page */
54932 if( !pnParentMaxKey ){
54933 if( nMaxKey > *pnParentMinKey ){
54934 checkAppendMsg(pCheck, zContext,
54935 "Rowid %lld out of order (max larger than parent min of %lld)",
54936 nMaxKey, *pnParentMinKey);
54938 }else{
54939 if( nMinKey <= *pnParentMinKey ){
54940 checkAppendMsg(pCheck, zContext,
54941 "Rowid %lld out of order (min less than parent min of %lld)",
54942 nMinKey, *pnParentMinKey);
54944 if( nMaxKey > *pnParentMaxKey ){
54945 checkAppendMsg(pCheck, zContext,
54946 "Rowid %lld out of order (max larger than parent max of %lld)",
54947 nMaxKey, *pnParentMaxKey);
54949 *pnParentMinKey = nMaxKey;
54951 /* else if we're a right child page */
54952 } else if( pnParentMaxKey ){
54953 if( nMinKey <= *pnParentMaxKey ){
54954 checkAppendMsg(pCheck, zContext,
54955 "Rowid %lld out of order (min less than parent max of %lld)",
54956 nMinKey, *pnParentMaxKey);
54961 /* Check for complete coverage of the page
54963 data = pPage->aData;
54964 hdr = pPage->hdrOffset;
54965 hit = sqlite3PageMalloc( pBt->pageSize );
54966 if( hit==0 ){
54967 pCheck->mallocFailed = 1;
54968 }else{
54969 int contentOffset = get2byteNotZero(&data[hdr+5]);
54970 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
54971 memset(hit+contentOffset, 0, usableSize-contentOffset);
54972 memset(hit, 1, contentOffset);
54973 nCell = get2byte(&data[hdr+3]);
54974 cellStart = hdr + 12 - 4*pPage->leaf;
54975 for(i=0; i<nCell; i++){
54976 int pc = get2byte(&data[cellStart+i*2]);
54977 u32 size = 65536;
54978 int j;
54979 if( pc<=usableSize-4 ){
54980 size = cellSizePtr(pPage, &data[pc]);
54982 if( (int)(pc+size-1)>=usableSize ){
54983 checkAppendMsg(pCheck, 0,
54984 "Corruption detected in cell %d on page %d",i,iPage);
54985 }else{
54986 for(j=pc+size-1; j>=pc; j--) hit[j]++;
54989 i = get2byte(&data[hdr+1]);
54990 while( i>0 ){
54991 int size, j;
54992 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
54993 size = get2byte(&data[i+2]);
54994 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
54995 for(j=i+size-1; j>=i; j--) hit[j]++;
54996 j = get2byte(&data[i]);
54997 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
54998 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
54999 i = j;
55001 for(i=cnt=0; i<usableSize; i++){
55002 if( hit[i]==0 ){
55003 cnt++;
55004 }else if( hit[i]>1 ){
55005 checkAppendMsg(pCheck, 0,
55006 "Multiple uses for byte %d of page %d", i, iPage);
55007 break;
55010 if( cnt!=data[hdr+7] ){
55011 checkAppendMsg(pCheck, 0,
55012 "Fragmentation of %d bytes reported as %d on page %d",
55013 cnt, data[hdr+7], iPage);
55016 sqlite3PageFree(hit);
55017 releasePage(pPage);
55018 return depth+1;
55020 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55022 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55024 ** This routine does a complete check of the given BTree file. aRoot[] is
55025 ** an array of pages numbers were each page number is the root page of
55026 ** a table. nRoot is the number of entries in aRoot.
55028 ** A read-only or read-write transaction must be opened before calling
55029 ** this function.
55031 ** Write the number of error seen in *pnErr. Except for some memory
55032 ** allocation errors, an error message held in memory obtained from
55033 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
55034 ** returned. If a memory allocation error occurs, NULL is returned.
55036 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
55037 Btree *p, /* The btree to be checked */
55038 int *aRoot, /* An array of root pages numbers for individual trees */
55039 int nRoot, /* Number of entries in aRoot[] */
55040 int mxErr, /* Stop reporting errors after this many */
55041 int *pnErr /* Write number of errors seen to this variable */
55043 Pgno i;
55044 int nRef;
55045 IntegrityCk sCheck;
55046 BtShared *pBt = p->pBt;
55047 char zErr[100];
55049 sqlite3BtreeEnter(p);
55050 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
55051 nRef = sqlite3PagerRefcount(pBt->pPager);
55052 sCheck.pBt = pBt;
55053 sCheck.pPager = pBt->pPager;
55054 sCheck.nPage = btreePagecount(sCheck.pBt);
55055 sCheck.mxErr = mxErr;
55056 sCheck.nErr = 0;
55057 sCheck.mallocFailed = 0;
55058 *pnErr = 0;
55059 if( sCheck.nPage==0 ){
55060 sqlite3BtreeLeave(p);
55061 return 0;
55063 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
55064 if( !sCheck.anRef ){
55065 *pnErr = 1;
55066 sqlite3BtreeLeave(p);
55067 return 0;
55069 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
55070 i = PENDING_BYTE_PAGE(pBt);
55071 if( i<=sCheck.nPage ){
55072 sCheck.anRef[i] = 1;
55074 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
55075 sCheck.errMsg.useMalloc = 2;
55077 /* Check the integrity of the freelist
55079 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
55080 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
55082 /* Check all the tables.
55084 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
55085 if( aRoot[i]==0 ) continue;
55086 #ifndef SQLITE_OMIT_AUTOVACUUM
55087 if( pBt->autoVacuum && aRoot[i]>1 ){
55088 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
55090 #endif
55091 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
55094 /* Make sure every page in the file is referenced
55096 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
55097 #ifdef SQLITE_OMIT_AUTOVACUUM
55098 if( sCheck.anRef[i]==0 ){
55099 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
55101 #else
55102 /* If the database supports auto-vacuum, make sure no tables contain
55103 ** references to pointer-map pages.
55105 if( sCheck.anRef[i]==0 &&
55106 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
55107 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
55109 if( sCheck.anRef[i]!=0 &&
55110 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
55111 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
55113 #endif
55116 /* Make sure this analysis did not leave any unref() pages.
55117 ** This is an internal consistency check; an integrity check
55118 ** of the integrity check.
55120 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
55121 checkAppendMsg(&sCheck, 0,
55122 "Outstanding page count goes from %d to %d during this analysis",
55123 nRef, sqlite3PagerRefcount(pBt->pPager)
55127 /* Clean up and report errors.
55129 sqlite3BtreeLeave(p);
55130 sqlite3_free(sCheck.anRef);
55131 if( sCheck.mallocFailed ){
55132 sqlite3StrAccumReset(&sCheck.errMsg);
55133 *pnErr = sCheck.nErr+1;
55134 return 0;
55136 *pnErr = sCheck.nErr;
55137 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
55138 return sqlite3StrAccumFinish(&sCheck.errMsg);
55140 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55143 ** Return the full pathname of the underlying database file.
55145 ** The pager filename is invariant as long as the pager is
55146 ** open so it is safe to access without the BtShared mutex.
55148 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
55149 assert( p->pBt->pPager!=0 );
55150 return sqlite3PagerFilename(p->pBt->pPager);
55154 ** Return the pathname of the journal file for this database. The return
55155 ** value of this routine is the same regardless of whether the journal file
55156 ** has been created or not.
55158 ** The pager journal filename is invariant as long as the pager is
55159 ** open so it is safe to access without the BtShared mutex.
55161 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
55162 assert( p->pBt->pPager!=0 );
55163 return sqlite3PagerJournalname(p->pBt->pPager);
55167 ** Return non-zero if a transaction is active.
55169 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
55170 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
55171 return (p && (p->inTrans==TRANS_WRITE));
55174 #ifndef SQLITE_OMIT_WAL
55176 ** Run a checkpoint on the Btree passed as the first argument.
55178 ** Return SQLITE_LOCKED if this or any other connection has an open
55179 ** transaction on the shared-cache the argument Btree is connected to.
55181 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
55183 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
55184 int rc = SQLITE_OK;
55185 if( p ){
55186 BtShared *pBt = p->pBt;
55187 sqlite3BtreeEnter(p);
55188 if( pBt->inTransaction!=TRANS_NONE ){
55189 rc = SQLITE_LOCKED;
55190 }else{
55191 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
55193 sqlite3BtreeLeave(p);
55195 return rc;
55197 #endif
55200 ** Return non-zero if a read (or write) transaction is active.
55202 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
55203 assert( p );
55204 assert( sqlite3_mutex_held(p->db->mutex) );
55205 return p->inTrans!=TRANS_NONE;
55208 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
55209 assert( p );
55210 assert( sqlite3_mutex_held(p->db->mutex) );
55211 return p->nBackup!=0;
55215 ** This function returns a pointer to a blob of memory associated with
55216 ** a single shared-btree. The memory is used by client code for its own
55217 ** purposes (for example, to store a high-level schema associated with
55218 ** the shared-btree). The btree layer manages reference counting issues.
55220 ** The first time this is called on a shared-btree, nBytes bytes of memory
55221 ** are allocated, zeroed, and returned to the caller. For each subsequent
55222 ** call the nBytes parameter is ignored and a pointer to the same blob
55223 ** of memory returned.
55225 ** If the nBytes parameter is 0 and the blob of memory has not yet been
55226 ** allocated, a null pointer is returned. If the blob has already been
55227 ** allocated, it is returned as normal.
55229 ** Just before the shared-btree is closed, the function passed as the
55230 ** xFree argument when the memory allocation was made is invoked on the
55231 ** blob of allocated memory. The xFree function should not call sqlite3_free()
55232 ** on the memory, the btree layer does that.
55234 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
55235 BtShared *pBt = p->pBt;
55236 sqlite3BtreeEnter(p);
55237 if( !pBt->pSchema && nBytes ){
55238 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
55239 pBt->xFreeSchema = xFree;
55241 sqlite3BtreeLeave(p);
55242 return pBt->pSchema;
55246 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
55247 ** btree as the argument handle holds an exclusive lock on the
55248 ** sqlite_master table. Otherwise SQLITE_OK.
55250 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
55251 int rc;
55252 assert( sqlite3_mutex_held(p->db->mutex) );
55253 sqlite3BtreeEnter(p);
55254 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
55255 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
55256 sqlite3BtreeLeave(p);
55257 return rc;
55261 #ifndef SQLITE_OMIT_SHARED_CACHE
55263 ** Obtain a lock on the table whose root page is iTab. The
55264 ** lock is a write lock if isWritelock is true or a read lock
55265 ** if it is false.
55267 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
55268 int rc = SQLITE_OK;
55269 assert( p->inTrans!=TRANS_NONE );
55270 if( p->sharable ){
55271 u8 lockType = READ_LOCK + isWriteLock;
55272 assert( READ_LOCK+1==WRITE_LOCK );
55273 assert( isWriteLock==0 || isWriteLock==1 );
55275 sqlite3BtreeEnter(p);
55276 rc = querySharedCacheTableLock(p, iTab, lockType);
55277 if( rc==SQLITE_OK ){
55278 rc = setSharedCacheTableLock(p, iTab, lockType);
55280 sqlite3BtreeLeave(p);
55282 return rc;
55284 #endif
55286 #ifndef SQLITE_OMIT_INCRBLOB
55288 ** Argument pCsr must be a cursor opened for writing on an
55289 ** INTKEY table currently pointing at a valid table entry.
55290 ** This function modifies the data stored as part of that entry.
55292 ** Only the data content may only be modified, it is not possible to
55293 ** change the length of the data stored. If this function is called with
55294 ** parameters that attempt to write past the end of the existing data,
55295 ** no modifications are made and SQLITE_CORRUPT is returned.
55297 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
55298 int rc;
55299 assert( cursorHoldsMutex(pCsr) );
55300 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
55301 assert( pCsr->isIncrblobHandle );
55303 rc = restoreCursorPosition(pCsr);
55304 if( rc!=SQLITE_OK ){
55305 return rc;
55307 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
55308 if( pCsr->eState!=CURSOR_VALID ){
55309 return SQLITE_ABORT;
55312 /* Check some assumptions:
55313 ** (a) the cursor is open for writing,
55314 ** (b) there is a read/write transaction open,
55315 ** (c) the connection holds a write-lock on the table (if required),
55316 ** (d) there are no conflicting read-locks, and
55317 ** (e) the cursor points at a valid row of an intKey table.
55319 if( !pCsr->wrFlag ){
55320 return SQLITE_READONLY;
55322 assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
55323 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
55324 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
55325 assert( pCsr->apPage[pCsr->iPage]->intKey );
55327 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
55331 ** Set a flag on this cursor to cache the locations of pages from the
55332 ** overflow list for the current row. This is used by cursors opened
55333 ** for incremental blob IO only.
55335 ** This function sets a flag only. The actual page location cache
55336 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
55337 ** accessPayload() (the worker function for sqlite3BtreeData() and
55338 ** sqlite3BtreePutData()).
55340 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
55341 assert( cursorHoldsMutex(pCur) );
55342 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55343 invalidateOverflowCache(pCur);
55344 pCur->isIncrblobHandle = 1;
55346 #endif
55349 ** Set both the "read version" (single byte at byte offset 18) and
55350 ** "write version" (single byte at byte offset 19) fields in the database
55351 ** header to iVersion.
55353 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
55354 BtShared *pBt = pBtree->pBt;
55355 int rc; /* Return code */
55357 assert( pBtree->inTrans==TRANS_NONE );
55358 assert( iVersion==1 || iVersion==2 );
55360 /* If setting the version fields to 1, do not automatically open the
55361 ** WAL connection, even if the version fields are currently set to 2.
55363 pBt->doNotUseWAL = (u8)(iVersion==1);
55365 rc = sqlite3BtreeBeginTrans(pBtree, 0);
55366 if( rc==SQLITE_OK ){
55367 u8 *aData = pBt->pPage1->aData;
55368 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
55369 rc = sqlite3BtreeBeginTrans(pBtree, 2);
55370 if( rc==SQLITE_OK ){
55371 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55372 if( rc==SQLITE_OK ){
55373 aData[18] = (u8)iVersion;
55374 aData[19] = (u8)iVersion;
55380 pBt->doNotUseWAL = 0;
55381 return rc;
55384 /************** End of btree.c ***********************************************/
55385 /************** Begin file backup.c ******************************************/
55387 ** 2009 January 28
55389 ** The author disclaims copyright to this source code. In place of
55390 ** a legal notice, here is a blessing:
55392 ** May you do good and not evil.
55393 ** May you find forgiveness for yourself and forgive others.
55394 ** May you share freely, never taking more than you give.
55396 *************************************************************************
55397 ** This file contains the implementation of the sqlite3_backup_XXX()
55398 ** API functions and the related features.
55401 /* Macro to find the minimum of two numeric values.
55403 #ifndef MIN
55404 # define MIN(x,y) ((x)<(y)?(x):(y))
55405 #endif
55408 ** Structure allocated for each backup operation.
55410 struct sqlite3_backup {
55411 sqlite3* pDestDb; /* Destination database handle */
55412 Btree *pDest; /* Destination b-tree file */
55413 u32 iDestSchema; /* Original schema cookie in destination */
55414 int bDestLocked; /* True once a write-transaction is open on pDest */
55416 Pgno iNext; /* Page number of the next source page to copy */
55417 sqlite3* pSrcDb; /* Source database handle */
55418 Btree *pSrc; /* Source b-tree file */
55420 int rc; /* Backup process error code */
55422 /* These two variables are set by every call to backup_step(). They are
55423 ** read by calls to backup_remaining() and backup_pagecount().
55425 Pgno nRemaining; /* Number of pages left to copy */
55426 Pgno nPagecount; /* Total number of pages to copy */
55428 int isAttached; /* True once backup has been registered with pager */
55429 sqlite3_backup *pNext; /* Next backup associated with source pager */
55433 ** THREAD SAFETY NOTES:
55435 ** Once it has been created using backup_init(), a single sqlite3_backup
55436 ** structure may be accessed via two groups of thread-safe entry points:
55438 ** * Via the sqlite3_backup_XXX() API function backup_step() and
55439 ** backup_finish(). Both these functions obtain the source database
55440 ** handle mutex and the mutex associated with the source BtShared
55441 ** structure, in that order.
55443 ** * Via the BackupUpdate() and BackupRestart() functions, which are
55444 ** invoked by the pager layer to report various state changes in
55445 ** the page cache associated with the source database. The mutex
55446 ** associated with the source database BtShared structure will always
55447 ** be held when either of these functions are invoked.
55449 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
55450 ** backup_pagecount() are not thread-safe functions. If they are called
55451 ** while some other thread is calling backup_step() or backup_finish(),
55452 ** the values returned may be invalid. There is no way for a call to
55453 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
55454 ** or backup_pagecount().
55456 ** Depending on the SQLite configuration, the database handles and/or
55457 ** the Btree objects may have their own mutexes that require locking.
55458 ** Non-sharable Btrees (in-memory databases for example), do not have
55459 ** associated mutexes.
55463 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
55464 ** in connection handle pDb. If such a database cannot be found, return
55465 ** a NULL pointer and write an error message to pErrorDb.
55467 ** If the "temp" database is requested, it may need to be opened by this
55468 ** function. If an error occurs while doing so, return 0 and write an
55469 ** error message to pErrorDb.
55471 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
55472 int i = sqlite3FindDbName(pDb, zDb);
55474 if( i==1 ){
55475 Parse *pParse;
55476 int rc = 0;
55477 pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
55478 if( pParse==0 ){
55479 sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
55480 rc = SQLITE_NOMEM;
55481 }else{
55482 pParse->db = pDb;
55483 if( sqlite3OpenTempDatabase(pParse) ){
55484 sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
55485 rc = SQLITE_ERROR;
55487 sqlite3DbFree(pErrorDb, pParse->zErrMsg);
55488 sqlite3StackFree(pErrorDb, pParse);
55490 if( rc ){
55491 return 0;
55495 if( i<0 ){
55496 sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
55497 return 0;
55500 return pDb->aDb[i].pBt;
55504 ** Attempt to set the page size of the destination to match the page size
55505 ** of the source.
55507 static int setDestPgsz(sqlite3_backup *p){
55508 int rc;
55509 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
55510 return rc;
55514 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
55515 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
55516 ** a pointer to the new sqlite3_backup object.
55518 ** If an error occurs, NULL is returned and an error code and error message
55519 ** stored in database handle pDestDb.
55521 SQLITE_API sqlite3_backup *sqlite3_backup_init(
55522 sqlite3* pDestDb, /* Database to write to */
55523 const char *zDestDb, /* Name of database within pDestDb */
55524 sqlite3* pSrcDb, /* Database connection to read from */
55525 const char *zSrcDb /* Name of database within pSrcDb */
55527 sqlite3_backup *p; /* Value to return */
55529 /* Lock the source database handle. The destination database
55530 ** handle is not locked in this routine, but it is locked in
55531 ** sqlite3_backup_step(). The user is required to ensure that no
55532 ** other thread accesses the destination handle for the duration
55533 ** of the backup operation. Any attempt to use the destination
55534 ** database connection while a backup is in progress may cause
55535 ** a malfunction or a deadlock.
55537 sqlite3_mutex_enter(pSrcDb->mutex);
55538 sqlite3_mutex_enter(pDestDb->mutex);
55540 if( pSrcDb==pDestDb ){
55541 sqlite3Error(
55542 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
55544 p = 0;
55545 }else {
55546 /* Allocate space for a new sqlite3_backup object...
55547 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
55548 ** call to sqlite3_backup_init() and is destroyed by a call to
55549 ** sqlite3_backup_finish(). */
55550 p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
55551 if( !p ){
55552 sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
55556 /* If the allocation succeeded, populate the new object. */
55557 if( p ){
55558 memset(p, 0, sizeof(sqlite3_backup));
55559 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
55560 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
55561 p->pDestDb = pDestDb;
55562 p->pSrcDb = pSrcDb;
55563 p->iNext = 1;
55564 p->isAttached = 0;
55566 if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
55567 /* One (or both) of the named databases did not exist or an OOM
55568 ** error was hit. The error has already been written into the
55569 ** pDestDb handle. All that is left to do here is free the
55570 ** sqlite3_backup structure.
55572 sqlite3_free(p);
55573 p = 0;
55576 if( p ){
55577 p->pSrc->nBackup++;
55580 sqlite3_mutex_leave(pDestDb->mutex);
55581 sqlite3_mutex_leave(pSrcDb->mutex);
55582 return p;
55586 ** Argument rc is an SQLite error code. Return true if this error is
55587 ** considered fatal if encountered during a backup operation. All errors
55588 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
55590 static int isFatalError(int rc){
55591 return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
55595 ** Parameter zSrcData points to a buffer containing the data for
55596 ** page iSrcPg from the source database. Copy this data into the
55597 ** destination database.
55599 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
55600 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
55601 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
55602 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
55603 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
55604 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
55605 #ifdef SQLITE_HAS_CODEC
55606 int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
55607 int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
55608 #endif
55610 int rc = SQLITE_OK;
55611 i64 iOff;
55613 assert( p->bDestLocked );
55614 assert( !isFatalError(p->rc) );
55615 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
55616 assert( zSrcData );
55618 /* Catch the case where the destination is an in-memory database and the
55619 ** page sizes of the source and destination differ.
55621 if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
55622 rc = SQLITE_READONLY;
55625 #ifdef SQLITE_HAS_CODEC
55626 /* Backup is not possible if the page size of the destination is changing
55627 ** and a codec is in use.
55629 if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
55630 rc = SQLITE_READONLY;
55633 /* Backup is not possible if the number of bytes of reserve space differ
55634 ** between source and destination. If there is a difference, try to
55635 ** fix the destination to agree with the source. If that is not possible,
55636 ** then the backup cannot proceed.
55638 if( nSrcReserve!=nDestReserve ){
55639 u32 newPgsz = nSrcPgsz;
55640 rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
55641 if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
55643 #endif
55645 /* This loop runs once for each destination page spanned by the source
55646 ** page. For each iteration, variable iOff is set to the byte offset
55647 ** of the destination page.
55649 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
55650 DbPage *pDestPg = 0;
55651 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
55652 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
55653 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
55654 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
55656 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
55657 u8 *zDestData = sqlite3PagerGetData(pDestPg);
55658 u8 *zOut = &zDestData[iOff%nDestPgsz];
55660 /* Copy the data from the source page into the destination page.
55661 ** Then clear the Btree layer MemPage.isInit flag. Both this module
55662 ** and the pager code use this trick (clearing the first byte
55663 ** of the page 'extra' space to invalidate the Btree layers
55664 ** cached parse of the page). MemPage.isInit is marked
55665 ** "MUST BE FIRST" for this purpose.
55667 memcpy(zOut, zIn, nCopy);
55668 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
55670 sqlite3PagerUnref(pDestPg);
55673 return rc;
55677 ** If pFile is currently larger than iSize bytes, then truncate it to
55678 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
55679 ** this function is a no-op.
55681 ** Return SQLITE_OK if everything is successful, or an SQLite error
55682 ** code if an error occurs.
55684 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
55685 i64 iCurrent;
55686 int rc = sqlite3OsFileSize(pFile, &iCurrent);
55687 if( rc==SQLITE_OK && iCurrent>iSize ){
55688 rc = sqlite3OsTruncate(pFile, iSize);
55690 return rc;
55694 ** Register this backup object with the associated source pager for
55695 ** callbacks when pages are changed or the cache invalidated.
55697 static void attachBackupObject(sqlite3_backup *p){
55698 sqlite3_backup **pp;
55699 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
55700 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
55701 p->pNext = *pp;
55702 *pp = p;
55703 p->isAttached = 1;
55707 ** Copy nPage pages from the source b-tree to the destination.
55709 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
55710 int rc;
55711 int destMode; /* Destination journal mode */
55712 int pgszSrc = 0; /* Source page size */
55713 int pgszDest = 0; /* Destination page size */
55715 sqlite3_mutex_enter(p->pSrcDb->mutex);
55716 sqlite3BtreeEnter(p->pSrc);
55717 if( p->pDestDb ){
55718 sqlite3_mutex_enter(p->pDestDb->mutex);
55721 rc = p->rc;
55722 if( !isFatalError(rc) ){
55723 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
55724 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
55725 int ii; /* Iterator variable */
55726 int nSrcPage = -1; /* Size of source db in pages */
55727 int bCloseTrans = 0; /* True if src db requires unlocking */
55729 /* If the source pager is currently in a write-transaction, return
55730 ** SQLITE_BUSY immediately.
55732 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
55733 rc = SQLITE_BUSY;
55734 }else{
55735 rc = SQLITE_OK;
55738 /* Lock the destination database, if it is not locked already. */
55739 if( SQLITE_OK==rc && p->bDestLocked==0
55740 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
55742 p->bDestLocked = 1;
55743 sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
55746 /* If there is no open read-transaction on the source database, open
55747 ** one now. If a transaction is opened here, then it will be closed
55748 ** before this function exits.
55750 if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
55751 rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
55752 bCloseTrans = 1;
55755 /* Do not allow backup if the destination database is in WAL mode
55756 ** and the page sizes are different between source and destination */
55757 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
55758 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
55759 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
55760 if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
55761 rc = SQLITE_READONLY;
55764 /* Now that there is a read-lock on the source database, query the
55765 ** source pager for the number of pages in the database.
55767 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
55768 assert( nSrcPage>=0 );
55769 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
55770 const Pgno iSrcPg = p->iNext; /* Source page number */
55771 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
55772 DbPage *pSrcPg; /* Source page object */
55773 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
55774 if( rc==SQLITE_OK ){
55775 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
55776 sqlite3PagerUnref(pSrcPg);
55779 p->iNext++;
55781 if( rc==SQLITE_OK ){
55782 p->nPagecount = nSrcPage;
55783 p->nRemaining = nSrcPage+1-p->iNext;
55784 if( p->iNext>(Pgno)nSrcPage ){
55785 rc = SQLITE_DONE;
55786 }else if( !p->isAttached ){
55787 attachBackupObject(p);
55791 /* Update the schema version field in the destination database. This
55792 ** is to make sure that the schema-version really does change in
55793 ** the case where the source and destination databases have the
55794 ** same schema version.
55796 if( rc==SQLITE_DONE
55797 && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
55799 int nDestTruncate;
55801 if( p->pDestDb ){
55802 sqlite3ResetInternalSchema(p->pDestDb, -1);
55805 /* Set nDestTruncate to the final number of pages in the destination
55806 ** database. The complication here is that the destination page
55807 ** size may be different to the source page size.
55809 ** If the source page size is smaller than the destination page size,
55810 ** round up. In this case the call to sqlite3OsTruncate() below will
55811 ** fix the size of the file. However it is important to call
55812 ** sqlite3PagerTruncateImage() here so that any pages in the
55813 ** destination file that lie beyond the nDestTruncate page mark are
55814 ** journalled by PagerCommitPhaseOne() before they are destroyed
55815 ** by the file truncation.
55817 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
55818 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
55819 if( pgszSrc<pgszDest ){
55820 int ratio = pgszDest/pgszSrc;
55821 nDestTruncate = (nSrcPage+ratio-1)/ratio;
55822 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
55823 nDestTruncate--;
55825 }else{
55826 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
55828 sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
55830 if( pgszSrc<pgszDest ){
55831 /* If the source page-size is smaller than the destination page-size,
55832 ** two extra things may need to happen:
55834 ** * The destination may need to be truncated, and
55836 ** * Data stored on the pages immediately following the
55837 ** pending-byte page in the source database may need to be
55838 ** copied into the destination database.
55840 const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
55841 sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
55842 i64 iOff;
55843 i64 iEnd;
55845 assert( pFile );
55846 assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
55847 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
55848 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
55851 /* This call ensures that all data required to recreate the original
55852 ** database has been stored in the journal for pDestPager and the
55853 ** journal synced to disk. So at this point we may safely modify
55854 ** the database file in any way, knowing that if a power failure
55855 ** occurs, the original database will be reconstructed from the
55856 ** journal file. */
55857 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
55859 /* Write the extra pages and truncate the database file as required. */
55860 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
55861 for(
55862 iOff=PENDING_BYTE+pgszSrc;
55863 rc==SQLITE_OK && iOff<iEnd;
55864 iOff+=pgszSrc
55866 PgHdr *pSrcPg = 0;
55867 const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
55868 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
55869 if( rc==SQLITE_OK ){
55870 u8 *zData = sqlite3PagerGetData(pSrcPg);
55871 rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
55873 sqlite3PagerUnref(pSrcPg);
55875 if( rc==SQLITE_OK ){
55876 rc = backupTruncateFile(pFile, iSize);
55879 /* Sync the database file to disk. */
55880 if( rc==SQLITE_OK ){
55881 rc = sqlite3PagerSync(pDestPager);
55883 }else{
55884 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
55887 /* Finish committing the transaction to the destination database. */
55888 if( SQLITE_OK==rc
55889 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
55891 rc = SQLITE_DONE;
55895 /* If bCloseTrans is true, then this function opened a read transaction
55896 ** on the source database. Close the read transaction here. There is
55897 ** no need to check the return values of the btree methods here, as
55898 ** "committing" a read-only transaction cannot fail.
55900 if( bCloseTrans ){
55901 TESTONLY( int rc2 );
55902 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
55903 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
55904 assert( rc2==SQLITE_OK );
55907 if( rc==SQLITE_IOERR_NOMEM ){
55908 rc = SQLITE_NOMEM;
55910 p->rc = rc;
55912 if( p->pDestDb ){
55913 sqlite3_mutex_leave(p->pDestDb->mutex);
55915 sqlite3BtreeLeave(p->pSrc);
55916 sqlite3_mutex_leave(p->pSrcDb->mutex);
55917 return rc;
55921 ** Release all resources associated with an sqlite3_backup* handle.
55923 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
55924 sqlite3_backup **pp; /* Ptr to head of pagers backup list */
55925 sqlite3_mutex *mutex; /* Mutex to protect source database */
55926 int rc; /* Value to return */
55928 /* Enter the mutexes */
55929 if( p==0 ) return SQLITE_OK;
55930 sqlite3_mutex_enter(p->pSrcDb->mutex);
55931 sqlite3BtreeEnter(p->pSrc);
55932 mutex = p->pSrcDb->mutex;
55933 if( p->pDestDb ){
55934 sqlite3_mutex_enter(p->pDestDb->mutex);
55937 /* Detach this backup from the source pager. */
55938 if( p->pDestDb ){
55939 p->pSrc->nBackup--;
55941 if( p->isAttached ){
55942 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
55943 while( *pp!=p ){
55944 pp = &(*pp)->pNext;
55946 *pp = p->pNext;
55949 /* If a transaction is still open on the Btree, roll it back. */
55950 sqlite3BtreeRollback(p->pDest);
55952 /* Set the error code of the destination database handle. */
55953 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
55954 sqlite3Error(p->pDestDb, rc, 0);
55956 /* Exit the mutexes and free the backup context structure. */
55957 if( p->pDestDb ){
55958 sqlite3_mutex_leave(p->pDestDb->mutex);
55960 sqlite3BtreeLeave(p->pSrc);
55961 if( p->pDestDb ){
55962 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
55963 ** call to sqlite3_backup_init() and is destroyed by a call to
55964 ** sqlite3_backup_finish(). */
55965 sqlite3_free(p);
55967 sqlite3_mutex_leave(mutex);
55968 return rc;
55972 ** Return the number of pages still to be backed up as of the most recent
55973 ** call to sqlite3_backup_step().
55975 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
55976 return p->nRemaining;
55980 ** Return the total number of pages in the source database as of the most
55981 ** recent call to sqlite3_backup_step().
55983 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
55984 return p->nPagecount;
55988 ** This function is called after the contents of page iPage of the
55989 ** source database have been modified. If page iPage has already been
55990 ** copied into the destination database, then the data written to the
55991 ** destination is now invalidated. The destination copy of iPage needs
55992 ** to be updated with the new data before the backup operation is
55993 ** complete.
55995 ** It is assumed that the mutex associated with the BtShared object
55996 ** corresponding to the source database is held when this function is
55997 ** called.
55999 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
56000 sqlite3_backup *p; /* Iterator variable */
56001 for(p=pBackup; p; p=p->pNext){
56002 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
56003 if( !isFatalError(p->rc) && iPage<p->iNext ){
56004 /* The backup process p has already copied page iPage. But now it
56005 ** has been modified by a transaction on the source pager. Copy
56006 ** the new data into the backup.
56008 int rc;
56009 assert( p->pDestDb );
56010 sqlite3_mutex_enter(p->pDestDb->mutex);
56011 rc = backupOnePage(p, iPage, aData);
56012 sqlite3_mutex_leave(p->pDestDb->mutex);
56013 assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
56014 if( rc!=SQLITE_OK ){
56015 p->rc = rc;
56022 ** Restart the backup process. This is called when the pager layer
56023 ** detects that the database has been modified by an external database
56024 ** connection. In this case there is no way of knowing which of the
56025 ** pages that have been copied into the destination database are still
56026 ** valid and which are not, so the entire process needs to be restarted.
56028 ** It is assumed that the mutex associated with the BtShared object
56029 ** corresponding to the source database is held when this function is
56030 ** called.
56032 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
56033 sqlite3_backup *p; /* Iterator variable */
56034 for(p=pBackup; p; p=p->pNext){
56035 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
56036 p->iNext = 1;
56040 #ifndef SQLITE_OMIT_VACUUM
56042 ** Copy the complete content of pBtFrom into pBtTo. A transaction
56043 ** must be active for both files.
56045 ** The size of file pTo may be reduced by this operation. If anything
56046 ** goes wrong, the transaction on pTo is rolled back. If successful, the
56047 ** transaction is committed before returning.
56049 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
56050 int rc;
56051 sqlite3_backup b;
56052 sqlite3BtreeEnter(pTo);
56053 sqlite3BtreeEnter(pFrom);
56055 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
56056 ** to 0. This is used by the implementations of sqlite3_backup_step()
56057 ** and sqlite3_backup_finish() to detect that they are being called
56058 ** from this function, not directly by the user.
56060 memset(&b, 0, sizeof(b));
56061 b.pSrcDb = pFrom->db;
56062 b.pSrc = pFrom;
56063 b.pDest = pTo;
56064 b.iNext = 1;
56066 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
56067 ** file. By passing this as the number of pages to copy to
56068 ** sqlite3_backup_step(), we can guarantee that the copy finishes
56069 ** within a single call (unless an error occurs). The assert() statement
56070 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
56071 ** or an error code.
56073 sqlite3_backup_step(&b, 0x7FFFFFFF);
56074 assert( b.rc!=SQLITE_OK );
56075 rc = sqlite3_backup_finish(&b);
56076 if( rc==SQLITE_OK ){
56077 pTo->pBt->pageSizeFixed = 0;
56080 sqlite3BtreeLeave(pFrom);
56081 sqlite3BtreeLeave(pTo);
56082 return rc;
56084 #endif /* SQLITE_OMIT_VACUUM */
56086 /************** End of backup.c **********************************************/
56087 /************** Begin file vdbemem.c *****************************************/
56089 ** 2004 May 26
56091 ** The author disclaims copyright to this source code. In place of
56092 ** a legal notice, here is a blessing:
56094 ** May you do good and not evil.
56095 ** May you find forgiveness for yourself and forgive others.
56096 ** May you share freely, never taking more than you give.
56098 *************************************************************************
56100 ** This file contains code use to manipulate "Mem" structure. A "Mem"
56101 ** stores a single value in the VDBE. Mem is an opaque structure visible
56102 ** only within the VDBE. Interface routines refer to a Mem using the
56103 ** name sqlite_value
56107 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
56108 ** P if required.
56110 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
56113 ** If pMem is an object with a valid string representation, this routine
56114 ** ensures the internal encoding for the string representation is
56115 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
56117 ** If pMem is not a string object, or the encoding of the string
56118 ** representation is already stored using the requested encoding, then this
56119 ** routine is a no-op.
56121 ** SQLITE_OK is returned if the conversion is successful (or not required).
56122 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
56123 ** between formats.
56125 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
56126 int rc;
56127 assert( (pMem->flags&MEM_RowSet)==0 );
56128 assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
56129 || desiredEnc==SQLITE_UTF16BE );
56130 if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
56131 return SQLITE_OK;
56133 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56134 #ifdef SQLITE_OMIT_UTF16
56135 return SQLITE_ERROR;
56136 #else
56138 /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
56139 ** then the encoding of the value may not have changed.
56141 rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
56142 assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
56143 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
56144 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
56145 return rc;
56146 #endif
56150 ** Make sure pMem->z points to a writable allocation of at least
56151 ** n bytes.
56153 ** If the memory cell currently contains string or blob data
56154 ** and the third argument passed to this function is true, the
56155 ** current content of the cell is preserved. Otherwise, it may
56156 ** be discarded.
56158 ** This function sets the MEM_Dyn flag and clears any xDel callback.
56159 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
56160 ** not set, Mem.n is zeroed.
56162 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
56163 assert( 1 >=
56164 ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
56165 (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
56166 ((pMem->flags&MEM_Ephem) ? 1 : 0) +
56167 ((pMem->flags&MEM_Static) ? 1 : 0)
56169 assert( (pMem->flags&MEM_RowSet)==0 );
56171 if( n<32 ) n = 32;
56172 if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
56173 if( preserve && pMem->z==pMem->zMalloc ){
56174 pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
56175 preserve = 0;
56176 }else{
56177 sqlite3DbFree(pMem->db, pMem->zMalloc);
56178 pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
56182 if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
56183 memcpy(pMem->zMalloc, pMem->z, pMem->n);
56185 if( pMem->flags&MEM_Dyn && pMem->xDel ){
56186 pMem->xDel((void *)(pMem->z));
56189 pMem->z = pMem->zMalloc;
56190 if( pMem->z==0 ){
56191 pMem->flags = MEM_Null;
56192 }else{
56193 pMem->flags &= ~(MEM_Ephem|MEM_Static);
56195 pMem->xDel = 0;
56196 return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
56200 ** Make the given Mem object MEM_Dyn. In other words, make it so
56201 ** that any TEXT or BLOB content is stored in memory obtained from
56202 ** malloc(). In this way, we know that the memory is safe to be
56203 ** overwritten or altered.
56205 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
56207 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
56208 int f;
56209 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56210 assert( (pMem->flags&MEM_RowSet)==0 );
56211 expandBlob(pMem);
56212 f = pMem->flags;
56213 if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
56214 if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
56215 return SQLITE_NOMEM;
56217 pMem->z[pMem->n] = 0;
56218 pMem->z[pMem->n+1] = 0;
56219 pMem->flags |= MEM_Term;
56220 #ifdef SQLITE_DEBUG
56221 pMem->pScopyFrom = 0;
56222 #endif
56225 return SQLITE_OK;
56229 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
56230 ** blob stored in dynamically allocated space.
56232 #ifndef SQLITE_OMIT_INCRBLOB
56233 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
56234 if( pMem->flags & MEM_Zero ){
56235 int nByte;
56236 assert( pMem->flags&MEM_Blob );
56237 assert( (pMem->flags&MEM_RowSet)==0 );
56238 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56240 /* Set nByte to the number of bytes required to store the expanded blob. */
56241 nByte = pMem->n + pMem->u.nZero;
56242 if( nByte<=0 ){
56243 nByte = 1;
56245 if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
56246 return SQLITE_NOMEM;
56249 memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
56250 pMem->n += pMem->u.nZero;
56251 pMem->flags &= ~(MEM_Zero|MEM_Term);
56253 return SQLITE_OK;
56255 #endif
56259 ** Make sure the given Mem is \u0000 terminated.
56261 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
56262 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56263 if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
56264 return SQLITE_OK; /* Nothing to do */
56266 if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
56267 return SQLITE_NOMEM;
56269 pMem->z[pMem->n] = 0;
56270 pMem->z[pMem->n+1] = 0;
56271 pMem->flags |= MEM_Term;
56272 return SQLITE_OK;
56276 ** Add MEM_Str to the set of representations for the given Mem. Numbers
56277 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
56278 ** is a no-op.
56280 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
56282 ** A MEM_Null value will never be passed to this function. This function is
56283 ** used for converting values to text for returning to the user (i.e. via
56284 ** sqlite3_value_text()), or for ensuring that values to be used as btree
56285 ** keys are strings. In the former case a NULL pointer is returned the
56286 ** user and the later is an internal programming error.
56288 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
56289 int rc = SQLITE_OK;
56290 int fg = pMem->flags;
56291 const int nByte = 32;
56293 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56294 assert( !(fg&MEM_Zero) );
56295 assert( !(fg&(MEM_Str|MEM_Blob)) );
56296 assert( fg&(MEM_Int|MEM_Real) );
56297 assert( (pMem->flags&MEM_RowSet)==0 );
56298 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56301 if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
56302 return SQLITE_NOMEM;
56305 /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
56306 ** string representation of the value. Then, if the required encoding
56307 ** is UTF-16le or UTF-16be do a translation.
56309 ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
56311 if( fg & MEM_Int ){
56312 sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
56313 }else{
56314 assert( fg & MEM_Real );
56315 sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
56317 pMem->n = sqlite3Strlen30(pMem->z);
56318 pMem->enc = SQLITE_UTF8;
56319 pMem->flags |= MEM_Str|MEM_Term;
56320 sqlite3VdbeChangeEncoding(pMem, enc);
56321 return rc;
56325 ** Memory cell pMem contains the context of an aggregate function.
56326 ** This routine calls the finalize method for that function. The
56327 ** result of the aggregate is stored back into pMem.
56329 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
56330 ** otherwise.
56332 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
56333 int rc = SQLITE_OK;
56334 if( ALWAYS(pFunc && pFunc->xFinalize) ){
56335 sqlite3_context ctx;
56336 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
56337 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56338 memset(&ctx, 0, sizeof(ctx));
56339 ctx.s.flags = MEM_Null;
56340 ctx.s.db = pMem->db;
56341 ctx.pMem = pMem;
56342 ctx.pFunc = pFunc;
56343 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
56344 assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
56345 sqlite3DbFree(pMem->db, pMem->zMalloc);
56346 memcpy(pMem, &ctx.s, sizeof(ctx.s));
56347 rc = ctx.isError;
56349 return rc;
56353 ** If the memory cell contains a string value that must be freed by
56354 ** invoking an external callback, free it now. Calling this function
56355 ** does not free any Mem.zMalloc buffer.
56357 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
56358 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
56359 testcase( p->flags & MEM_Agg );
56360 testcase( p->flags & MEM_Dyn );
56361 testcase( p->flags & MEM_RowSet );
56362 testcase( p->flags & MEM_Frame );
56363 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
56364 if( p->flags&MEM_Agg ){
56365 sqlite3VdbeMemFinalize(p, p->u.pDef);
56366 assert( (p->flags & MEM_Agg)==0 );
56367 sqlite3VdbeMemRelease(p);
56368 }else if( p->flags&MEM_Dyn && p->xDel ){
56369 assert( (p->flags&MEM_RowSet)==0 );
56370 p->xDel((void *)p->z);
56371 p->xDel = 0;
56372 }else if( p->flags&MEM_RowSet ){
56373 sqlite3RowSetClear(p->u.pRowSet);
56374 }else if( p->flags&MEM_Frame ){
56375 sqlite3VdbeMemSetNull(p);
56381 ** Release any memory held by the Mem. This may leave the Mem in an
56382 ** inconsistent state, for example with (Mem.z==0) and
56383 ** (Mem.type==SQLITE_TEXT).
56385 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
56386 sqlite3VdbeMemReleaseExternal(p);
56387 sqlite3DbFree(p->db, p->zMalloc);
56388 p->z = 0;
56389 p->zMalloc = 0;
56390 p->xDel = 0;
56394 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
56395 ** If the double is too large, return 0x8000000000000000.
56397 ** Most systems appear to do this simply by assigning
56398 ** variables and without the extra range tests. But
56399 ** there are reports that windows throws an expection
56400 ** if the floating point value is out of range. (See ticket #2880.)
56401 ** Because we do not completely understand the problem, we will
56402 ** take the conservative approach and always do range tests
56403 ** before attempting the conversion.
56405 static i64 doubleToInt64(double r){
56406 #ifdef SQLITE_OMIT_FLOATING_POINT
56407 /* When floating-point is omitted, double and int64 are the same thing */
56408 return r;
56409 #else
56411 ** Many compilers we encounter do not define constants for the
56412 ** minimum and maximum 64-bit integers, or they define them
56413 ** inconsistently. And many do not understand the "LL" notation.
56414 ** So we define our own static constants here using nothing
56415 ** larger than a 32-bit integer constant.
56417 static const i64 maxInt = LARGEST_INT64;
56418 static const i64 minInt = SMALLEST_INT64;
56420 if( r<(double)minInt ){
56421 return minInt;
56422 }else if( r>(double)maxInt ){
56423 /* minInt is correct here - not maxInt. It turns out that assigning
56424 ** a very large positive number to an integer results in a very large
56425 ** negative integer. This makes no sense, but it is what x86 hardware
56426 ** does so for compatibility we will do the same in software. */
56427 return minInt;
56428 }else{
56429 return (i64)r;
56431 #endif
56435 ** Return some kind of integer value which is the best we can do
56436 ** at representing the value that *pMem describes as an integer.
56437 ** If pMem is an integer, then the value is exact. If pMem is
56438 ** a floating-point then the value returned is the integer part.
56439 ** If pMem is a string or blob, then we make an attempt to convert
56440 ** it into a integer and return that. If pMem represents an
56441 ** an SQL-NULL value, return 0.
56443 ** If pMem represents a string value, its encoding might be changed.
56445 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
56446 int flags;
56447 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56448 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56449 flags = pMem->flags;
56450 if( flags & MEM_Int ){
56451 return pMem->u.i;
56452 }else if( flags & MEM_Real ){
56453 return doubleToInt64(pMem->r);
56454 }else if( flags & (MEM_Str|MEM_Blob) ){
56455 i64 value = 0;
56456 assert( pMem->z || pMem->n==0 );
56457 testcase( pMem->z==0 );
56458 sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
56459 return value;
56460 }else{
56461 return 0;
56466 ** Return the best representation of pMem that we can get into a
56467 ** double. If pMem is already a double or an integer, return its
56468 ** value. If it is a string or blob, try to convert it to a double.
56469 ** If it is a NULL, return 0.0.
56471 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
56472 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56473 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56474 if( pMem->flags & MEM_Real ){
56475 return pMem->r;
56476 }else if( pMem->flags & MEM_Int ){
56477 return (double)pMem->u.i;
56478 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
56479 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56480 double val = (double)0;
56481 sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
56482 return val;
56483 }else{
56484 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56485 return (double)0;
56490 ** The MEM structure is already a MEM_Real. Try to also make it a
56491 ** MEM_Int if we can.
56493 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
56494 assert( pMem->flags & MEM_Real );
56495 assert( (pMem->flags & MEM_RowSet)==0 );
56496 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56497 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56499 pMem->u.i = doubleToInt64(pMem->r);
56501 /* Only mark the value as an integer if
56503 ** (1) the round-trip conversion real->int->real is a no-op, and
56504 ** (2) The integer is neither the largest nor the smallest
56505 ** possible integer (ticket #3922)
56507 ** The second and third terms in the following conditional enforces
56508 ** the second condition under the assumption that addition overflow causes
56509 ** values to wrap around. On x86 hardware, the third term is always
56510 ** true and could be omitted. But we leave it in because other
56511 ** architectures might behave differently.
56513 if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
56514 && ALWAYS(pMem->u.i<LARGEST_INT64) ){
56515 pMem->flags |= MEM_Int;
56520 ** Convert pMem to type integer. Invalidate any prior representations.
56522 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
56523 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56524 assert( (pMem->flags & MEM_RowSet)==0 );
56525 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56527 pMem->u.i = sqlite3VdbeIntValue(pMem);
56528 MemSetTypeFlag(pMem, MEM_Int);
56529 return SQLITE_OK;
56533 ** Convert pMem so that it is of type MEM_Real.
56534 ** Invalidate any prior representations.
56536 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
56537 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56538 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56540 pMem->r = sqlite3VdbeRealValue(pMem);
56541 MemSetTypeFlag(pMem, MEM_Real);
56542 return SQLITE_OK;
56546 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
56547 ** Invalidate any prior representations.
56549 ** Every effort is made to force the conversion, even if the input
56550 ** is a string that does not look completely like a number. Convert
56551 ** as much of the string as we can and ignore the rest.
56553 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
56554 if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
56555 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
56556 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56557 if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
56558 MemSetTypeFlag(pMem, MEM_Int);
56559 }else{
56560 pMem->r = sqlite3VdbeRealValue(pMem);
56561 MemSetTypeFlag(pMem, MEM_Real);
56562 sqlite3VdbeIntegerAffinity(pMem);
56565 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
56566 pMem->flags &= ~(MEM_Str|MEM_Blob);
56567 return SQLITE_OK;
56571 ** Delete any previous value and set the value stored in *pMem to NULL.
56573 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
56574 if( pMem->flags & MEM_Frame ){
56575 VdbeFrame *pFrame = pMem->u.pFrame;
56576 pFrame->pParent = pFrame->v->pDelFrame;
56577 pFrame->v->pDelFrame = pFrame;
56579 if( pMem->flags & MEM_RowSet ){
56580 sqlite3RowSetClear(pMem->u.pRowSet);
56582 MemSetTypeFlag(pMem, MEM_Null);
56583 pMem->type = SQLITE_NULL;
56587 ** Delete any previous value and set the value to be a BLOB of length
56588 ** n containing all zeros.
56590 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
56591 sqlite3VdbeMemRelease(pMem);
56592 pMem->flags = MEM_Blob|MEM_Zero;
56593 pMem->type = SQLITE_BLOB;
56594 pMem->n = 0;
56595 if( n<0 ) n = 0;
56596 pMem->u.nZero = n;
56597 pMem->enc = SQLITE_UTF8;
56599 #ifdef SQLITE_OMIT_INCRBLOB
56600 sqlite3VdbeMemGrow(pMem, n, 0);
56601 if( pMem->z ){
56602 pMem->n = n;
56603 memset(pMem->z, 0, n);
56605 #endif
56609 ** Delete any previous value and set the value stored in *pMem to val,
56610 ** manifest type INTEGER.
56612 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
56613 sqlite3VdbeMemRelease(pMem);
56614 pMem->u.i = val;
56615 pMem->flags = MEM_Int;
56616 pMem->type = SQLITE_INTEGER;
56619 #ifndef SQLITE_OMIT_FLOATING_POINT
56621 ** Delete any previous value and set the value stored in *pMem to val,
56622 ** manifest type REAL.
56624 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
56625 if( sqlite3IsNaN(val) ){
56626 sqlite3VdbeMemSetNull(pMem);
56627 }else{
56628 sqlite3VdbeMemRelease(pMem);
56629 pMem->r = val;
56630 pMem->flags = MEM_Real;
56631 pMem->type = SQLITE_FLOAT;
56634 #endif
56637 ** Delete any previous value and set the value of pMem to be an
56638 ** empty boolean index.
56640 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
56641 sqlite3 *db = pMem->db;
56642 assert( db!=0 );
56643 assert( (pMem->flags & MEM_RowSet)==0 );
56644 sqlite3VdbeMemRelease(pMem);
56645 pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
56646 if( db->mallocFailed ){
56647 pMem->flags = MEM_Null;
56648 }else{
56649 assert( pMem->zMalloc );
56650 pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
56651 sqlite3DbMallocSize(db, pMem->zMalloc));
56652 assert( pMem->u.pRowSet!=0 );
56653 pMem->flags = MEM_RowSet;
56658 ** Return true if the Mem object contains a TEXT or BLOB that is
56659 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
56661 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
56662 assert( p->db!=0 );
56663 if( p->flags & (MEM_Str|MEM_Blob) ){
56664 int n = p->n;
56665 if( p->flags & MEM_Zero ){
56666 n += p->u.nZero;
56668 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
56670 return 0;
56673 #ifdef SQLITE_DEBUG
56675 ** This routine prepares a memory cell for modication by breaking
56676 ** its link to a shallow copy and by marking any current shallow
56677 ** copies of this cell as invalid.
56679 ** This is used for testing and debugging only - to make sure shallow
56680 ** copies are not misused.
56682 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
56683 int i;
56684 Mem *pX;
56685 for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
56686 if( pX->pScopyFrom==pMem ){
56687 pX->flags |= MEM_Invalid;
56688 pX->pScopyFrom = 0;
56691 pMem->pScopyFrom = 0;
56693 #endif /* SQLITE_DEBUG */
56696 ** Size of struct Mem not including the Mem.zMalloc member.
56698 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
56701 ** Make an shallow copy of pFrom into pTo. Prior contents of
56702 ** pTo are freed. The pFrom->z field is not duplicated. If
56703 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
56704 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
56706 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
56707 assert( (pFrom->flags & MEM_RowSet)==0 );
56708 sqlite3VdbeMemReleaseExternal(pTo);
56709 memcpy(pTo, pFrom, MEMCELLSIZE);
56710 pTo->xDel = 0;
56711 if( (pFrom->flags&MEM_Static)==0 ){
56712 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
56713 assert( srcType==MEM_Ephem || srcType==MEM_Static );
56714 pTo->flags |= srcType;
56719 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
56720 ** freed before the copy is made.
56722 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
56723 int rc = SQLITE_OK;
56725 assert( (pFrom->flags & MEM_RowSet)==0 );
56726 sqlite3VdbeMemReleaseExternal(pTo);
56727 memcpy(pTo, pFrom, MEMCELLSIZE);
56728 pTo->flags &= ~MEM_Dyn;
56730 if( pTo->flags&(MEM_Str|MEM_Blob) ){
56731 if( 0==(pFrom->flags&MEM_Static) ){
56732 pTo->flags |= MEM_Ephem;
56733 rc = sqlite3VdbeMemMakeWriteable(pTo);
56737 return rc;
56741 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
56742 ** freed. If pFrom contains ephemeral data, a copy is made.
56744 ** pFrom contains an SQL NULL when this routine returns.
56746 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
56747 assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
56748 assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
56749 assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
56751 sqlite3VdbeMemRelease(pTo);
56752 memcpy(pTo, pFrom, sizeof(Mem));
56753 pFrom->flags = MEM_Null;
56754 pFrom->xDel = 0;
56755 pFrom->zMalloc = 0;
56759 ** Change the value of a Mem to be a string or a BLOB.
56761 ** The memory management strategy depends on the value of the xDel
56762 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
56763 ** string is copied into a (possibly existing) buffer managed by the
56764 ** Mem structure. Otherwise, any existing buffer is freed and the
56765 ** pointer copied.
56767 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
56768 ** size limit) then no memory allocation occurs. If the string can be
56769 ** stored without allocating memory, then it is. If a memory allocation
56770 ** is required to store the string, then value of pMem is unchanged. In
56771 ** either case, SQLITE_TOOBIG is returned.
56773 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
56774 Mem *pMem, /* Memory cell to set to string value */
56775 const char *z, /* String pointer */
56776 int n, /* Bytes in string, or negative */
56777 u8 enc, /* Encoding of z. 0 for BLOBs */
56778 void (*xDel)(void*) /* Destructor function */
56780 int nByte = n; /* New value for pMem->n */
56781 int iLimit; /* Maximum allowed string or blob size */
56782 u16 flags = 0; /* New value for pMem->flags */
56784 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56785 assert( (pMem->flags & MEM_RowSet)==0 );
56787 /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
56788 if( !z ){
56789 sqlite3VdbeMemSetNull(pMem);
56790 return SQLITE_OK;
56793 if( pMem->db ){
56794 iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
56795 }else{
56796 iLimit = SQLITE_MAX_LENGTH;
56798 flags = (enc==0?MEM_Blob:MEM_Str);
56799 if( nByte<0 ){
56800 assert( enc!=0 );
56801 if( enc==SQLITE_UTF8 ){
56802 for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
56803 }else{
56804 for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
56806 flags |= MEM_Term;
56809 /* The following block sets the new values of Mem.z and Mem.xDel. It
56810 ** also sets a flag in local variable "flags" to indicate the memory
56811 ** management (one of MEM_Dyn or MEM_Static).
56813 if( xDel==SQLITE_TRANSIENT ){
56814 int nAlloc = nByte;
56815 if( flags&MEM_Term ){
56816 nAlloc += (enc==SQLITE_UTF8?1:2);
56818 if( nByte>iLimit ){
56819 return SQLITE_TOOBIG;
56821 if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
56822 return SQLITE_NOMEM;
56824 memcpy(pMem->z, z, nAlloc);
56825 }else if( xDel==SQLITE_DYNAMIC ){
56826 sqlite3VdbeMemRelease(pMem);
56827 pMem->zMalloc = pMem->z = (char *)z;
56828 pMem->xDel = 0;
56829 }else{
56830 sqlite3VdbeMemRelease(pMem);
56831 pMem->z = (char *)z;
56832 pMem->xDel = xDel;
56833 flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
56836 pMem->n = nByte;
56837 pMem->flags = flags;
56838 pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
56839 pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
56841 #ifndef SQLITE_OMIT_UTF16
56842 if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
56843 return SQLITE_NOMEM;
56845 #endif
56847 if( nByte>iLimit ){
56848 return SQLITE_TOOBIG;
56851 return SQLITE_OK;
56855 ** Compare the values contained by the two memory cells, returning
56856 ** negative, zero or positive if pMem1 is less than, equal to, or greater
56857 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
56858 ** and reals) sorted numerically, followed by text ordered by the collating
56859 ** sequence pColl and finally blob's ordered by memcmp().
56861 ** Two NULL values are considered equal by this function.
56863 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
56864 int rc;
56865 int f1, f2;
56866 int combined_flags;
56868 f1 = pMem1->flags;
56869 f2 = pMem2->flags;
56870 combined_flags = f1|f2;
56871 assert( (combined_flags & MEM_RowSet)==0 );
56873 /* If one value is NULL, it is less than the other. If both values
56874 ** are NULL, return 0.
56876 if( combined_flags&MEM_Null ){
56877 return (f2&MEM_Null) - (f1&MEM_Null);
56880 /* If one value is a number and the other is not, the number is less.
56881 ** If both are numbers, compare as reals if one is a real, or as integers
56882 ** if both values are integers.
56884 if( combined_flags&(MEM_Int|MEM_Real) ){
56885 if( !(f1&(MEM_Int|MEM_Real)) ){
56886 return 1;
56888 if( !(f2&(MEM_Int|MEM_Real)) ){
56889 return -1;
56891 if( (f1 & f2 & MEM_Int)==0 ){
56892 double r1, r2;
56893 if( (f1&MEM_Real)==0 ){
56894 r1 = (double)pMem1->u.i;
56895 }else{
56896 r1 = pMem1->r;
56898 if( (f2&MEM_Real)==0 ){
56899 r2 = (double)pMem2->u.i;
56900 }else{
56901 r2 = pMem2->r;
56903 if( r1<r2 ) return -1;
56904 if( r1>r2 ) return 1;
56905 return 0;
56906 }else{
56907 assert( f1&MEM_Int );
56908 assert( f2&MEM_Int );
56909 if( pMem1->u.i < pMem2->u.i ) return -1;
56910 if( pMem1->u.i > pMem2->u.i ) return 1;
56911 return 0;
56915 /* If one value is a string and the other is a blob, the string is less.
56916 ** If both are strings, compare using the collating functions.
56918 if( combined_flags&MEM_Str ){
56919 if( (f1 & MEM_Str)==0 ){
56920 return 1;
56922 if( (f2 & MEM_Str)==0 ){
56923 return -1;
56926 assert( pMem1->enc==pMem2->enc );
56927 assert( pMem1->enc==SQLITE_UTF8 ||
56928 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
56930 /* The collation sequence must be defined at this point, even if
56931 ** the user deletes the collation sequence after the vdbe program is
56932 ** compiled (this was not always the case).
56934 assert( !pColl || pColl->xCmp );
56936 if( pColl ){
56937 if( pMem1->enc==pColl->enc ){
56938 /* The strings are already in the correct encoding. Call the
56939 ** comparison function directly */
56940 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
56941 }else{
56942 const void *v1, *v2;
56943 int n1, n2;
56944 Mem c1;
56945 Mem c2;
56946 memset(&c1, 0, sizeof(c1));
56947 memset(&c2, 0, sizeof(c2));
56948 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
56949 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
56950 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
56951 n1 = v1==0 ? 0 : c1.n;
56952 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
56953 n2 = v2==0 ? 0 : c2.n;
56954 rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
56955 sqlite3VdbeMemRelease(&c1);
56956 sqlite3VdbeMemRelease(&c2);
56957 return rc;
56960 /* If a NULL pointer was passed as the collate function, fall through
56961 ** to the blob case and use memcmp(). */
56964 /* Both values must be blobs. Compare using memcmp(). */
56965 rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
56966 if( rc==0 ){
56967 rc = pMem1->n - pMem2->n;
56969 return rc;
56973 ** Move data out of a btree key or data field and into a Mem structure.
56974 ** The data or key is taken from the entry that pCur is currently pointing
56975 ** to. offset and amt determine what portion of the data or key to retrieve.
56976 ** key is true to get the key or false to get data. The result is written
56977 ** into the pMem element.
56979 ** The pMem structure is assumed to be uninitialized. Any prior content
56980 ** is overwritten without being freed.
56982 ** If this routine fails for any reason (malloc returns NULL or unable
56983 ** to read from the disk) then the pMem is left in an inconsistent state.
56985 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
56986 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
56987 int offset, /* Offset from the start of data to return bytes from. */
56988 int amt, /* Number of bytes to return. */
56989 int key, /* If true, retrieve from the btree key, not data. */
56990 Mem *pMem /* OUT: Return data in this Mem structure. */
56992 char *zData; /* Data from the btree layer */
56993 int available = 0; /* Number of bytes available on the local btree page */
56994 int rc = SQLITE_OK; /* Return code */
56996 assert( sqlite3BtreeCursorIsValid(pCur) );
56998 /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
56999 ** that both the BtShared and database handle mutexes are held. */
57000 assert( (pMem->flags & MEM_RowSet)==0 );
57001 if( key ){
57002 zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
57003 }else{
57004 zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
57006 assert( zData!=0 );
57008 if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
57009 sqlite3VdbeMemRelease(pMem);
57010 pMem->z = &zData[offset];
57011 pMem->flags = MEM_Blob|MEM_Ephem;
57012 }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
57013 pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
57014 pMem->enc = 0;
57015 pMem->type = SQLITE_BLOB;
57016 if( key ){
57017 rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
57018 }else{
57019 rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
57021 pMem->z[amt] = 0;
57022 pMem->z[amt+1] = 0;
57023 if( rc!=SQLITE_OK ){
57024 sqlite3VdbeMemRelease(pMem);
57027 pMem->n = amt;
57029 return rc;
57032 /* This function is only available internally, it is not part of the
57033 ** external API. It works in a similar way to sqlite3_value_text(),
57034 ** except the data returned is in the encoding specified by the second
57035 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
57036 ** SQLITE_UTF8.
57038 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
57039 ** If that is the case, then the result must be aligned on an even byte
57040 ** boundary.
57042 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
57043 if( !pVal ) return 0;
57045 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
57046 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
57047 assert( (pVal->flags & MEM_RowSet)==0 );
57049 if( pVal->flags&MEM_Null ){
57050 return 0;
57052 assert( (MEM_Blob>>3) == MEM_Str );
57053 pVal->flags |= (pVal->flags & MEM_Blob)>>3;
57054 expandBlob(pVal);
57055 if( pVal->flags&MEM_Str ){
57056 sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
57057 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
57058 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
57059 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
57060 return 0;
57063 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
57064 }else{
57065 assert( (pVal->flags&MEM_Blob)==0 );
57066 sqlite3VdbeMemStringify(pVal, enc);
57067 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
57069 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
57070 || pVal->db->mallocFailed );
57071 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
57072 return pVal->z;
57073 }else{
57074 return 0;
57079 ** Create a new sqlite3_value object.
57081 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
57082 Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
57083 if( p ){
57084 p->flags = MEM_Null;
57085 p->type = SQLITE_NULL;
57086 p->db = db;
57088 return p;
57092 ** Create a new sqlite3_value object, containing the value of pExpr.
57094 ** This only works for very simple expressions that consist of one constant
57095 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
57096 ** be converted directly into a value, then the value is allocated and
57097 ** a pointer written to *ppVal. The caller is responsible for deallocating
57098 ** the value by passing it to sqlite3ValueFree() later on. If the expression
57099 ** cannot be converted to a value, then *ppVal is set to NULL.
57101 SQLITE_PRIVATE int sqlite3ValueFromExpr(
57102 sqlite3 *db, /* The database connection */
57103 Expr *pExpr, /* The expression to evaluate */
57104 u8 enc, /* Encoding to use */
57105 u8 affinity, /* Affinity to use */
57106 sqlite3_value **ppVal /* Write the new value here */
57108 int op;
57109 char *zVal = 0;
57110 sqlite3_value *pVal = 0;
57111 int negInt = 1;
57112 const char *zNeg = "";
57114 if( !pExpr ){
57115 *ppVal = 0;
57116 return SQLITE_OK;
57118 op = pExpr->op;
57120 /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
57121 ** The ifdef here is to enable us to achieve 100% branch test coverage even
57122 ** when SQLITE_ENABLE_STAT2 is omitted.
57124 #ifdef SQLITE_ENABLE_STAT2
57125 if( op==TK_REGISTER ) op = pExpr->op2;
57126 #else
57127 if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
57128 #endif
57130 /* Handle negative integers in a single step. This is needed in the
57131 ** case when the value is -9223372036854775808.
57133 if( op==TK_UMINUS
57134 && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
57135 pExpr = pExpr->pLeft;
57136 op = pExpr->op;
57137 negInt = -1;
57138 zNeg = "-";
57141 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
57142 pVal = sqlite3ValueNew(db);
57143 if( pVal==0 ) goto no_mem;
57144 if( ExprHasProperty(pExpr, EP_IntValue) ){
57145 sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
57146 }else{
57147 zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
57148 if( zVal==0 ) goto no_mem;
57149 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
57150 if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
57152 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
57153 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
57154 }else{
57155 sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
57157 if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
57158 if( enc!=SQLITE_UTF8 ){
57159 sqlite3VdbeChangeEncoding(pVal, enc);
57161 }else if( op==TK_UMINUS ) {
57162 /* This branch happens for multiple negative signs. Ex: -(-5) */
57163 if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
57164 sqlite3VdbeMemNumerify(pVal);
57165 if( pVal->u.i==SMALLEST_INT64 ){
57166 pVal->flags &= MEM_Int;
57167 pVal->flags |= MEM_Real;
57168 pVal->r = (double)LARGEST_INT64;
57169 }else{
57170 pVal->u.i = -pVal->u.i;
57172 pVal->r = -pVal->r;
57173 sqlite3ValueApplyAffinity(pVal, affinity, enc);
57175 }else if( op==TK_NULL ){
57176 pVal = sqlite3ValueNew(db);
57177 if( pVal==0 ) goto no_mem;
57179 #ifndef SQLITE_OMIT_BLOB_LITERAL
57180 else if( op==TK_BLOB ){
57181 int nVal;
57182 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
57183 assert( pExpr->u.zToken[1]=='\'' );
57184 pVal = sqlite3ValueNew(db);
57185 if( !pVal ) goto no_mem;
57186 zVal = &pExpr->u.zToken[2];
57187 nVal = sqlite3Strlen30(zVal)-1;
57188 assert( zVal[nVal]=='\'' );
57189 sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
57190 0, SQLITE_DYNAMIC);
57192 #endif
57194 if( pVal ){
57195 sqlite3VdbeMemStoreType(pVal);
57197 *ppVal = pVal;
57198 return SQLITE_OK;
57200 no_mem:
57201 db->mallocFailed = 1;
57202 sqlite3DbFree(db, zVal);
57203 sqlite3ValueFree(pVal);
57204 *ppVal = 0;
57205 return SQLITE_NOMEM;
57209 ** Change the string value of an sqlite3_value object
57211 SQLITE_PRIVATE void sqlite3ValueSetStr(
57212 sqlite3_value *v, /* Value to be set */
57213 int n, /* Length of string z */
57214 const void *z, /* Text of the new string */
57215 u8 enc, /* Encoding to use */
57216 void (*xDel)(void*) /* Destructor for the string */
57218 if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
57222 ** Free an sqlite3_value object
57224 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
57225 if( !v ) return;
57226 sqlite3VdbeMemRelease((Mem *)v);
57227 sqlite3DbFree(((Mem*)v)->db, v);
57231 ** Return the number of bytes in the sqlite3_value object assuming
57232 ** that it uses the encoding "enc"
57234 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
57235 Mem *p = (Mem*)pVal;
57236 if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
57237 if( p->flags & MEM_Zero ){
57238 return p->n + p->u.nZero;
57239 }else{
57240 return p->n;
57243 return 0;
57246 /************** End of vdbemem.c *********************************************/
57247 /************** Begin file vdbeaux.c *****************************************/
57249 ** 2003 September 6
57251 ** The author disclaims copyright to this source code. In place of
57252 ** a legal notice, here is a blessing:
57254 ** May you do good and not evil.
57255 ** May you find forgiveness for yourself and forgive others.
57256 ** May you share freely, never taking more than you give.
57258 *************************************************************************
57259 ** This file contains code used for creating, destroying, and populating
57260 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
57261 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
57262 ** But that file was getting too big so this subroutines were split out.
57268 ** When debugging the code generator in a symbolic debugger, one can
57269 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
57270 ** as they are added to the instruction stream.
57272 #ifdef SQLITE_DEBUG
57273 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
57274 #endif
57278 ** Create a new virtual database engine.
57280 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
57281 Vdbe *p;
57282 p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
57283 if( p==0 ) return 0;
57284 p->db = db;
57285 if( db->pVdbe ){
57286 db->pVdbe->pPrev = p;
57288 p->pNext = db->pVdbe;
57289 p->pPrev = 0;
57290 db->pVdbe = p;
57291 p->magic = VDBE_MAGIC_INIT;
57292 return p;
57296 ** Remember the SQL string for a prepared statement.
57298 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
57299 assert( isPrepareV2==1 || isPrepareV2==0 );
57300 if( p==0 ) return;
57301 #ifdef SQLITE_OMIT_TRACE
57302 if( !isPrepareV2 ) return;
57303 #endif
57304 assert( p->zSql==0 );
57305 p->zSql = sqlite3DbStrNDup(p->db, z, n);
57306 p->isPrepareV2 = (u8)isPrepareV2;
57310 ** Return the SQL associated with a prepared statement
57312 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
57313 Vdbe *p = (Vdbe *)pStmt;
57314 return (p && p->isPrepareV2) ? p->zSql : 0;
57318 ** Swap all content between two VDBE structures.
57320 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
57321 Vdbe tmp, *pTmp;
57322 char *zTmp;
57323 tmp = *pA;
57324 *pA = *pB;
57325 *pB = tmp;
57326 pTmp = pA->pNext;
57327 pA->pNext = pB->pNext;
57328 pB->pNext = pTmp;
57329 pTmp = pA->pPrev;
57330 pA->pPrev = pB->pPrev;
57331 pB->pPrev = pTmp;
57332 zTmp = pA->zSql;
57333 pA->zSql = pB->zSql;
57334 pB->zSql = zTmp;
57335 pB->isPrepareV2 = pA->isPrepareV2;
57338 #ifdef SQLITE_DEBUG
57340 ** Turn tracing on or off
57342 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
57343 p->trace = trace;
57345 #endif
57348 ** Resize the Vdbe.aOp array so that it is at least one op larger than
57349 ** it was.
57351 ** If an out-of-memory error occurs while resizing the array, return
57352 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
57353 ** unchanged (this is so that any opcodes already allocated can be
57354 ** correctly deallocated along with the rest of the Vdbe).
57356 static int growOpArray(Vdbe *p){
57357 VdbeOp *pNew;
57358 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
57359 pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
57360 if( pNew ){
57361 p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
57362 p->aOp = pNew;
57364 return (pNew ? SQLITE_OK : SQLITE_NOMEM);
57368 ** Add a new instruction to the list of instructions current in the
57369 ** VDBE. Return the address of the new instruction.
57371 ** Parameters:
57373 ** p Pointer to the VDBE
57375 ** op The opcode for this instruction
57377 ** p1, p2, p3 Operands
57379 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
57380 ** the sqlite3VdbeChangeP4() function to change the value of the P4
57381 ** operand.
57383 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
57384 int i;
57385 VdbeOp *pOp;
57387 i = p->nOp;
57388 assert( p->magic==VDBE_MAGIC_INIT );
57389 assert( op>0 && op<0xff );
57390 if( p->nOpAlloc<=i ){
57391 if( growOpArray(p) ){
57392 return 1;
57395 p->nOp++;
57396 pOp = &p->aOp[i];
57397 pOp->opcode = (u8)op;
57398 pOp->p5 = 0;
57399 pOp->p1 = p1;
57400 pOp->p2 = p2;
57401 pOp->p3 = p3;
57402 pOp->p4.p = 0;
57403 pOp->p4type = P4_NOTUSED;
57404 p->expired = 0;
57405 if( op==OP_ParseSchema ){
57406 /* Any program that uses the OP_ParseSchema opcode needs to lock
57407 ** all btrees. */
57408 int j;
57409 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
57411 #ifdef SQLITE_DEBUG
57412 pOp->zComment = 0;
57413 if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
57414 #endif
57415 #ifdef VDBE_PROFILE
57416 pOp->cycles = 0;
57417 pOp->cnt = 0;
57418 #endif
57419 return i;
57421 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
57422 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
57424 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
57425 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
57427 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
57428 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
57433 ** Add an opcode that includes the p4 value as a pointer.
57435 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
57436 Vdbe *p, /* Add the opcode to this VM */
57437 int op, /* The new opcode */
57438 int p1, /* The P1 operand */
57439 int p2, /* The P2 operand */
57440 int p3, /* The P3 operand */
57441 const char *zP4, /* The P4 operand */
57442 int p4type /* P4 operand type */
57444 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57445 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
57446 return addr;
57450 ** Add an opcode that includes the p4 value as an integer.
57452 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
57453 Vdbe *p, /* Add the opcode to this VM */
57454 int op, /* The new opcode */
57455 int p1, /* The P1 operand */
57456 int p2, /* The P2 operand */
57457 int p3, /* The P3 operand */
57458 int p4 /* The P4 operand as an integer */
57460 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57461 sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
57462 return addr;
57466 ** Create a new symbolic label for an instruction that has yet to be
57467 ** coded. The symbolic label is really just a negative number. The
57468 ** label can be used as the P2 value of an operation. Later, when
57469 ** the label is resolved to a specific address, the VDBE will scan
57470 ** through its operation list and change all values of P2 which match
57471 ** the label into the resolved address.
57473 ** The VDBE knows that a P2 value is a label because labels are
57474 ** always negative and P2 values are suppose to be non-negative.
57475 ** Hence, a negative P2 value is a label that has yet to be resolved.
57477 ** Zero is returned if a malloc() fails.
57479 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
57480 int i;
57481 i = p->nLabel++;
57482 assert( p->magic==VDBE_MAGIC_INIT );
57483 if( i>=p->nLabelAlloc ){
57484 int n = p->nLabelAlloc*2 + 5;
57485 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
57486 n*sizeof(p->aLabel[0]));
57487 p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
57489 if( p->aLabel ){
57490 p->aLabel[i] = -1;
57492 return -1-i;
57496 ** Resolve label "x" to be the address of the next instruction to
57497 ** be inserted. The parameter "x" must have been obtained from
57498 ** a prior call to sqlite3VdbeMakeLabel().
57500 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
57501 int j = -1-x;
57502 assert( p->magic==VDBE_MAGIC_INIT );
57503 assert( j>=0 && j<p->nLabel );
57504 if( p->aLabel ){
57505 p->aLabel[j] = p->nOp;
57510 ** Mark the VDBE as one that can only be run one time.
57512 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
57513 p->runOnlyOnce = 1;
57516 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
57519 ** The following type and function are used to iterate through all opcodes
57520 ** in a Vdbe main program and each of the sub-programs (triggers) it may
57521 ** invoke directly or indirectly. It should be used as follows:
57523 ** Op *pOp;
57524 ** VdbeOpIter sIter;
57526 ** memset(&sIter, 0, sizeof(sIter));
57527 ** sIter.v = v; // v is of type Vdbe*
57528 ** while( (pOp = opIterNext(&sIter)) ){
57529 ** // Do something with pOp
57530 ** }
57531 ** sqlite3DbFree(v->db, sIter.apSub);
57534 typedef struct VdbeOpIter VdbeOpIter;
57535 struct VdbeOpIter {
57536 Vdbe *v; /* Vdbe to iterate through the opcodes of */
57537 SubProgram **apSub; /* Array of subprograms */
57538 int nSub; /* Number of entries in apSub */
57539 int iAddr; /* Address of next instruction to return */
57540 int iSub; /* 0 = main program, 1 = first sub-program etc. */
57542 static Op *opIterNext(VdbeOpIter *p){
57543 Vdbe *v = p->v;
57544 Op *pRet = 0;
57545 Op *aOp;
57546 int nOp;
57548 if( p->iSub<=p->nSub ){
57550 if( p->iSub==0 ){
57551 aOp = v->aOp;
57552 nOp = v->nOp;
57553 }else{
57554 aOp = p->apSub[p->iSub-1]->aOp;
57555 nOp = p->apSub[p->iSub-1]->nOp;
57557 assert( p->iAddr<nOp );
57559 pRet = &aOp[p->iAddr];
57560 p->iAddr++;
57561 if( p->iAddr==nOp ){
57562 p->iSub++;
57563 p->iAddr = 0;
57566 if( pRet->p4type==P4_SUBPROGRAM ){
57567 int nByte = (p->nSub+1)*sizeof(SubProgram*);
57568 int j;
57569 for(j=0; j<p->nSub; j++){
57570 if( p->apSub[j]==pRet->p4.pProgram ) break;
57572 if( j==p->nSub ){
57573 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
57574 if( !p->apSub ){
57575 pRet = 0;
57576 }else{
57577 p->apSub[p->nSub++] = pRet->p4.pProgram;
57583 return pRet;
57587 ** Check if the program stored in the VM associated with pParse may
57588 ** throw an ABORT exception (causing the statement, but not entire transaction
57589 ** to be rolled back). This condition is true if the main program or any
57590 ** sub-programs contains any of the following:
57592 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57593 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57594 ** * OP_Destroy
57595 ** * OP_VUpdate
57596 ** * OP_VRename
57597 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
57599 ** Then check that the value of Parse.mayAbort is true if an
57600 ** ABORT may be thrown, or false otherwise. Return true if it does
57601 ** match, or false otherwise. This function is intended to be used as
57602 ** part of an assert statement in the compiler. Similar to:
57604 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
57606 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
57607 int hasAbort = 0;
57608 Op *pOp;
57609 VdbeOpIter sIter;
57610 memset(&sIter, 0, sizeof(sIter));
57611 sIter.v = v;
57613 while( (pOp = opIterNext(&sIter))!=0 ){
57614 int opcode = pOp->opcode;
57615 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
57616 #ifndef SQLITE_OMIT_FOREIGN_KEY
57617 || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
57618 #endif
57619 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
57620 && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
57622 hasAbort = 1;
57623 break;
57626 sqlite3DbFree(v->db, sIter.apSub);
57628 /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
57629 ** If malloc failed, then the while() loop above may not have iterated
57630 ** through all opcodes and hasAbort may be set incorrectly. Return
57631 ** true for this case to prevent the assert() in the callers frame
57632 ** from failing. */
57633 return ( v->db->mallocFailed || hasAbort==mayAbort );
57635 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
57638 ** Loop through the program looking for P2 values that are negative
57639 ** on jump instructions. Each such value is a label. Resolve the
57640 ** label by setting the P2 value to its correct non-zero value.
57642 ** This routine is called once after all opcodes have been inserted.
57644 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
57645 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
57646 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
57648 ** The Op.opflags field is set on all opcodes.
57650 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
57651 int i;
57652 int nMaxArgs = *pMaxFuncArgs;
57653 Op *pOp;
57654 int *aLabel = p->aLabel;
57655 p->readOnly = 1;
57656 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
57657 u8 opcode = pOp->opcode;
57659 pOp->opflags = sqlite3OpcodeProperty[opcode];
57660 if( opcode==OP_Function || opcode==OP_AggStep ){
57661 if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
57662 }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
57663 p->readOnly = 0;
57664 #ifndef SQLITE_OMIT_VIRTUALTABLE
57665 }else if( opcode==OP_VUpdate ){
57666 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
57667 }else if( opcode==OP_VFilter ){
57668 int n;
57669 assert( p->nOp - i >= 3 );
57670 assert( pOp[-1].opcode==OP_Integer );
57671 n = pOp[-1].p1;
57672 if( n>nMaxArgs ) nMaxArgs = n;
57673 #endif
57676 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
57677 assert( -1-pOp->p2<p->nLabel );
57678 pOp->p2 = aLabel[-1-pOp->p2];
57681 sqlite3DbFree(p->db, p->aLabel);
57682 p->aLabel = 0;
57684 *pMaxFuncArgs = nMaxArgs;
57688 ** Return the address of the next instruction to be inserted.
57690 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
57691 assert( p->magic==VDBE_MAGIC_INIT );
57692 return p->nOp;
57696 ** This function returns a pointer to the array of opcodes associated with
57697 ** the Vdbe passed as the first argument. It is the callers responsibility
57698 ** to arrange for the returned array to be eventually freed using the
57699 ** vdbeFreeOpArray() function.
57701 ** Before returning, *pnOp is set to the number of entries in the returned
57702 ** array. Also, *pnMaxArg is set to the larger of its current value and
57703 ** the number of entries in the Vdbe.apArg[] array required to execute the
57704 ** returned program.
57706 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
57707 VdbeOp *aOp = p->aOp;
57708 assert( aOp && !p->db->mallocFailed );
57710 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
57711 assert( p->btreeMask==0 );
57713 resolveP2Values(p, pnMaxArg);
57714 *pnOp = p->nOp;
57715 p->aOp = 0;
57716 return aOp;
57720 ** Add a whole list of operations to the operation stack. Return the
57721 ** address of the first operation added.
57723 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
57724 int addr;
57725 assert( p->magic==VDBE_MAGIC_INIT );
57726 if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
57727 return 0;
57729 addr = p->nOp;
57730 if( ALWAYS(nOp>0) ){
57731 int i;
57732 VdbeOpList const *pIn = aOp;
57733 for(i=0; i<nOp; i++, pIn++){
57734 int p2 = pIn->p2;
57735 VdbeOp *pOut = &p->aOp[i+addr];
57736 pOut->opcode = pIn->opcode;
57737 pOut->p1 = pIn->p1;
57738 if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
57739 pOut->p2 = addr + ADDR(p2);
57740 }else{
57741 pOut->p2 = p2;
57743 pOut->p3 = pIn->p3;
57744 pOut->p4type = P4_NOTUSED;
57745 pOut->p4.p = 0;
57746 pOut->p5 = 0;
57747 #ifdef SQLITE_DEBUG
57748 pOut->zComment = 0;
57749 if( sqlite3VdbeAddopTrace ){
57750 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
57752 #endif
57754 p->nOp += nOp;
57756 return addr;
57760 ** Change the value of the P1 operand for a specific instruction.
57761 ** This routine is useful when a large program is loaded from a
57762 ** static array using sqlite3VdbeAddOpList but we want to make a
57763 ** few minor changes to the program.
57765 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
57766 assert( p!=0 );
57767 assert( addr>=0 );
57768 if( p->nOp>addr ){
57769 p->aOp[addr].p1 = val;
57774 ** Change the value of the P2 operand for a specific instruction.
57775 ** This routine is useful for setting a jump destination.
57777 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
57778 assert( p!=0 );
57779 assert( addr>=0 );
57780 if( p->nOp>addr ){
57781 p->aOp[addr].p2 = val;
57786 ** Change the value of the P3 operand for a specific instruction.
57788 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
57789 assert( p!=0 );
57790 assert( addr>=0 );
57791 if( p->nOp>addr ){
57792 p->aOp[addr].p3 = val;
57797 ** Change the value of the P5 operand for the most recently
57798 ** added operation.
57800 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
57801 assert( p!=0 );
57802 if( p->aOp ){
57803 assert( p->nOp>0 );
57804 p->aOp[p->nOp-1].p5 = val;
57809 ** Change the P2 operand of instruction addr so that it points to
57810 ** the address of the next instruction to be coded.
57812 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
57813 assert( addr>=0 );
57814 sqlite3VdbeChangeP2(p, addr, p->nOp);
57819 ** If the input FuncDef structure is ephemeral, then free it. If
57820 ** the FuncDef is not ephermal, then do nothing.
57822 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
57823 if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
57824 sqlite3DbFree(db, pDef);
57828 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
57831 ** Delete a P4 value if necessary.
57833 static void freeP4(sqlite3 *db, int p4type, void *p4){
57834 if( p4 ){
57835 assert( db );
57836 switch( p4type ){
57837 case P4_REAL:
57838 case P4_INT64:
57839 case P4_DYNAMIC:
57840 case P4_KEYINFO:
57841 case P4_INTARRAY:
57842 case P4_KEYINFO_HANDOFF: {
57843 sqlite3DbFree(db, p4);
57844 break;
57846 case P4_MPRINTF: {
57847 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
57848 break;
57850 case P4_VDBEFUNC: {
57851 VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
57852 freeEphemeralFunction(db, pVdbeFunc->pFunc);
57853 if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
57854 sqlite3DbFree(db, pVdbeFunc);
57855 break;
57857 case P4_FUNCDEF: {
57858 freeEphemeralFunction(db, (FuncDef*)p4);
57859 break;
57861 case P4_MEM: {
57862 if( db->pnBytesFreed==0 ){
57863 sqlite3ValueFree((sqlite3_value*)p4);
57864 }else{
57865 Mem *p = (Mem*)p4;
57866 sqlite3DbFree(db, p->zMalloc);
57867 sqlite3DbFree(db, p);
57869 break;
57871 case P4_VTAB : {
57872 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
57873 break;
57880 ** Free the space allocated for aOp and any p4 values allocated for the
57881 ** opcodes contained within. If aOp is not NULL it is assumed to contain
57882 ** nOp entries.
57884 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
57885 if( aOp ){
57886 Op *pOp;
57887 for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
57888 freeP4(db, pOp->p4type, pOp->p4.p);
57889 #ifdef SQLITE_DEBUG
57890 sqlite3DbFree(db, pOp->zComment);
57891 #endif
57894 sqlite3DbFree(db, aOp);
57898 ** Link the SubProgram object passed as the second argument into the linked
57899 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
57900 ** objects when the VM is no longer required.
57902 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
57903 p->pNext = pVdbe->pProgram;
57904 pVdbe->pProgram = p;
57908 ** Change N opcodes starting at addr to No-ops.
57910 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
57911 if( p->aOp ){
57912 VdbeOp *pOp = &p->aOp[addr];
57913 sqlite3 *db = p->db;
57914 while( N-- ){
57915 freeP4(db, pOp->p4type, pOp->p4.p);
57916 memset(pOp, 0, sizeof(pOp[0]));
57917 pOp->opcode = OP_Noop;
57918 pOp++;
57924 ** Change the value of the P4 operand for a specific instruction.
57925 ** This routine is useful when a large program is loaded from a
57926 ** static array using sqlite3VdbeAddOpList but we want to make a
57927 ** few minor changes to the program.
57929 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
57930 ** the string is made into memory obtained from sqlite3_malloc().
57931 ** A value of n==0 means copy bytes of zP4 up to and including the
57932 ** first null byte. If n>0 then copy n+1 bytes of zP4.
57934 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
57935 ** A copy is made of the KeyInfo structure into memory obtained from
57936 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
57937 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
57938 ** stored in memory that the caller has obtained from sqlite3_malloc. The
57939 ** caller should not free the allocation, it will be freed when the Vdbe is
57940 ** finalized.
57942 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
57943 ** to a string or structure that is guaranteed to exist for the lifetime of
57944 ** the Vdbe. In these cases we can just copy the pointer.
57946 ** If addr<0 then change P4 on the most recently inserted instruction.
57948 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
57949 Op *pOp;
57950 sqlite3 *db;
57951 assert( p!=0 );
57952 db = p->db;
57953 assert( p->magic==VDBE_MAGIC_INIT );
57954 if( p->aOp==0 || db->mallocFailed ){
57955 if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
57956 freeP4(db, n, (void*)*(char**)&zP4);
57958 return;
57960 assert( p->nOp>0 );
57961 assert( addr<p->nOp );
57962 if( addr<0 ){
57963 addr = p->nOp - 1;
57965 pOp = &p->aOp[addr];
57966 freeP4(db, pOp->p4type, pOp->p4.p);
57967 pOp->p4.p = 0;
57968 if( n==P4_INT32 ){
57969 /* Note: this cast is safe, because the origin data point was an int
57970 ** that was cast to a (const char *). */
57971 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
57972 pOp->p4type = P4_INT32;
57973 }else if( zP4==0 ){
57974 pOp->p4.p = 0;
57975 pOp->p4type = P4_NOTUSED;
57976 }else if( n==P4_KEYINFO ){
57977 KeyInfo *pKeyInfo;
57978 int nField, nByte;
57980 nField = ((KeyInfo*)zP4)->nField;
57981 nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
57982 pKeyInfo = sqlite3DbMallocRaw(0, nByte);
57983 pOp->p4.pKeyInfo = pKeyInfo;
57984 if( pKeyInfo ){
57985 u8 *aSortOrder;
57986 memcpy((char*)pKeyInfo, zP4, nByte - nField);
57987 aSortOrder = pKeyInfo->aSortOrder;
57988 if( aSortOrder ){
57989 pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
57990 memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
57992 pOp->p4type = P4_KEYINFO;
57993 }else{
57994 p->db->mallocFailed = 1;
57995 pOp->p4type = P4_NOTUSED;
57997 }else if( n==P4_KEYINFO_HANDOFF ){
57998 pOp->p4.p = (void*)zP4;
57999 pOp->p4type = P4_KEYINFO;
58000 }else if( n==P4_VTAB ){
58001 pOp->p4.p = (void*)zP4;
58002 pOp->p4type = P4_VTAB;
58003 sqlite3VtabLock((VTable *)zP4);
58004 assert( ((VTable *)zP4)->db==p->db );
58005 }else if( n<0 ){
58006 pOp->p4.p = (void*)zP4;
58007 pOp->p4type = (signed char)n;
58008 }else{
58009 if( n==0 ) n = sqlite3Strlen30(zP4);
58010 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
58011 pOp->p4type = P4_DYNAMIC;
58015 #ifndef NDEBUG
58017 ** Change the comment on the the most recently coded instruction. Or
58018 ** insert a No-op and add the comment to that new instruction. This
58019 ** makes the code easier to read during debugging. None of this happens
58020 ** in a production build.
58022 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
58023 va_list ap;
58024 if( !p ) return;
58025 assert( p->nOp>0 || p->aOp==0 );
58026 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
58027 if( p->nOp ){
58028 char **pz = &p->aOp[p->nOp-1].zComment;
58029 va_start(ap, zFormat);
58030 sqlite3DbFree(p->db, *pz);
58031 *pz = sqlite3VMPrintf(p->db, zFormat, ap);
58032 va_end(ap);
58035 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
58036 va_list ap;
58037 if( !p ) return;
58038 sqlite3VdbeAddOp0(p, OP_Noop);
58039 assert( p->nOp>0 || p->aOp==0 );
58040 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
58041 if( p->nOp ){
58042 char **pz = &p->aOp[p->nOp-1].zComment;
58043 va_start(ap, zFormat);
58044 sqlite3DbFree(p->db, *pz);
58045 *pz = sqlite3VMPrintf(p->db, zFormat, ap);
58046 va_end(ap);
58049 #endif /* NDEBUG */
58052 ** Return the opcode for a given address. If the address is -1, then
58053 ** return the most recently inserted opcode.
58055 ** If a memory allocation error has occurred prior to the calling of this
58056 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
58057 ** is readable but not writable, though it is cast to a writable value.
58058 ** The return of a dummy opcode allows the call to continue functioning
58059 ** after a OOM fault without having to check to see if the return from
58060 ** this routine is a valid pointer. But because the dummy.opcode is 0,
58061 ** dummy will never be written to. This is verified by code inspection and
58062 ** by running with Valgrind.
58064 ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
58065 ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
58066 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
58067 ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
58068 ** having to double-check to make sure that the result is non-negative. But
58069 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
58070 ** check the value of p->nOp-1 before continuing.
58072 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
58073 /* C89 specifies that the constant "dummy" will be initialized to all
58074 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
58075 static const VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
58076 assert( p->magic==VDBE_MAGIC_INIT );
58077 if( addr<0 ){
58078 #ifdef SQLITE_OMIT_TRACE
58079 if( p->nOp==0 ) return (VdbeOp*)&dummy;
58080 #endif
58081 addr = p->nOp - 1;
58083 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
58084 if( p->db->mallocFailed ){
58085 return (VdbeOp*)&dummy;
58086 }else{
58087 return &p->aOp[addr];
58091 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
58092 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
58094 ** Compute a string that describes the P4 parameter for an opcode.
58095 ** Use zTemp for any required temporary buffer space.
58097 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
58098 char *zP4 = zTemp;
58099 assert( nTemp>=20 );
58100 switch( pOp->p4type ){
58101 case P4_KEYINFO_STATIC:
58102 case P4_KEYINFO: {
58103 int i, j;
58104 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
58105 sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
58106 i = sqlite3Strlen30(zTemp);
58107 for(j=0; j<pKeyInfo->nField; j++){
58108 CollSeq *pColl = pKeyInfo->aColl[j];
58109 if( pColl ){
58110 int n = sqlite3Strlen30(pColl->zName);
58111 if( i+n>nTemp-6 ){
58112 memcpy(&zTemp[i],",...",4);
58113 break;
58115 zTemp[i++] = ',';
58116 if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
58117 zTemp[i++] = '-';
58119 memcpy(&zTemp[i], pColl->zName,n+1);
58120 i += n;
58121 }else if( i+4<nTemp-6 ){
58122 memcpy(&zTemp[i],",nil",4);
58123 i += 4;
58126 zTemp[i++] = ')';
58127 zTemp[i] = 0;
58128 assert( i<nTemp );
58129 break;
58131 case P4_COLLSEQ: {
58132 CollSeq *pColl = pOp->p4.pColl;
58133 sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
58134 break;
58136 case P4_FUNCDEF: {
58137 FuncDef *pDef = pOp->p4.pFunc;
58138 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
58139 break;
58141 case P4_INT64: {
58142 sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
58143 break;
58145 case P4_INT32: {
58146 sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
58147 break;
58149 case P4_REAL: {
58150 sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
58151 break;
58153 case P4_MEM: {
58154 Mem *pMem = pOp->p4.pMem;
58155 assert( (pMem->flags & MEM_Null)==0 );
58156 if( pMem->flags & MEM_Str ){
58157 zP4 = pMem->z;
58158 }else if( pMem->flags & MEM_Int ){
58159 sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
58160 }else if( pMem->flags & MEM_Real ){
58161 sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
58162 }else{
58163 assert( pMem->flags & MEM_Blob );
58164 zP4 = "(blob)";
58166 break;
58168 #ifndef SQLITE_OMIT_VIRTUALTABLE
58169 case P4_VTAB: {
58170 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
58171 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
58172 break;
58174 #endif
58175 case P4_INTARRAY: {
58176 sqlite3_snprintf(nTemp, zTemp, "intarray");
58177 break;
58179 case P4_SUBPROGRAM: {
58180 sqlite3_snprintf(nTemp, zTemp, "program");
58181 break;
58183 default: {
58184 zP4 = pOp->p4.z;
58185 if( zP4==0 ){
58186 zP4 = zTemp;
58187 zTemp[0] = 0;
58191 assert( zP4!=0 );
58192 return zP4;
58194 #endif
58197 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
58199 ** The prepared statements need to know in advance the complete set of
58200 ** attached databases that they will be using. A mask of these databases
58201 ** is maintained in p->btreeMask and is used for locking and other purposes.
58203 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
58204 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
58205 assert( i<(int)sizeof(p->btreeMask)*8 );
58206 p->btreeMask |= ((yDbMask)1)<<i;
58207 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
58208 p->lockMask |= ((yDbMask)1)<<i;
58212 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
58214 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
58215 ** this routine obtains the mutex associated with each BtShared structure
58216 ** that may be accessed by the VM passed as an argument. In doing so it also
58217 ** sets the BtShared.db member of each of the BtShared structures, ensuring
58218 ** that the correct busy-handler callback is invoked if required.
58220 ** If SQLite is not threadsafe but does support shared-cache mode, then
58221 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
58222 ** of all of BtShared structures accessible via the database handle
58223 ** associated with the VM.
58225 ** If SQLite is not threadsafe and does not support shared-cache mode, this
58226 ** function is a no-op.
58228 ** The p->btreeMask field is a bitmask of all btrees that the prepared
58229 ** statement p will ever use. Let N be the number of bits in p->btreeMask
58230 ** corresponding to btrees that use shared cache. Then the runtime of
58231 ** this routine is N*N. But as N is rarely more than 1, this should not
58232 ** be a problem.
58234 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
58235 int i;
58236 yDbMask mask;
58237 sqlite3 *db;
58238 Db *aDb;
58239 int nDb;
58240 if( p->lockMask==0 ) return; /* The common case */
58241 db = p->db;
58242 aDb = db->aDb;
58243 nDb = db->nDb;
58244 for(i=0, mask=1; i<nDb; i++, mask += mask){
58245 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
58246 sqlite3BtreeEnter(aDb[i].pBt);
58250 #endif
58252 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
58254 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
58256 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
58257 int i;
58258 yDbMask mask;
58259 sqlite3 *db;
58260 Db *aDb;
58261 int nDb;
58262 if( p->lockMask==0 ) return; /* The common case */
58263 db = p->db;
58264 aDb = db->aDb;
58265 nDb = db->nDb;
58266 for(i=0, mask=1; i<nDb; i++, mask += mask){
58267 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
58268 sqlite3BtreeLeave(aDb[i].pBt);
58272 #endif
58274 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
58276 ** Print a single opcode. This routine is used for debugging only.
58278 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
58279 char *zP4;
58280 char zPtr[50];
58281 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
58282 if( pOut==0 ) pOut = stdout;
58283 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
58284 fprintf(pOut, zFormat1, pc,
58285 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
58286 #ifdef SQLITE_DEBUG
58287 pOp->zComment ? pOp->zComment : ""
58288 #else
58290 #endif
58292 fflush(pOut);
58294 #endif
58297 ** Release an array of N Mem elements
58299 static void releaseMemArray(Mem *p, int N){
58300 if( p && N ){
58301 Mem *pEnd;
58302 sqlite3 *db = p->db;
58303 u8 malloc_failed = db->mallocFailed;
58304 if( db->pnBytesFreed ){
58305 for(pEnd=&p[N]; p<pEnd; p++){
58306 sqlite3DbFree(db, p->zMalloc);
58308 return;
58310 for(pEnd=&p[N]; p<pEnd; p++){
58311 assert( (&p[1])==pEnd || p[0].db==p[1].db );
58313 /* This block is really an inlined version of sqlite3VdbeMemRelease()
58314 ** that takes advantage of the fact that the memory cell value is
58315 ** being set to NULL after releasing any dynamic resources.
58317 ** The justification for duplicating code is that according to
58318 ** callgrind, this causes a certain test case to hit the CPU 4.7
58319 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
58320 ** sqlite3MemRelease() were called from here. With -O2, this jumps
58321 ** to 6.6 percent. The test case is inserting 1000 rows into a table
58322 ** with no indexes using a single prepared INSERT statement, bind()
58323 ** and reset(). Inserts are grouped into a transaction.
58325 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
58326 sqlite3VdbeMemRelease(p);
58327 }else if( p->zMalloc ){
58328 sqlite3DbFree(db, p->zMalloc);
58329 p->zMalloc = 0;
58332 p->flags = MEM_Null;
58334 db->mallocFailed = malloc_failed;
58339 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
58340 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
58342 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
58343 int i;
58344 Mem *aMem = VdbeFrameMem(p);
58345 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
58346 for(i=0; i<p->nChildCsr; i++){
58347 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
58349 releaseMemArray(aMem, p->nChildMem);
58350 sqlite3DbFree(p->v->db, p);
58353 #ifndef SQLITE_OMIT_EXPLAIN
58355 ** Give a listing of the program in the virtual machine.
58357 ** The interface is the same as sqlite3VdbeExec(). But instead of
58358 ** running the code, it invokes the callback once for each instruction.
58359 ** This feature is used to implement "EXPLAIN".
58361 ** When p->explain==1, each instruction is listed. When
58362 ** p->explain==2, only OP_Explain instructions are listed and these
58363 ** are shown in a different format. p->explain==2 is used to implement
58364 ** EXPLAIN QUERY PLAN.
58366 ** When p->explain==1, first the main program is listed, then each of
58367 ** the trigger subprograms are listed one by one.
58369 SQLITE_PRIVATE int sqlite3VdbeList(
58370 Vdbe *p /* The VDBE */
58372 int nRow; /* Stop when row count reaches this */
58373 int nSub = 0; /* Number of sub-vdbes seen so far */
58374 SubProgram **apSub = 0; /* Array of sub-vdbes */
58375 Mem *pSub = 0; /* Memory cell hold array of subprogs */
58376 sqlite3 *db = p->db; /* The database connection */
58377 int i; /* Loop counter */
58378 int rc = SQLITE_OK; /* Return code */
58379 Mem *pMem = p->pResultSet = &p->aMem[1]; /* First Mem of result set */
58381 assert( p->explain );
58382 assert( p->magic==VDBE_MAGIC_RUN );
58383 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
58385 /* Even though this opcode does not use dynamic strings for
58386 ** the result, result columns may become dynamic if the user calls
58387 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
58389 releaseMemArray(pMem, 8);
58391 if( p->rc==SQLITE_NOMEM ){
58392 /* This happens if a malloc() inside a call to sqlite3_column_text() or
58393 ** sqlite3_column_text16() failed. */
58394 db->mallocFailed = 1;
58395 return SQLITE_ERROR;
58398 /* When the number of output rows reaches nRow, that means the
58399 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
58400 ** nRow is the sum of the number of rows in the main program, plus
58401 ** the sum of the number of rows in all trigger subprograms encountered
58402 ** so far. The nRow value will increase as new trigger subprograms are
58403 ** encountered, but p->pc will eventually catch up to nRow.
58405 nRow = p->nOp;
58406 if( p->explain==1 ){
58407 /* The first 8 memory cells are used for the result set. So we will
58408 ** commandeer the 9th cell to use as storage for an array of pointers
58409 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
58410 ** cells. */
58411 assert( p->nMem>9 );
58412 pSub = &p->aMem[9];
58413 if( pSub->flags&MEM_Blob ){
58414 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
58415 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
58416 nSub = pSub->n/sizeof(Vdbe*);
58417 apSub = (SubProgram **)pSub->z;
58419 for(i=0; i<nSub; i++){
58420 nRow += apSub[i]->nOp;
58425 i = p->pc++;
58426 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
58427 if( i>=nRow ){
58428 p->rc = SQLITE_OK;
58429 rc = SQLITE_DONE;
58430 }else if( db->u1.isInterrupted ){
58431 p->rc = SQLITE_INTERRUPT;
58432 rc = SQLITE_ERROR;
58433 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
58434 }else{
58435 char *z;
58436 Op *pOp;
58437 if( i<p->nOp ){
58438 /* The output line number is small enough that we are still in the
58439 ** main program. */
58440 pOp = &p->aOp[i];
58441 }else{
58442 /* We are currently listing subprograms. Figure out which one and
58443 ** pick up the appropriate opcode. */
58444 int j;
58445 i -= p->nOp;
58446 for(j=0; i>=apSub[j]->nOp; j++){
58447 i -= apSub[j]->nOp;
58449 pOp = &apSub[j]->aOp[i];
58451 if( p->explain==1 ){
58452 pMem->flags = MEM_Int;
58453 pMem->type = SQLITE_INTEGER;
58454 pMem->u.i = i; /* Program counter */
58455 pMem++;
58457 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
58458 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
58459 assert( pMem->z!=0 );
58460 pMem->n = sqlite3Strlen30(pMem->z);
58461 pMem->type = SQLITE_TEXT;
58462 pMem->enc = SQLITE_UTF8;
58463 pMem++;
58465 /* When an OP_Program opcode is encounter (the only opcode that has
58466 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
58467 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
58468 ** has not already been seen.
58470 if( pOp->p4type==P4_SUBPROGRAM ){
58471 int nByte = (nSub+1)*sizeof(SubProgram*);
58472 int j;
58473 for(j=0; j<nSub; j++){
58474 if( apSub[j]==pOp->p4.pProgram ) break;
58476 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
58477 apSub = (SubProgram **)pSub->z;
58478 apSub[nSub++] = pOp->p4.pProgram;
58479 pSub->flags |= MEM_Blob;
58480 pSub->n = nSub*sizeof(SubProgram*);
58485 pMem->flags = MEM_Int;
58486 pMem->u.i = pOp->p1; /* P1 */
58487 pMem->type = SQLITE_INTEGER;
58488 pMem++;
58490 pMem->flags = MEM_Int;
58491 pMem->u.i = pOp->p2; /* P2 */
58492 pMem->type = SQLITE_INTEGER;
58493 pMem++;
58495 pMem->flags = MEM_Int;
58496 pMem->u.i = pOp->p3; /* P3 */
58497 pMem->type = SQLITE_INTEGER;
58498 pMem++;
58500 if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
58501 assert( p->db->mallocFailed );
58502 return SQLITE_ERROR;
58504 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58505 z = displayP4(pOp, pMem->z, 32);
58506 if( z!=pMem->z ){
58507 sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
58508 }else{
58509 assert( pMem->z!=0 );
58510 pMem->n = sqlite3Strlen30(pMem->z);
58511 pMem->enc = SQLITE_UTF8;
58513 pMem->type = SQLITE_TEXT;
58514 pMem++;
58516 if( p->explain==1 ){
58517 if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
58518 assert( p->db->mallocFailed );
58519 return SQLITE_ERROR;
58521 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58522 pMem->n = 2;
58523 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
58524 pMem->type = SQLITE_TEXT;
58525 pMem->enc = SQLITE_UTF8;
58526 pMem++;
58528 #ifdef SQLITE_DEBUG
58529 if( pOp->zComment ){
58530 pMem->flags = MEM_Str|MEM_Term;
58531 pMem->z = pOp->zComment;
58532 pMem->n = sqlite3Strlen30(pMem->z);
58533 pMem->enc = SQLITE_UTF8;
58534 pMem->type = SQLITE_TEXT;
58535 }else
58536 #endif
58538 pMem->flags = MEM_Null; /* Comment */
58539 pMem->type = SQLITE_NULL;
58543 p->nResColumn = 8 - 4*(p->explain-1);
58544 p->rc = SQLITE_OK;
58545 rc = SQLITE_ROW;
58547 return rc;
58549 #endif /* SQLITE_OMIT_EXPLAIN */
58551 #ifdef SQLITE_DEBUG
58553 ** Print the SQL that was used to generate a VDBE program.
58555 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
58556 int nOp = p->nOp;
58557 VdbeOp *pOp;
58558 if( nOp<1 ) return;
58559 pOp = &p->aOp[0];
58560 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58561 const char *z = pOp->p4.z;
58562 while( sqlite3Isspace(*z) ) z++;
58563 printf("SQL: [%s]\n", z);
58566 #endif
58568 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
58570 ** Print an IOTRACE message showing SQL content.
58572 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
58573 int nOp = p->nOp;
58574 VdbeOp *pOp;
58575 if( sqlite3IoTrace==0 ) return;
58576 if( nOp<1 ) return;
58577 pOp = &p->aOp[0];
58578 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58579 int i, j;
58580 char z[1000];
58581 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
58582 for(i=0; sqlite3Isspace(z[i]); i++){}
58583 for(j=0; z[i]; i++){
58584 if( sqlite3Isspace(z[i]) ){
58585 if( z[i-1]!=' ' ){
58586 z[j++] = ' ';
58588 }else{
58589 z[j++] = z[i];
58592 z[j] = 0;
58593 sqlite3IoTrace("SQL %s\n", z);
58596 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
58599 ** Allocate space from a fixed size buffer and return a pointer to
58600 ** that space. If insufficient space is available, return NULL.
58602 ** The pBuf parameter is the initial value of a pointer which will
58603 ** receive the new memory. pBuf is normally NULL. If pBuf is not
58604 ** NULL, it means that memory space has already been allocated and that
58605 ** this routine should not allocate any new memory. When pBuf is not
58606 ** NULL simply return pBuf. Only allocate new memory space when pBuf
58607 ** is NULL.
58609 ** nByte is the number of bytes of space needed.
58611 ** *ppFrom points to available space and pEnd points to the end of the
58612 ** available space. When space is allocated, *ppFrom is advanced past
58613 ** the end of the allocated space.
58615 ** *pnByte is a counter of the number of bytes of space that have failed
58616 ** to allocate. If there is insufficient space in *ppFrom to satisfy the
58617 ** request, then increment *pnByte by the amount of the request.
58619 static void *allocSpace(
58620 void *pBuf, /* Where return pointer will be stored */
58621 int nByte, /* Number of bytes to allocate */
58622 u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
58623 u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
58624 int *pnByte /* If allocation cannot be made, increment *pnByte */
58626 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
58627 if( pBuf ) return pBuf;
58628 nByte = ROUND8(nByte);
58629 if( &(*ppFrom)[nByte] <= pEnd ){
58630 pBuf = (void*)*ppFrom;
58631 *ppFrom += nByte;
58632 }else{
58633 *pnByte += nByte;
58635 return pBuf;
58639 ** Prepare a virtual machine for execution. This involves things such
58640 ** as allocating stack space and initializing the program counter.
58641 ** After the VDBE has be prepped, it can be executed by one or more
58642 ** calls to sqlite3VdbeExec().
58644 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
58645 ** VDBE_MAGIC_RUN.
58647 ** This function may be called more than once on a single virtual machine.
58648 ** The first call is made while compiling the SQL statement. Subsequent
58649 ** calls are made as part of the process of resetting a statement to be
58650 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
58651 ** and isExplain parameters are only passed correct values the first time
58652 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
58653 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
58655 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
58656 Vdbe *p, /* The VDBE */
58657 int nVar, /* Number of '?' see in the SQL statement */
58658 int nMem, /* Number of memory cells to allocate */
58659 int nCursor, /* Number of cursors to allocate */
58660 int nArg, /* Maximum number of args in SubPrograms */
58661 int isExplain, /* True if the EXPLAIN keywords is present */
58662 int usesStmtJournal /* True to set Vdbe.usesStmtJournal */
58664 int n;
58665 sqlite3 *db = p->db;
58667 assert( p!=0 );
58668 assert( p->magic==VDBE_MAGIC_INIT );
58670 /* There should be at least one opcode.
58672 assert( p->nOp>0 );
58674 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
58675 p->magic = VDBE_MAGIC_RUN;
58677 /* For each cursor required, also allocate a memory cell. Memory
58678 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
58679 ** the vdbe program. Instead they are used to allocate space for
58680 ** VdbeCursor/BtCursor structures. The blob of memory associated with
58681 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
58682 ** stores the blob of memory associated with cursor 1, etc.
58684 ** See also: allocateCursor().
58686 nMem += nCursor;
58688 /* Allocate space for memory registers, SQL variables, VDBE cursors and
58689 ** an array to marshal SQL function arguments in. This is only done the
58690 ** first time this function is called for a given VDBE, not when it is
58691 ** being called from sqlite3_reset() to reset the virtual machine.
58693 if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
58694 u8 *zCsr = (u8 *)&p->aOp[p->nOp]; /* Memory avaliable for alloation */
58695 u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc]; /* First byte past available mem */
58696 int nByte; /* How much extra memory needed */
58698 resolveP2Values(p, &nArg);
58699 p->usesStmtJournal = (u8)usesStmtJournal;
58700 if( isExplain && nMem<10 ){
58701 nMem = 10;
58703 memset(zCsr, 0, zEnd-zCsr);
58704 zCsr += (zCsr - (u8*)0)&7;
58705 assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
58707 /* Memory for registers, parameters, cursor, etc, is allocated in two
58708 ** passes. On the first pass, we try to reuse unused space at the
58709 ** end of the opcode array. If we are unable to satisfy all memory
58710 ** requirements by reusing the opcode array tail, then the second
58711 ** pass will fill in the rest using a fresh allocation.
58713 ** This two-pass approach that reuses as much memory as possible from
58714 ** the leftover space at the end of the opcode array can significantly
58715 ** reduce the amount of memory held by a prepared statement.
58717 do {
58718 nByte = 0;
58719 p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
58720 p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
58721 p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
58722 p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
58723 p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
58724 &zCsr, zEnd, &nByte);
58725 if( nByte ){
58726 p->pFree = sqlite3DbMallocZero(db, nByte);
58728 zCsr = p->pFree;
58729 zEnd = &zCsr[nByte];
58730 }while( nByte && !db->mallocFailed );
58732 p->nCursor = (u16)nCursor;
58733 if( p->aVar ){
58734 p->nVar = (ynVar)nVar;
58735 for(n=0; n<nVar; n++){
58736 p->aVar[n].flags = MEM_Null;
58737 p->aVar[n].db = db;
58740 if( p->aMem ){
58741 p->aMem--; /* aMem[] goes from 1..nMem */
58742 p->nMem = nMem; /* not from 0..nMem-1 */
58743 for(n=1; n<=nMem; n++){
58744 p->aMem[n].flags = MEM_Null;
58745 p->aMem[n].db = db;
58749 #ifdef SQLITE_DEBUG
58750 for(n=1; n<p->nMem; n++){
58751 assert( p->aMem[n].db==db );
58753 #endif
58755 p->pc = -1;
58756 p->rc = SQLITE_OK;
58757 p->errorAction = OE_Abort;
58758 p->explain |= isExplain;
58759 p->magic = VDBE_MAGIC_RUN;
58760 p->nChange = 0;
58761 p->cacheCtr = 1;
58762 p->minWriteFileFormat = 255;
58763 p->iStatement = 0;
58764 p->nFkConstraint = 0;
58765 #ifdef VDBE_PROFILE
58767 int i;
58768 for(i=0; i<p->nOp; i++){
58769 p->aOp[i].cnt = 0;
58770 p->aOp[i].cycles = 0;
58773 #endif
58777 ** Close a VDBE cursor and release all the resources that cursor
58778 ** happens to hold.
58780 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
58781 if( pCx==0 ){
58782 return;
58784 if( pCx->pBt ){
58785 sqlite3BtreeClose(pCx->pBt);
58786 /* The pCx->pCursor will be close automatically, if it exists, by
58787 ** the call above. */
58788 }else if( pCx->pCursor ){
58789 sqlite3BtreeCloseCursor(pCx->pCursor);
58791 #ifndef SQLITE_OMIT_VIRTUALTABLE
58792 if( pCx->pVtabCursor ){
58793 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
58794 const sqlite3_module *pModule = pCx->pModule;
58795 p->inVtabMethod = 1;
58796 pModule->xClose(pVtabCursor);
58797 p->inVtabMethod = 0;
58799 #endif
58803 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
58804 ** is used, for example, when a trigger sub-program is halted to restore
58805 ** control to the main program.
58807 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
58808 Vdbe *v = pFrame->v;
58809 v->aOp = pFrame->aOp;
58810 v->nOp = pFrame->nOp;
58811 v->aMem = pFrame->aMem;
58812 v->nMem = pFrame->nMem;
58813 v->apCsr = pFrame->apCsr;
58814 v->nCursor = pFrame->nCursor;
58815 v->db->lastRowid = pFrame->lastRowid;
58816 v->nChange = pFrame->nChange;
58817 return pFrame->pc;
58821 ** Close all cursors.
58823 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
58824 ** cell array. This is necessary as the memory cell array may contain
58825 ** pointers to VdbeFrame objects, which may in turn contain pointers to
58826 ** open cursors.
58828 static void closeAllCursors(Vdbe *p){
58829 if( p->pFrame ){
58830 VdbeFrame *pFrame;
58831 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
58832 sqlite3VdbeFrameRestore(pFrame);
58834 p->pFrame = 0;
58835 p->nFrame = 0;
58837 if( p->apCsr ){
58838 int i;
58839 for(i=0; i<p->nCursor; i++){
58840 VdbeCursor *pC = p->apCsr[i];
58841 if( pC ){
58842 sqlite3VdbeFreeCursor(p, pC);
58843 p->apCsr[i] = 0;
58847 if( p->aMem ){
58848 releaseMemArray(&p->aMem[1], p->nMem);
58850 while( p->pDelFrame ){
58851 VdbeFrame *pDel = p->pDelFrame;
58852 p->pDelFrame = pDel->pParent;
58853 sqlite3VdbeFrameDelete(pDel);
58858 ** Clean up the VM after execution.
58860 ** This routine will automatically close any cursors, lists, and/or
58861 ** sorters that were left open. It also deletes the values of
58862 ** variables in the aVar[] array.
58864 static void Cleanup(Vdbe *p){
58865 sqlite3 *db = p->db;
58867 #ifdef SQLITE_DEBUG
58868 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
58869 ** Vdbe.aMem[] arrays have already been cleaned up. */
58870 int i;
58871 for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
58872 for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
58873 #endif
58875 sqlite3DbFree(db, p->zErrMsg);
58876 p->zErrMsg = 0;
58877 p->pResultSet = 0;
58881 ** Set the number of result columns that will be returned by this SQL
58882 ** statement. This is now set at compile time, rather than during
58883 ** execution of the vdbe program so that sqlite3_column_count() can
58884 ** be called on an SQL statement before sqlite3_step().
58886 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
58887 Mem *pColName;
58888 int n;
58889 sqlite3 *db = p->db;
58891 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
58892 sqlite3DbFree(db, p->aColName);
58893 n = nResColumn*COLNAME_N;
58894 p->nResColumn = (u16)nResColumn;
58895 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
58896 if( p->aColName==0 ) return;
58897 while( n-- > 0 ){
58898 pColName->flags = MEM_Null;
58899 pColName->db = p->db;
58900 pColName++;
58905 ** Set the name of the idx'th column to be returned by the SQL statement.
58906 ** zName must be a pointer to a nul terminated string.
58908 ** This call must be made after a call to sqlite3VdbeSetNumCols().
58910 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
58911 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
58912 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
58914 SQLITE_PRIVATE int sqlite3VdbeSetColName(
58915 Vdbe *p, /* Vdbe being configured */
58916 int idx, /* Index of column zName applies to */
58917 int var, /* One of the COLNAME_* constants */
58918 const char *zName, /* Pointer to buffer containing name */
58919 void (*xDel)(void*) /* Memory management strategy for zName */
58921 int rc;
58922 Mem *pColName;
58923 assert( idx<p->nResColumn );
58924 assert( var<COLNAME_N );
58925 if( p->db->mallocFailed ){
58926 assert( !zName || xDel!=SQLITE_DYNAMIC );
58927 return SQLITE_NOMEM;
58929 assert( p->aColName!=0 );
58930 pColName = &(p->aColName[idx+var*p->nResColumn]);
58931 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
58932 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
58933 return rc;
58937 ** A read or write transaction may or may not be active on database handle
58938 ** db. If a transaction is active, commit it. If there is a
58939 ** write-transaction spanning more than one database file, this routine
58940 ** takes care of the master journal trickery.
58942 static int vdbeCommit(sqlite3 *db, Vdbe *p){
58943 int i;
58944 int nTrans = 0; /* Number of databases with an active write-transaction */
58945 int rc = SQLITE_OK;
58946 int needXcommit = 0;
58948 #ifdef SQLITE_OMIT_VIRTUALTABLE
58949 /* With this option, sqlite3VtabSync() is defined to be simply
58950 ** SQLITE_OK so p is not used.
58952 UNUSED_PARAMETER(p);
58953 #endif
58955 /* Before doing anything else, call the xSync() callback for any
58956 ** virtual module tables written in this transaction. This has to
58957 ** be done before determining whether a master journal file is
58958 ** required, as an xSync() callback may add an attached database
58959 ** to the transaction.
58961 rc = sqlite3VtabSync(db, &p->zErrMsg);
58963 /* This loop determines (a) if the commit hook should be invoked and
58964 ** (b) how many database files have open write transactions, not
58965 ** including the temp database. (b) is important because if more than
58966 ** one database file has an open write transaction, a master journal
58967 ** file is required for an atomic commit.
58969 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
58970 Btree *pBt = db->aDb[i].pBt;
58971 if( sqlite3BtreeIsInTrans(pBt) ){
58972 needXcommit = 1;
58973 if( i!=1 ) nTrans++;
58974 rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
58977 if( rc!=SQLITE_OK ){
58978 return rc;
58981 /* If there are any write-transactions at all, invoke the commit hook */
58982 if( needXcommit && db->xCommitCallback ){
58983 rc = db->xCommitCallback(db->pCommitArg);
58984 if( rc ){
58985 return SQLITE_CONSTRAINT;
58989 /* The simple case - no more than one database file (not counting the
58990 ** TEMP database) has a transaction active. There is no need for the
58991 ** master-journal.
58993 ** If the return value of sqlite3BtreeGetFilename() is a zero length
58994 ** string, it means the main database is :memory: or a temp file. In
58995 ** that case we do not support atomic multi-file commits, so use the
58996 ** simple case then too.
58998 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
58999 || nTrans<=1
59001 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59002 Btree *pBt = db->aDb[i].pBt;
59003 if( pBt ){
59004 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
59008 /* Do the commit only if all databases successfully complete phase 1.
59009 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
59010 ** IO error while deleting or truncating a journal file. It is unlikely,
59011 ** but could happen. In this case abandon processing and return the error.
59013 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59014 Btree *pBt = db->aDb[i].pBt;
59015 if( pBt ){
59016 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
59019 if( rc==SQLITE_OK ){
59020 sqlite3VtabCommit(db);
59024 /* The complex case - There is a multi-file write-transaction active.
59025 ** This requires a master journal file to ensure the transaction is
59026 ** committed atomicly.
59028 #ifndef SQLITE_OMIT_DISKIO
59029 else{
59030 sqlite3_vfs *pVfs = db->pVfs;
59031 int needSync = 0;
59032 char *zMaster = 0; /* File-name for the master journal */
59033 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
59034 sqlite3_file *pMaster = 0;
59035 i64 offset = 0;
59036 int res;
59038 /* Select a master journal file name */
59039 do {
59040 u32 iRandom;
59041 sqlite3DbFree(db, zMaster);
59042 sqlite3_randomness(sizeof(iRandom), &iRandom);
59043 zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
59044 if( !zMaster ){
59045 return SQLITE_NOMEM;
59047 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
59048 }while( rc==SQLITE_OK && res );
59049 if( rc==SQLITE_OK ){
59050 /* Open the master journal. */
59051 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
59052 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
59053 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
59056 if( rc!=SQLITE_OK ){
59057 sqlite3DbFree(db, zMaster);
59058 return rc;
59061 /* Write the name of each database file in the transaction into the new
59062 ** master journal file. If an error occurs at this point close
59063 ** and delete the master journal file. All the individual journal files
59064 ** still have 'null' as the master journal pointer, so they will roll
59065 ** back independently if a failure occurs.
59067 for(i=0; i<db->nDb; i++){
59068 Btree *pBt = db->aDb[i].pBt;
59069 if( sqlite3BtreeIsInTrans(pBt) ){
59070 char const *zFile = sqlite3BtreeGetJournalname(pBt);
59071 if( zFile==0 ){
59072 continue; /* Ignore TEMP and :memory: databases */
59074 assert( zFile[0]!=0 );
59075 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
59076 needSync = 1;
59078 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
59079 offset += sqlite3Strlen30(zFile)+1;
59080 if( rc!=SQLITE_OK ){
59081 sqlite3OsCloseFree(pMaster);
59082 sqlite3OsDelete(pVfs, zMaster, 0);
59083 sqlite3DbFree(db, zMaster);
59084 return rc;
59089 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
59090 ** flag is set this is not required.
59092 if( needSync
59093 && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
59094 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
59096 sqlite3OsCloseFree(pMaster);
59097 sqlite3OsDelete(pVfs, zMaster, 0);
59098 sqlite3DbFree(db, zMaster);
59099 return rc;
59102 /* Sync all the db files involved in the transaction. The same call
59103 ** sets the master journal pointer in each individual journal. If
59104 ** an error occurs here, do not delete the master journal file.
59106 ** If the error occurs during the first call to
59107 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
59108 ** master journal file will be orphaned. But we cannot delete it,
59109 ** in case the master journal file name was written into the journal
59110 ** file before the failure occurred.
59112 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59113 Btree *pBt = db->aDb[i].pBt;
59114 if( pBt ){
59115 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
59118 sqlite3OsCloseFree(pMaster);
59119 assert( rc!=SQLITE_BUSY );
59120 if( rc!=SQLITE_OK ){
59121 sqlite3DbFree(db, zMaster);
59122 return rc;
59125 /* Delete the master journal file. This commits the transaction. After
59126 ** doing this the directory is synced again before any individual
59127 ** transaction files are deleted.
59129 rc = sqlite3OsDelete(pVfs, zMaster, 1);
59130 sqlite3DbFree(db, zMaster);
59131 zMaster = 0;
59132 if( rc ){
59133 return rc;
59136 /* All files and directories have already been synced, so the following
59137 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
59138 ** deleting or truncating journals. If something goes wrong while
59139 ** this is happening we don't really care. The integrity of the
59140 ** transaction is already guaranteed, but some stray 'cold' journals
59141 ** may be lying around. Returning an error code won't help matters.
59143 disable_simulated_io_errors();
59144 sqlite3BeginBenignMalloc();
59145 for(i=0; i<db->nDb; i++){
59146 Btree *pBt = db->aDb[i].pBt;
59147 if( pBt ){
59148 sqlite3BtreeCommitPhaseTwo(pBt, 1);
59151 sqlite3EndBenignMalloc();
59152 enable_simulated_io_errors();
59154 sqlite3VtabCommit(db);
59156 #endif
59158 return rc;
59162 ** This routine checks that the sqlite3.activeVdbeCnt count variable
59163 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
59164 ** currently active. An assertion fails if the two counts do not match.
59165 ** This is an internal self-check only - it is not an essential processing
59166 ** step.
59168 ** This is a no-op if NDEBUG is defined.
59170 #ifndef NDEBUG
59171 static void checkActiveVdbeCnt(sqlite3 *db){
59172 Vdbe *p;
59173 int cnt = 0;
59174 int nWrite = 0;
59175 p = db->pVdbe;
59176 while( p ){
59177 if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
59178 cnt++;
59179 if( p->readOnly==0 ) nWrite++;
59181 p = p->pNext;
59183 assert( cnt==db->activeVdbeCnt );
59184 assert( nWrite==db->writeVdbeCnt );
59186 #else
59187 #define checkActiveVdbeCnt(x)
59188 #endif
59191 ** For every Btree that in database connection db which
59192 ** has been modified, "trip" or invalidate each cursor in
59193 ** that Btree might have been modified so that the cursor
59194 ** can never be used again. This happens when a rollback
59195 *** occurs. We have to trip all the other cursors, even
59196 ** cursor from other VMs in different database connections,
59197 ** so that none of them try to use the data at which they
59198 ** were pointing and which now may have been changed due
59199 ** to the rollback.
59201 ** Remember that a rollback can delete tables complete and
59202 ** reorder rootpages. So it is not sufficient just to save
59203 ** the state of the cursor. We have to invalidate the cursor
59204 ** so that it is never used again.
59206 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
59207 int i;
59208 for(i=0; i<db->nDb; i++){
59209 Btree *p = db->aDb[i].pBt;
59210 if( p && sqlite3BtreeIsInTrans(p) ){
59211 sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
59217 ** If the Vdbe passed as the first argument opened a statement-transaction,
59218 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
59219 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
59220 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
59221 ** statement transaction is commtted.
59223 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
59224 ** Otherwise SQLITE_OK.
59226 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
59227 sqlite3 *const db = p->db;
59228 int rc = SQLITE_OK;
59230 /* If p->iStatement is greater than zero, then this Vdbe opened a
59231 ** statement transaction that should be closed here. The only exception
59232 ** is that an IO error may have occured, causing an emergency rollback.
59233 ** In this case (db->nStatement==0), and there is nothing to do.
59235 if( db->nStatement && p->iStatement ){
59236 int i;
59237 const int iSavepoint = p->iStatement-1;
59239 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
59240 assert( db->nStatement>0 );
59241 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
59243 for(i=0; i<db->nDb; i++){
59244 int rc2 = SQLITE_OK;
59245 Btree *pBt = db->aDb[i].pBt;
59246 if( pBt ){
59247 if( eOp==SAVEPOINT_ROLLBACK ){
59248 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
59250 if( rc2==SQLITE_OK ){
59251 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
59253 if( rc==SQLITE_OK ){
59254 rc = rc2;
59258 db->nStatement--;
59259 p->iStatement = 0;
59261 /* If the statement transaction is being rolled back, also restore the
59262 ** database handles deferred constraint counter to the value it had when
59263 ** the statement transaction was opened. */
59264 if( eOp==SAVEPOINT_ROLLBACK ){
59265 db->nDeferredCons = p->nStmtDefCons;
59268 return rc;
59272 ** This function is called when a transaction opened by the database
59273 ** handle associated with the VM passed as an argument is about to be
59274 ** committed. If there are outstanding deferred foreign key constraint
59275 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
59277 ** If there are outstanding FK violations and this function returns
59278 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
59279 ** an error message to it. Then return SQLITE_ERROR.
59281 #ifndef SQLITE_OMIT_FOREIGN_KEY
59282 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
59283 sqlite3 *db = p->db;
59284 if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
59285 p->rc = SQLITE_CONSTRAINT;
59286 p->errorAction = OE_Abort;
59287 sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
59288 return SQLITE_ERROR;
59290 return SQLITE_OK;
59292 #endif
59295 ** This routine is called the when a VDBE tries to halt. If the VDBE
59296 ** has made changes and is in autocommit mode, then commit those
59297 ** changes. If a rollback is needed, then do the rollback.
59299 ** This routine is the only way to move the state of a VM from
59300 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
59301 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
59303 ** Return an error code. If the commit could not complete because of
59304 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
59305 ** means the close did not happen and needs to be repeated.
59307 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
59308 int rc; /* Used to store transient return codes */
59309 sqlite3 *db = p->db;
59311 /* This function contains the logic that determines if a statement or
59312 ** transaction will be committed or rolled back as a result of the
59313 ** execution of this virtual machine.
59315 ** If any of the following errors occur:
59317 ** SQLITE_NOMEM
59318 ** SQLITE_IOERR
59319 ** SQLITE_FULL
59320 ** SQLITE_INTERRUPT
59322 ** Then the internal cache might have been left in an inconsistent
59323 ** state. We need to rollback the statement transaction, if there is
59324 ** one, or the complete transaction if there is no statement transaction.
59327 if( p->db->mallocFailed ){
59328 p->rc = SQLITE_NOMEM;
59330 closeAllCursors(p);
59331 if( p->magic!=VDBE_MAGIC_RUN ){
59332 return SQLITE_OK;
59334 checkActiveVdbeCnt(db);
59336 /* No commit or rollback needed if the program never started */
59337 if( p->pc>=0 ){
59338 int mrc; /* Primary error code from p->rc */
59339 int eStatementOp = 0;
59340 int isSpecialError; /* Set to true if a 'special' error */
59342 /* Lock all btrees used by the statement */
59343 sqlite3VdbeEnter(p);
59345 /* Check for one of the special errors */
59346 mrc = p->rc & 0xff;
59347 assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
59348 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
59349 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
59350 if( isSpecialError ){
59351 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
59352 ** no rollback is necessary. Otherwise, at least a savepoint
59353 ** transaction must be rolled back to restore the database to a
59354 ** consistent state.
59356 ** Even if the statement is read-only, it is important to perform
59357 ** a statement or transaction rollback operation. If the error
59358 ** occured while writing to the journal, sub-journal or database
59359 ** file as part of an effort to free up cache space (see function
59360 ** pagerStress() in pager.c), the rollback is required to restore
59361 ** the pager to a consistent state.
59363 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
59364 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
59365 eStatementOp = SAVEPOINT_ROLLBACK;
59366 }else{
59367 /* We are forced to roll back the active transaction. Before doing
59368 ** so, abort any other statements this handle currently has active.
59370 invalidateCursorsOnModifiedBtrees(db);
59371 sqlite3RollbackAll(db);
59372 sqlite3CloseSavepoints(db);
59373 db->autoCommit = 1;
59378 /* Check for immediate foreign key violations. */
59379 if( p->rc==SQLITE_OK ){
59380 sqlite3VdbeCheckFk(p, 0);
59383 /* If the auto-commit flag is set and this is the only active writer
59384 ** VM, then we do either a commit or rollback of the current transaction.
59386 ** Note: This block also runs if one of the special errors handled
59387 ** above has occurred.
59389 if( !sqlite3VtabInSync(db)
59390 && db->autoCommit
59391 && db->writeVdbeCnt==(p->readOnly==0)
59393 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
59394 rc = sqlite3VdbeCheckFk(p, 1);
59395 if( rc!=SQLITE_OK ){
59396 if( NEVER(p->readOnly) ){
59397 sqlite3VdbeLeave(p);
59398 return SQLITE_ERROR;
59400 rc = SQLITE_CONSTRAINT;
59401 }else{
59402 /* The auto-commit flag is true, the vdbe program was successful
59403 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
59404 ** key constraints to hold up the transaction. This means a commit
59405 ** is required. */
59406 rc = vdbeCommit(db, p);
59408 if( rc==SQLITE_BUSY && p->readOnly ){
59409 sqlite3VdbeLeave(p);
59410 return SQLITE_BUSY;
59411 }else if( rc!=SQLITE_OK ){
59412 p->rc = rc;
59413 sqlite3RollbackAll(db);
59414 }else{
59415 db->nDeferredCons = 0;
59416 sqlite3CommitInternalChanges(db);
59418 }else{
59419 sqlite3RollbackAll(db);
59421 db->nStatement = 0;
59422 }else if( eStatementOp==0 ){
59423 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
59424 eStatementOp = SAVEPOINT_RELEASE;
59425 }else if( p->errorAction==OE_Abort ){
59426 eStatementOp = SAVEPOINT_ROLLBACK;
59427 }else{
59428 invalidateCursorsOnModifiedBtrees(db);
59429 sqlite3RollbackAll(db);
59430 sqlite3CloseSavepoints(db);
59431 db->autoCommit = 1;
59435 /* If eStatementOp is non-zero, then a statement transaction needs to
59436 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
59437 ** do so. If this operation returns an error, and the current statement
59438 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
59439 ** current statement error code.
59441 ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
59442 ** is SAVEPOINT_ROLLBACK. But if p->rc==SQLITE_OK then eStatementOp
59443 ** must be SAVEPOINT_RELEASE. Hence the NEVER(p->rc==SQLITE_OK) in
59444 ** the following code.
59446 if( eStatementOp ){
59447 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
59448 if( rc ){
59449 assert( eStatementOp==SAVEPOINT_ROLLBACK );
59450 if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
59451 p->rc = rc;
59452 sqlite3DbFree(db, p->zErrMsg);
59453 p->zErrMsg = 0;
59455 invalidateCursorsOnModifiedBtrees(db);
59456 sqlite3RollbackAll(db);
59457 sqlite3CloseSavepoints(db);
59458 db->autoCommit = 1;
59462 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
59463 ** has been rolled back, update the database connection change-counter.
59465 if( p->changeCntOn ){
59466 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
59467 sqlite3VdbeSetChanges(db, p->nChange);
59468 }else{
59469 sqlite3VdbeSetChanges(db, 0);
59471 p->nChange = 0;
59474 /* Rollback or commit any schema changes that occurred. */
59475 if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
59476 sqlite3ResetInternalSchema(db, -1);
59477 db->flags = (db->flags | SQLITE_InternChanges);
59480 /* Release the locks */
59481 sqlite3VdbeLeave(p);
59484 /* We have successfully halted and closed the VM. Record this fact. */
59485 if( p->pc>=0 ){
59486 db->activeVdbeCnt--;
59487 if( !p->readOnly ){
59488 db->writeVdbeCnt--;
59490 assert( db->activeVdbeCnt>=db->writeVdbeCnt );
59492 p->magic = VDBE_MAGIC_HALT;
59493 checkActiveVdbeCnt(db);
59494 if( p->db->mallocFailed ){
59495 p->rc = SQLITE_NOMEM;
59498 /* If the auto-commit flag is set to true, then any locks that were held
59499 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
59500 ** to invoke any required unlock-notify callbacks.
59502 if( db->autoCommit ){
59503 sqlite3ConnectionUnlocked(db);
59506 assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
59507 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
59512 ** Each VDBE holds the result of the most recent sqlite3_step() call
59513 ** in p->rc. This routine sets that result back to SQLITE_OK.
59515 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
59516 p->rc = SQLITE_OK;
59520 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
59521 ** Write any error messages into *pzErrMsg. Return the result code.
59523 ** After this routine is run, the VDBE should be ready to be executed
59524 ** again.
59526 ** To look at it another way, this routine resets the state of the
59527 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
59528 ** VDBE_MAGIC_INIT.
59530 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
59531 sqlite3 *db;
59532 db = p->db;
59534 /* If the VM did not run to completion or if it encountered an
59535 ** error, then it might not have been halted properly. So halt
59536 ** it now.
59538 sqlite3VdbeHalt(p);
59540 /* If the VDBE has be run even partially, then transfer the error code
59541 ** and error message from the VDBE into the main database structure. But
59542 ** if the VDBE has just been set to run but has not actually executed any
59543 ** instructions yet, leave the main database error information unchanged.
59545 if( p->pc>=0 ){
59546 if( p->zErrMsg ){
59547 sqlite3BeginBenignMalloc();
59548 sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
59549 sqlite3EndBenignMalloc();
59550 db->errCode = p->rc;
59551 sqlite3DbFree(db, p->zErrMsg);
59552 p->zErrMsg = 0;
59553 }else if( p->rc ){
59554 sqlite3Error(db, p->rc, 0);
59555 }else{
59556 sqlite3Error(db, SQLITE_OK, 0);
59558 if( p->runOnlyOnce ) p->expired = 1;
59559 }else if( p->rc && p->expired ){
59560 /* The expired flag was set on the VDBE before the first call
59561 ** to sqlite3_step(). For consistency (since sqlite3_step() was
59562 ** called), set the database error in this case as well.
59564 sqlite3Error(db, p->rc, 0);
59565 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
59566 sqlite3DbFree(db, p->zErrMsg);
59567 p->zErrMsg = 0;
59570 /* Reclaim all memory used by the VDBE
59572 Cleanup(p);
59574 /* Save profiling information from this VDBE run.
59576 #ifdef VDBE_PROFILE
59578 FILE *out = fopen("vdbe_profile.out", "a");
59579 if( out ){
59580 int i;
59581 fprintf(out, "---- ");
59582 for(i=0; i<p->nOp; i++){
59583 fprintf(out, "%02x", p->aOp[i].opcode);
59585 fprintf(out, "\n");
59586 for(i=0; i<p->nOp; i++){
59587 fprintf(out, "%6d %10lld %8lld ",
59588 p->aOp[i].cnt,
59589 p->aOp[i].cycles,
59590 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
59592 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
59594 fclose(out);
59597 #endif
59598 p->magic = VDBE_MAGIC_INIT;
59599 return p->rc & db->errMask;
59603 ** Clean up and delete a VDBE after execution. Return an integer which is
59604 ** the result code. Write any error message text into *pzErrMsg.
59606 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
59607 int rc = SQLITE_OK;
59608 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
59609 rc = sqlite3VdbeReset(p);
59610 assert( (rc & p->db->errMask)==rc );
59612 sqlite3VdbeDelete(p);
59613 return rc;
59617 ** Call the destructor for each auxdata entry in pVdbeFunc for which
59618 ** the corresponding bit in mask is clear. Auxdata entries beyond 31
59619 ** are always destroyed. To destroy all auxdata entries, call this
59620 ** routine with mask==0.
59622 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
59623 int i;
59624 for(i=0; i<pVdbeFunc->nAux; i++){
59625 struct AuxData *pAux = &pVdbeFunc->apAux[i];
59626 if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
59627 if( pAux->xDelete ){
59628 pAux->xDelete(pAux->pAux);
59630 pAux->pAux = 0;
59636 ** Free all memory associated with the Vdbe passed as the second argument.
59637 ** The difference between this function and sqlite3VdbeDelete() is that
59638 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
59639 ** the database connection.
59641 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
59642 SubProgram *pSub, *pNext;
59643 assert( p->db==0 || p->db==db );
59644 releaseMemArray(p->aVar, p->nVar);
59645 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
59646 for(pSub=p->pProgram; pSub; pSub=pNext){
59647 pNext = pSub->pNext;
59648 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
59649 sqlite3DbFree(db, pSub);
59651 vdbeFreeOpArray(db, p->aOp, p->nOp);
59652 sqlite3DbFree(db, p->aLabel);
59653 sqlite3DbFree(db, p->aColName);
59654 sqlite3DbFree(db, p->zSql);
59655 sqlite3DbFree(db, p->pFree);
59656 sqlite3DbFree(db, p);
59660 ** Delete an entire VDBE.
59662 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
59663 sqlite3 *db;
59665 if( NEVER(p==0) ) return;
59666 db = p->db;
59667 if( p->pPrev ){
59668 p->pPrev->pNext = p->pNext;
59669 }else{
59670 assert( db->pVdbe==p );
59671 db->pVdbe = p->pNext;
59673 if( p->pNext ){
59674 p->pNext->pPrev = p->pPrev;
59676 p->magic = VDBE_MAGIC_DEAD;
59677 p->db = 0;
59678 sqlite3VdbeDeleteObject(db, p);
59682 ** Make sure the cursor p is ready to read or write the row to which it
59683 ** was last positioned. Return an error code if an OOM fault or I/O error
59684 ** prevents us from positioning the cursor to its correct position.
59686 ** If a MoveTo operation is pending on the given cursor, then do that
59687 ** MoveTo now. If no move is pending, check to see if the row has been
59688 ** deleted out from under the cursor and if it has, mark the row as
59689 ** a NULL row.
59691 ** If the cursor is already pointing to the correct row and that row has
59692 ** not been deleted out from under the cursor, then this routine is a no-op.
59694 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
59695 if( p->deferredMoveto ){
59696 int res, rc;
59697 #ifdef SQLITE_TEST
59698 extern int sqlite3_search_count;
59699 #endif
59700 assert( p->isTable );
59701 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
59702 if( rc ) return rc;
59703 p->lastRowid = p->movetoTarget;
59704 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
59705 p->rowidIsValid = 1;
59706 #ifdef SQLITE_TEST
59707 sqlite3_search_count++;
59708 #endif
59709 p->deferredMoveto = 0;
59710 p->cacheStatus = CACHE_STALE;
59711 }else if( ALWAYS(p->pCursor) ){
59712 int hasMoved;
59713 int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
59714 if( rc ) return rc;
59715 if( hasMoved ){
59716 p->cacheStatus = CACHE_STALE;
59717 p->nullRow = 1;
59720 return SQLITE_OK;
59724 ** The following functions:
59726 ** sqlite3VdbeSerialType()
59727 ** sqlite3VdbeSerialTypeLen()
59728 ** sqlite3VdbeSerialLen()
59729 ** sqlite3VdbeSerialPut()
59730 ** sqlite3VdbeSerialGet()
59732 ** encapsulate the code that serializes values for storage in SQLite
59733 ** data and index records. Each serialized value consists of a
59734 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
59735 ** integer, stored as a varint.
59737 ** In an SQLite index record, the serial type is stored directly before
59738 ** the blob of data that it corresponds to. In a table record, all serial
59739 ** types are stored at the start of the record, and the blobs of data at
59740 ** the end. Hence these functions allow the caller to handle the
59741 ** serial-type and data blob seperately.
59743 ** The following table describes the various storage classes for data:
59745 ** serial type bytes of data type
59746 ** -------------- --------------- ---------------
59747 ** 0 0 NULL
59748 ** 1 1 signed integer
59749 ** 2 2 signed integer
59750 ** 3 3 signed integer
59751 ** 4 4 signed integer
59752 ** 5 6 signed integer
59753 ** 6 8 signed integer
59754 ** 7 8 IEEE float
59755 ** 8 0 Integer constant 0
59756 ** 9 0 Integer constant 1
59757 ** 10,11 reserved for expansion
59758 ** N>=12 and even (N-12)/2 BLOB
59759 ** N>=13 and odd (N-13)/2 text
59761 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
59762 ** of SQLite will not understand those serial types.
59766 ** Return the serial-type for the value stored in pMem.
59768 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
59769 int flags = pMem->flags;
59770 int n;
59772 if( flags&MEM_Null ){
59773 return 0;
59775 if( flags&MEM_Int ){
59776 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
59777 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
59778 i64 i = pMem->u.i;
59779 u64 u;
59780 if( file_format>=4 && (i&1)==i ){
59781 return 8+(u32)i;
59783 if( i<0 ){
59784 if( i<(-MAX_6BYTE) ) return 6;
59785 /* Previous test prevents: u = -(-9223372036854775808) */
59786 u = -i;
59787 }else{
59788 u = i;
59790 if( u<=127 ) return 1;
59791 if( u<=32767 ) return 2;
59792 if( u<=8388607 ) return 3;
59793 if( u<=2147483647 ) return 4;
59794 if( u<=MAX_6BYTE ) return 5;
59795 return 6;
59797 if( flags&MEM_Real ){
59798 return 7;
59800 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
59801 n = pMem->n;
59802 if( flags & MEM_Zero ){
59803 n += pMem->u.nZero;
59805 assert( n>=0 );
59806 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
59810 ** Return the length of the data corresponding to the supplied serial-type.
59812 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
59813 if( serial_type>=12 ){
59814 return (serial_type-12)/2;
59815 }else{
59816 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
59817 return aSize[serial_type];
59822 ** If we are on an architecture with mixed-endian floating
59823 ** points (ex: ARM7) then swap the lower 4 bytes with the
59824 ** upper 4 bytes. Return the result.
59826 ** For most architectures, this is a no-op.
59828 ** (later): It is reported to me that the mixed-endian problem
59829 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
59830 ** that early versions of GCC stored the two words of a 64-bit
59831 ** float in the wrong order. And that error has been propagated
59832 ** ever since. The blame is not necessarily with GCC, though.
59833 ** GCC might have just copying the problem from a prior compiler.
59834 ** I am also told that newer versions of GCC that follow a different
59835 ** ABI get the byte order right.
59837 ** Developers using SQLite on an ARM7 should compile and run their
59838 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
59839 ** enabled, some asserts below will ensure that the byte order of
59840 ** floating point values is correct.
59842 ** (2007-08-30) Frank van Vugt has studied this problem closely
59843 ** and has send his findings to the SQLite developers. Frank
59844 ** writes that some Linux kernels offer floating point hardware
59845 ** emulation that uses only 32-bit mantissas instead of a full
59846 ** 48-bits as required by the IEEE standard. (This is the
59847 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
59848 ** byte swapping becomes very complicated. To avoid problems,
59849 ** the necessary byte swapping is carried out using a 64-bit integer
59850 ** rather than a 64-bit float. Frank assures us that the code here
59851 ** works for him. We, the developers, have no way to independently
59852 ** verify this, but Frank seems to know what he is talking about
59853 ** so we trust him.
59855 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
59856 static u64 floatSwap(u64 in){
59857 union {
59858 u64 r;
59859 u32 i[2];
59860 } u;
59861 u32 t;
59863 u.r = in;
59864 t = u.i[0];
59865 u.i[0] = u.i[1];
59866 u.i[1] = t;
59867 return u.r;
59869 # define swapMixedEndianFloat(X) X = floatSwap(X)
59870 #else
59871 # define swapMixedEndianFloat(X)
59872 #endif
59875 ** Write the serialized data blob for the value stored in pMem into
59876 ** buf. It is assumed that the caller has allocated sufficient space.
59877 ** Return the number of bytes written.
59879 ** nBuf is the amount of space left in buf[]. nBuf must always be
59880 ** large enough to hold the entire field. Except, if the field is
59881 ** a blob with a zero-filled tail, then buf[] might be just the right
59882 ** size to hold everything except for the zero-filled tail. If buf[]
59883 ** is only big enough to hold the non-zero prefix, then only write that
59884 ** prefix into buf[]. But if buf[] is large enough to hold both the
59885 ** prefix and the tail then write the prefix and set the tail to all
59886 ** zeros.
59888 ** Return the number of bytes actually written into buf[]. The number
59889 ** of bytes in the zero-filled tail is included in the return value only
59890 ** if those bytes were zeroed in buf[].
59892 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
59893 u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
59894 u32 len;
59896 /* Integer and Real */
59897 if( serial_type<=7 && serial_type>0 ){
59898 u64 v;
59899 u32 i;
59900 if( serial_type==7 ){
59901 assert( sizeof(v)==sizeof(pMem->r) );
59902 memcpy(&v, &pMem->r, sizeof(v));
59903 swapMixedEndianFloat(v);
59904 }else{
59905 v = pMem->u.i;
59907 len = i = sqlite3VdbeSerialTypeLen(serial_type);
59908 assert( len<=(u32)nBuf );
59909 while( i-- ){
59910 buf[i] = (u8)(v&0xFF);
59911 v >>= 8;
59913 return len;
59916 /* String or blob */
59917 if( serial_type>=12 ){
59918 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
59919 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
59920 assert( pMem->n<=nBuf );
59921 len = pMem->n;
59922 memcpy(buf, pMem->z, len);
59923 if( pMem->flags & MEM_Zero ){
59924 len += pMem->u.nZero;
59925 assert( nBuf>=0 );
59926 if( len > (u32)nBuf ){
59927 len = (u32)nBuf;
59929 memset(&buf[pMem->n], 0, len-pMem->n);
59931 return len;
59934 /* NULL or constants 0 or 1 */
59935 return 0;
59939 ** Deserialize the data blob pointed to by buf as serial type serial_type
59940 ** and store the result in pMem. Return the number of bytes read.
59942 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
59943 const unsigned char *buf, /* Buffer to deserialize from */
59944 u32 serial_type, /* Serial type to deserialize */
59945 Mem *pMem /* Memory cell to write value into */
59947 switch( serial_type ){
59948 case 10: /* Reserved for future use */
59949 case 11: /* Reserved for future use */
59950 case 0: { /* NULL */
59951 pMem->flags = MEM_Null;
59952 break;
59954 case 1: { /* 1-byte signed integer */
59955 pMem->u.i = (signed char)buf[0];
59956 pMem->flags = MEM_Int;
59957 return 1;
59959 case 2: { /* 2-byte signed integer */
59960 pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
59961 pMem->flags = MEM_Int;
59962 return 2;
59964 case 3: { /* 3-byte signed integer */
59965 pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
59966 pMem->flags = MEM_Int;
59967 return 3;
59969 case 4: { /* 4-byte signed integer */
59970 pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
59971 pMem->flags = MEM_Int;
59972 return 4;
59974 case 5: { /* 6-byte signed integer */
59975 u64 x = (((signed char)buf[0])<<8) | buf[1];
59976 u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
59977 x = (x<<32) | y;
59978 pMem->u.i = *(i64*)&x;
59979 pMem->flags = MEM_Int;
59980 return 6;
59982 case 6: /* 8-byte signed integer */
59983 case 7: { /* IEEE floating point */
59984 u64 x;
59985 u32 y;
59986 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
59987 /* Verify that integers and floating point values use the same
59988 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
59989 ** defined that 64-bit floating point values really are mixed
59990 ** endian.
59992 static const u64 t1 = ((u64)0x3ff00000)<<32;
59993 static const double r1 = 1.0;
59994 u64 t2 = t1;
59995 swapMixedEndianFloat(t2);
59996 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
59997 #endif
59999 x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
60000 y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
60001 x = (x<<32) | y;
60002 if( serial_type==6 ){
60003 pMem->u.i = *(i64*)&x;
60004 pMem->flags = MEM_Int;
60005 }else{
60006 assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
60007 swapMixedEndianFloat(x);
60008 memcpy(&pMem->r, &x, sizeof(x));
60009 pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
60011 return 8;
60013 case 8: /* Integer 0 */
60014 case 9: { /* Integer 1 */
60015 pMem->u.i = serial_type-8;
60016 pMem->flags = MEM_Int;
60017 return 0;
60019 default: {
60020 u32 len = (serial_type-12)/2;
60021 pMem->z = (char *)buf;
60022 pMem->n = len;
60023 pMem->xDel = 0;
60024 if( serial_type&0x01 ){
60025 pMem->flags = MEM_Str | MEM_Ephem;
60026 }else{
60027 pMem->flags = MEM_Blob | MEM_Ephem;
60029 return len;
60032 return 0;
60037 ** Given the nKey-byte encoding of a record in pKey[], parse the
60038 ** record into a UnpackedRecord structure. Return a pointer to
60039 ** that structure.
60041 ** The calling function might provide szSpace bytes of memory
60042 ** space at pSpace. This space can be used to hold the returned
60043 ** VDbeParsedRecord structure if it is large enough. If it is
60044 ** not big enough, space is obtained from sqlite3_malloc().
60046 ** The returned structure should be closed by a call to
60047 ** sqlite3VdbeDeleteUnpackedRecord().
60049 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
60050 KeyInfo *pKeyInfo, /* Information about the record format */
60051 int nKey, /* Size of the binary record */
60052 const void *pKey, /* The binary record */
60053 char *pSpace, /* Unaligned space available to hold the object */
60054 int szSpace /* Size of pSpace[] in bytes */
60056 const unsigned char *aKey = (const unsigned char *)pKey;
60057 UnpackedRecord *p; /* The unpacked record that we will return */
60058 int nByte; /* Memory space needed to hold p, in bytes */
60059 int d;
60060 u32 idx;
60061 u16 u; /* Unsigned loop counter */
60062 u32 szHdr;
60063 Mem *pMem;
60064 int nOff; /* Increase pSpace by this much to 8-byte align it */
60067 ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
60068 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
60069 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
60071 nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
60072 pSpace += nOff;
60073 szSpace -= nOff;
60074 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
60075 if( nByte>szSpace ){
60076 p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
60077 if( p==0 ) return 0;
60078 p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
60079 }else{
60080 p = (UnpackedRecord*)pSpace;
60081 p->flags = UNPACKED_NEED_DESTROY;
60083 p->pKeyInfo = pKeyInfo;
60084 p->nField = pKeyInfo->nField + 1;
60085 p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
60086 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60087 idx = getVarint32(aKey, szHdr);
60088 d = szHdr;
60089 u = 0;
60090 while( idx<szHdr && u<p->nField && d<=nKey ){
60091 u32 serial_type;
60093 idx += getVarint32(&aKey[idx], serial_type);
60094 pMem->enc = pKeyInfo->enc;
60095 pMem->db = pKeyInfo->db;
60096 pMem->flags = 0;
60097 pMem->zMalloc = 0;
60098 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
60099 pMem++;
60100 u++;
60102 assert( u<=pKeyInfo->nField + 1 );
60103 p->nField = u;
60104 return (void*)p;
60108 ** This routine destroys a UnpackedRecord object.
60110 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
60111 int i;
60112 Mem *pMem;
60114 assert( p!=0 );
60115 assert( p->flags & UNPACKED_NEED_DESTROY );
60116 for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
60117 /* The unpacked record is always constructed by the
60118 ** sqlite3VdbeUnpackRecord() function above, which makes all
60119 ** strings and blobs static. And none of the elements are
60120 ** ever transformed, so there is never anything to delete.
60122 if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
60124 if( p->flags & UNPACKED_NEED_FREE ){
60125 sqlite3DbFree(p->pKeyInfo->db, p);
60130 ** This function compares the two table rows or index records
60131 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
60132 ** or positive integer if key1 is less than, equal to or
60133 ** greater than key2. The {nKey1, pKey1} key must be a blob
60134 ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
60135 ** key must be a parsed key such as obtained from
60136 ** sqlite3VdbeParseRecord.
60138 ** Key1 and Key2 do not have to contain the same number of fields.
60139 ** The key with fewer fields is usually compares less than the
60140 ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
60141 ** and the common prefixes are equal, then key1 is less than key2.
60142 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
60143 ** equal, then the keys are considered to be equal and
60144 ** the parts beyond the common prefix are ignored.
60146 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
60147 ** the header of pKey1 is ignored. It is assumed that pKey1 is
60148 ** an index key, and thus ends with a rowid value. The last byte
60149 ** of the header will therefore be the serial type of the rowid:
60150 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
60151 ** The serial type of the final rowid will always be a single byte.
60152 ** By ignoring this last byte of the header, we force the comparison
60153 ** to ignore the rowid at the end of key1.
60155 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
60156 int nKey1, const void *pKey1, /* Left key */
60157 UnpackedRecord *pPKey2 /* Right key */
60159 int d1; /* Offset into aKey[] of next data element */
60160 u32 idx1; /* Offset into aKey[] of next header element */
60161 u32 szHdr1; /* Number of bytes in header */
60162 int i = 0;
60163 int nField;
60164 int rc = 0;
60165 const unsigned char *aKey1 = (const unsigned char *)pKey1;
60166 KeyInfo *pKeyInfo;
60167 Mem mem1;
60169 pKeyInfo = pPKey2->pKeyInfo;
60170 mem1.enc = pKeyInfo->enc;
60171 mem1.db = pKeyInfo->db;
60172 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
60173 VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
60175 /* Compilers may complain that mem1.u.i is potentially uninitialized.
60176 ** We could initialize it, as shown here, to silence those complaints.
60177 ** But in fact, mem1.u.i will never actually be used initialized, and doing
60178 ** the unnecessary initialization has a measurable negative performance
60179 ** impact, since this routine is a very high runner. And so, we choose
60180 ** to ignore the compiler warnings and leave this variable uninitialized.
60182 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
60184 idx1 = getVarint32(aKey1, szHdr1);
60185 d1 = szHdr1;
60186 if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
60187 szHdr1--;
60189 nField = pKeyInfo->nField;
60190 while( idx1<szHdr1 && i<pPKey2->nField ){
60191 u32 serial_type1;
60193 /* Read the serial types for the next element in each key. */
60194 idx1 += getVarint32( aKey1+idx1, serial_type1 );
60195 if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
60197 /* Extract the values to be compared.
60199 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
60201 /* Do the comparison
60203 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
60204 i<nField ? pKeyInfo->aColl[i] : 0);
60205 if( rc!=0 ){
60206 assert( mem1.zMalloc==0 ); /* See comment below */
60208 /* Invert the result if we are using DESC sort order. */
60209 if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
60210 rc = -rc;
60213 /* If the PREFIX_SEARCH flag is set and all fields except the final
60214 ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
60215 ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
60216 ** This is used by the OP_IsUnique opcode.
60218 if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
60219 assert( idx1==szHdr1 && rc );
60220 assert( mem1.flags & MEM_Int );
60221 pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
60222 pPKey2->rowid = mem1.u.i;
60225 return rc;
60227 i++;
60230 /* No memory allocation is ever used on mem1. Prove this using
60231 ** the following assert(). If the assert() fails, it indicates a
60232 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
60234 assert( mem1.zMalloc==0 );
60236 /* rc==0 here means that one of the keys ran out of fields and
60237 ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
60238 ** flag is set, then break the tie by treating key2 as larger.
60239 ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
60240 ** are considered to be equal. Otherwise, the longer key is the
60241 ** larger. As it happens, the pPKey2 will always be the longer
60242 ** if there is a difference.
60244 assert( rc==0 );
60245 if( pPKey2->flags & UNPACKED_INCRKEY ){
60246 rc = -1;
60247 }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
60248 /* Leave rc==0 */
60249 }else if( idx1<szHdr1 ){
60250 rc = 1;
60252 return rc;
60257 ** pCur points at an index entry created using the OP_MakeRecord opcode.
60258 ** Read the rowid (the last field in the record) and store it in *rowid.
60259 ** Return SQLITE_OK if everything works, or an error code otherwise.
60261 ** pCur might be pointing to text obtained from a corrupt database file.
60262 ** So the content cannot be trusted. Do appropriate checks on the content.
60264 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
60265 i64 nCellKey = 0;
60266 int rc;
60267 u32 szHdr; /* Size of the header */
60268 u32 typeRowid; /* Serial type of the rowid */
60269 u32 lenRowid; /* Size of the rowid */
60270 Mem m, v;
60272 UNUSED_PARAMETER(db);
60274 /* Get the size of the index entry. Only indices entries of less
60275 ** than 2GiB are support - anything large must be database corruption.
60276 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
60277 ** this code can safely assume that nCellKey is 32-bits
60279 assert( sqlite3BtreeCursorIsValid(pCur) );
60280 rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60281 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
60282 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
60284 /* Read in the complete content of the index entry */
60285 memset(&m, 0, sizeof(m));
60286 rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
60287 if( rc ){
60288 return rc;
60291 /* The index entry must begin with a header size */
60292 (void)getVarint32((u8*)m.z, szHdr);
60293 testcase( szHdr==3 );
60294 testcase( szHdr==m.n );
60295 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
60296 goto idx_rowid_corruption;
60299 /* The last field of the index should be an integer - the ROWID.
60300 ** Verify that the last entry really is an integer. */
60301 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
60302 testcase( typeRowid==1 );
60303 testcase( typeRowid==2 );
60304 testcase( typeRowid==3 );
60305 testcase( typeRowid==4 );
60306 testcase( typeRowid==5 );
60307 testcase( typeRowid==6 );
60308 testcase( typeRowid==8 );
60309 testcase( typeRowid==9 );
60310 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
60311 goto idx_rowid_corruption;
60313 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
60314 testcase( (u32)m.n==szHdr+lenRowid );
60315 if( unlikely((u32)m.n<szHdr+lenRowid) ){
60316 goto idx_rowid_corruption;
60319 /* Fetch the integer off the end of the index record */
60320 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
60321 *rowid = v.u.i;
60322 sqlite3VdbeMemRelease(&m);
60323 return SQLITE_OK;
60325 /* Jump here if database corruption is detected after m has been
60326 ** allocated. Free the m object and return SQLITE_CORRUPT. */
60327 idx_rowid_corruption:
60328 testcase( m.zMalloc!=0 );
60329 sqlite3VdbeMemRelease(&m);
60330 return SQLITE_CORRUPT_BKPT;
60334 ** Compare the key of the index entry that cursor pC is pointing to against
60335 ** the key string in pUnpacked. Write into *pRes a number
60336 ** that is negative, zero, or positive if pC is less than, equal to,
60337 ** or greater than pUnpacked. Return SQLITE_OK on success.
60339 ** pUnpacked is either created without a rowid or is truncated so that it
60340 ** omits the rowid at the end. The rowid at the end of the index entry
60341 ** is ignored as well. Hence, this routine only compares the prefixes
60342 ** of the keys prior to the final rowid, not the entire key.
60344 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
60345 VdbeCursor *pC, /* The cursor to compare against */
60346 UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
60347 int *res /* Write the comparison result here */
60349 i64 nCellKey = 0;
60350 int rc;
60351 BtCursor *pCur = pC->pCursor;
60352 Mem m;
60354 assert( sqlite3BtreeCursorIsValid(pCur) );
60355 rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60356 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
60357 /* nCellKey will always be between 0 and 0xffffffff because of the say
60358 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
60359 if( nCellKey<=0 || nCellKey>0x7fffffff ){
60360 *res = 0;
60361 return SQLITE_CORRUPT_BKPT;
60363 memset(&m, 0, sizeof(m));
60364 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
60365 if( rc ){
60366 return rc;
60368 assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
60369 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
60370 sqlite3VdbeMemRelease(&m);
60371 return SQLITE_OK;
60375 ** This routine sets the value to be returned by subsequent calls to
60376 ** sqlite3_changes() on the database handle 'db'.
60378 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
60379 assert( sqlite3_mutex_held(db->mutex) );
60380 db->nChange = nChange;
60381 db->nTotalChange += nChange;
60385 ** Set a flag in the vdbe to update the change counter when it is finalised
60386 ** or reset.
60388 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
60389 v->changeCntOn = 1;
60393 ** Mark every prepared statement associated with a database connection
60394 ** as expired.
60396 ** An expired statement means that recompilation of the statement is
60397 ** recommend. Statements expire when things happen that make their
60398 ** programs obsolete. Removing user-defined functions or collating
60399 ** sequences, or changing an authorization function are the types of
60400 ** things that make prepared statements obsolete.
60402 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
60403 Vdbe *p;
60404 for(p = db->pVdbe; p; p=p->pNext){
60405 p->expired = 1;
60410 ** Return the database associated with the Vdbe.
60412 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
60413 return v->db;
60417 ** Return a pointer to an sqlite3_value structure containing the value bound
60418 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
60419 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
60420 ** constants) to the value before returning it.
60422 ** The returned value must be freed by the caller using sqlite3ValueFree().
60424 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
60425 assert( iVar>0 );
60426 if( v ){
60427 Mem *pMem = &v->aVar[iVar-1];
60428 if( 0==(pMem->flags & MEM_Null) ){
60429 sqlite3_value *pRet = sqlite3ValueNew(v->db);
60430 if( pRet ){
60431 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
60432 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
60433 sqlite3VdbeMemStoreType((Mem *)pRet);
60435 return pRet;
60438 return 0;
60442 ** Configure SQL variable iVar so that binding a new value to it signals
60443 ** to sqlite3_reoptimize() that re-preparing the statement may result
60444 ** in a better query plan.
60446 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
60447 assert( iVar>0 );
60448 if( iVar>32 ){
60449 v->expmask = 0xffffffff;
60450 }else{
60451 v->expmask |= ((u32)1 << (iVar-1));
60455 /************** End of vdbeaux.c *********************************************/
60456 /************** Begin file vdbeapi.c *****************************************/
60458 ** 2004 May 26
60460 ** The author disclaims copyright to this source code. In place of
60461 ** a legal notice, here is a blessing:
60463 ** May you do good and not evil.
60464 ** May you find forgiveness for yourself and forgive others.
60465 ** May you share freely, never taking more than you give.
60467 *************************************************************************
60469 ** This file contains code use to implement APIs that are part of the
60470 ** VDBE.
60473 #ifndef SQLITE_OMIT_DEPRECATED
60475 ** Return TRUE (non-zero) of the statement supplied as an argument needs
60476 ** to be recompiled. A statement needs to be recompiled whenever the
60477 ** execution environment changes in a way that would alter the program
60478 ** that sqlite3_prepare() generates. For example, if new functions or
60479 ** collating sequences are registered or if an authorizer function is
60480 ** added or changed.
60482 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
60483 Vdbe *p = (Vdbe*)pStmt;
60484 return p==0 || p->expired;
60486 #endif
60489 ** Check on a Vdbe to make sure it has not been finalized. Log
60490 ** an error and return true if it has been finalized (or is otherwise
60491 ** invalid). Return false if it is ok.
60493 static int vdbeSafety(Vdbe *p){
60494 if( p->db==0 ){
60495 sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
60496 return 1;
60497 }else{
60498 return 0;
60501 static int vdbeSafetyNotNull(Vdbe *p){
60502 if( p==0 ){
60503 sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
60504 return 1;
60505 }else{
60506 return vdbeSafety(p);
60511 ** The following routine destroys a virtual machine that is created by
60512 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
60513 ** success/failure code that describes the result of executing the virtual
60514 ** machine.
60516 ** This routine sets the error code and string returned by
60517 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60519 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
60520 int rc;
60521 if( pStmt==0 ){
60522 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
60523 ** pointer is a harmless no-op. */
60524 rc = SQLITE_OK;
60525 }else{
60526 Vdbe *v = (Vdbe*)pStmt;
60527 sqlite3 *db = v->db;
60528 #if SQLITE_THREADSAFE
60529 sqlite3_mutex *mutex;
60530 #endif
60531 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
60532 #if SQLITE_THREADSAFE
60533 mutex = v->db->mutex;
60534 #endif
60535 sqlite3_mutex_enter(mutex);
60536 rc = sqlite3VdbeFinalize(v);
60537 rc = sqlite3ApiExit(db, rc);
60538 sqlite3_mutex_leave(mutex);
60540 return rc;
60544 ** Terminate the current execution of an SQL statement and reset it
60545 ** back to its starting state so that it can be reused. A success code from
60546 ** the prior execution is returned.
60548 ** This routine sets the error code and string returned by
60549 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60551 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
60552 int rc;
60553 if( pStmt==0 ){
60554 rc = SQLITE_OK;
60555 }else{
60556 Vdbe *v = (Vdbe*)pStmt;
60557 sqlite3_mutex_enter(v->db->mutex);
60558 rc = sqlite3VdbeReset(v);
60559 sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
60560 assert( (rc & (v->db->errMask))==rc );
60561 rc = sqlite3ApiExit(v->db, rc);
60562 sqlite3_mutex_leave(v->db->mutex);
60564 return rc;
60568 ** Set all the parameters in the compiled SQL statement to NULL.
60570 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
60571 int i;
60572 int rc = SQLITE_OK;
60573 Vdbe *p = (Vdbe*)pStmt;
60574 #if SQLITE_THREADSAFE
60575 sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
60576 #endif
60577 sqlite3_mutex_enter(mutex);
60578 for(i=0; i<p->nVar; i++){
60579 sqlite3VdbeMemRelease(&p->aVar[i]);
60580 p->aVar[i].flags = MEM_Null;
60582 if( p->isPrepareV2 && p->expmask ){
60583 p->expired = 1;
60585 sqlite3_mutex_leave(mutex);
60586 return rc;
60590 /**************************** sqlite3_value_ *******************************
60591 ** The following routines extract information from a Mem or sqlite3_value
60592 ** structure.
60594 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
60595 Mem *p = (Mem*)pVal;
60596 if( p->flags & (MEM_Blob|MEM_Str) ){
60597 sqlite3VdbeMemExpandBlob(p);
60598 p->flags &= ~MEM_Str;
60599 p->flags |= MEM_Blob;
60600 return p->n ? p->z : 0;
60601 }else{
60602 return sqlite3_value_text(pVal);
60605 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
60606 return sqlite3ValueBytes(pVal, SQLITE_UTF8);
60608 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
60609 return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
60611 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
60612 return sqlite3VdbeRealValue((Mem*)pVal);
60614 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
60615 return (int)sqlite3VdbeIntValue((Mem*)pVal);
60617 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
60618 return sqlite3VdbeIntValue((Mem*)pVal);
60620 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
60621 return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
60623 #ifndef SQLITE_OMIT_UTF16
60624 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
60625 return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
60627 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
60628 return sqlite3ValueText(pVal, SQLITE_UTF16BE);
60630 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
60631 return sqlite3ValueText(pVal, SQLITE_UTF16LE);
60633 #endif /* SQLITE_OMIT_UTF16 */
60634 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
60635 return pVal->type;
60638 /**************************** sqlite3_result_ *******************************
60639 ** The following routines are used by user-defined functions to specify
60640 ** the function result.
60642 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
60643 ** result as a string or blob but if the string or blob is too large, it
60644 ** then sets the error code to SQLITE_TOOBIG
60646 static void setResultStrOrError(
60647 sqlite3_context *pCtx, /* Function context */
60648 const char *z, /* String pointer */
60649 int n, /* Bytes in string, or negative */
60650 u8 enc, /* Encoding of z. 0 for BLOBs */
60651 void (*xDel)(void*) /* Destructor function */
60653 if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
60654 sqlite3_result_error_toobig(pCtx);
60657 SQLITE_API void sqlite3_result_blob(
60658 sqlite3_context *pCtx,
60659 const void *z,
60660 int n,
60661 void (*xDel)(void *)
60663 assert( n>=0 );
60664 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60665 setResultStrOrError(pCtx, z, n, 0, xDel);
60667 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
60668 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60669 sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
60671 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
60672 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60673 pCtx->isError = SQLITE_ERROR;
60674 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
60676 #ifndef SQLITE_OMIT_UTF16
60677 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
60678 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60679 pCtx->isError = SQLITE_ERROR;
60680 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
60682 #endif
60683 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
60684 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60685 sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
60687 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
60688 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60689 sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
60691 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
60692 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60693 sqlite3VdbeMemSetNull(&pCtx->s);
60695 SQLITE_API void sqlite3_result_text(
60696 sqlite3_context *pCtx,
60697 const char *z,
60698 int n,
60699 void (*xDel)(void *)
60701 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60702 setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
60704 #ifndef SQLITE_OMIT_UTF16
60705 SQLITE_API void sqlite3_result_text16(
60706 sqlite3_context *pCtx,
60707 const void *z,
60708 int n,
60709 void (*xDel)(void *)
60711 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60712 setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
60714 SQLITE_API void sqlite3_result_text16be(
60715 sqlite3_context *pCtx,
60716 const void *z,
60717 int n,
60718 void (*xDel)(void *)
60720 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60721 setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
60723 SQLITE_API void sqlite3_result_text16le(
60724 sqlite3_context *pCtx,
60725 const void *z,
60726 int n,
60727 void (*xDel)(void *)
60729 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60730 setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
60732 #endif /* SQLITE_OMIT_UTF16 */
60733 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
60734 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60735 sqlite3VdbeMemCopy(&pCtx->s, pValue);
60737 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
60738 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60739 sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
60741 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
60742 pCtx->isError = errCode;
60743 if( pCtx->s.flags & MEM_Null ){
60744 sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
60745 SQLITE_UTF8, SQLITE_STATIC);
60749 /* Force an SQLITE_TOOBIG error. */
60750 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
60751 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60752 pCtx->isError = SQLITE_TOOBIG;
60753 sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
60754 SQLITE_UTF8, SQLITE_STATIC);
60757 /* An SQLITE_NOMEM error. */
60758 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
60759 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60760 sqlite3VdbeMemSetNull(&pCtx->s);
60761 pCtx->isError = SQLITE_NOMEM;
60762 pCtx->s.db->mallocFailed = 1;
60766 ** This function is called after a transaction has been committed. It
60767 ** invokes callbacks registered with sqlite3_wal_hook() as required.
60769 static int doWalCallbacks(sqlite3 *db){
60770 int rc = SQLITE_OK;
60771 #ifndef SQLITE_OMIT_WAL
60772 int i;
60773 for(i=0; i<db->nDb; i++){
60774 Btree *pBt = db->aDb[i].pBt;
60775 if( pBt ){
60776 int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
60777 if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
60778 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
60782 #endif
60783 return rc;
60787 ** Execute the statement pStmt, either until a row of data is ready, the
60788 ** statement is completely executed or an error occurs.
60790 ** This routine implements the bulk of the logic behind the sqlite_step()
60791 ** API. The only thing omitted is the automatic recompile if a
60792 ** schema change has occurred. That detail is handled by the
60793 ** outer sqlite3_step() wrapper procedure.
60795 static int sqlite3Step(Vdbe *p){
60796 sqlite3 *db;
60797 int rc;
60799 assert(p);
60800 if( p->magic!=VDBE_MAGIC_RUN ){
60801 /* We used to require that sqlite3_reset() be called before retrying
60802 ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
60803 ** with version 3.7.0, we changed this so that sqlite3_reset() would
60804 ** be called automatically instead of throwing the SQLITE_MISUSE error.
60805 ** This "automatic-reset" change is not technically an incompatibility,
60806 ** since any application that receives an SQLITE_MISUSE is broken by
60807 ** definition.
60809 ** Nevertheless, some published applications that were originally written
60810 ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
60811 ** returns, and the so were broken by the automatic-reset change. As a
60812 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
60813 ** legacy behavior of returning SQLITE_MISUSE for cases where the
60814 ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
60815 ** or SQLITE_BUSY error.
60817 #ifdef SQLITE_OMIT_AUTORESET
60818 if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
60819 sqlite3_reset((sqlite3_stmt*)p);
60820 }else{
60821 return SQLITE_MISUSE_BKPT;
60823 #else
60824 sqlite3_reset((sqlite3_stmt*)p);
60825 #endif
60828 /* Check that malloc() has not failed. If it has, return early. */
60829 db = p->db;
60830 if( db->mallocFailed ){
60831 p->rc = SQLITE_NOMEM;
60832 return SQLITE_NOMEM;
60835 if( p->pc<=0 && p->expired ){
60836 p->rc = SQLITE_SCHEMA;
60837 rc = SQLITE_ERROR;
60838 goto end_of_step;
60840 if( p->pc<0 ){
60841 /* If there are no other statements currently running, then
60842 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
60843 ** from interrupting a statement that has not yet started.
60845 if( db->activeVdbeCnt==0 ){
60846 db->u1.isInterrupted = 0;
60849 assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
60851 #ifndef SQLITE_OMIT_TRACE
60852 if( db->xProfile && !db->init.busy ){
60853 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
60855 #endif
60857 db->activeVdbeCnt++;
60858 if( p->readOnly==0 ) db->writeVdbeCnt++;
60859 p->pc = 0;
60861 #ifndef SQLITE_OMIT_EXPLAIN
60862 if( p->explain ){
60863 rc = sqlite3VdbeList(p);
60864 }else
60865 #endif /* SQLITE_OMIT_EXPLAIN */
60867 db->vdbeExecCnt++;
60868 rc = sqlite3VdbeExec(p);
60869 db->vdbeExecCnt--;
60872 #ifndef SQLITE_OMIT_TRACE
60873 /* Invoke the profile callback if there is one
60875 if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
60876 sqlite3_int64 iNow;
60877 sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
60878 db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
60880 #endif
60882 if( rc==SQLITE_DONE ){
60883 assert( p->rc==SQLITE_OK );
60884 p->rc = doWalCallbacks(db);
60885 if( p->rc!=SQLITE_OK ){
60886 rc = SQLITE_ERROR;
60890 db->errCode = rc;
60891 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
60892 p->rc = SQLITE_NOMEM;
60894 end_of_step:
60895 /* At this point local variable rc holds the value that should be
60896 ** returned if this statement was compiled using the legacy
60897 ** sqlite3_prepare() interface. According to the docs, this can only
60898 ** be one of the values in the first assert() below. Variable p->rc
60899 ** contains the value that would be returned if sqlite3_finalize()
60900 ** were called on statement p.
60902 assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
60903 || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
60905 assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
60906 if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
60907 /* If this statement was prepared using sqlite3_prepare_v2(), and an
60908 ** error has occured, then return the error code in p->rc to the
60909 ** caller. Set the error code in the database handle to the same value.
60911 rc = db->errCode = p->rc;
60913 return (rc&db->errMask);
60917 ** This is the top-level implementation of sqlite3_step(). Call
60918 ** sqlite3Step() to do most of the work. If a schema error occurs,
60919 ** call sqlite3Reprepare() and try again.
60921 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
60922 int rc = SQLITE_OK; /* Result from sqlite3Step() */
60923 int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
60924 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
60925 int cnt = 0; /* Counter to prevent infinite loop of reprepares */
60926 sqlite3 *db; /* The database connection */
60928 if( vdbeSafetyNotNull(v) ){
60929 return SQLITE_MISUSE_BKPT;
60931 db = v->db;
60932 sqlite3_mutex_enter(db->mutex);
60933 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
60934 && cnt++ < 5
60935 && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
60936 sqlite3_reset(pStmt);
60937 v->expired = 0;
60939 if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
60940 /* This case occurs after failing to recompile an sql statement.
60941 ** The error message from the SQL compiler has already been loaded
60942 ** into the database handle. This block copies the error message
60943 ** from the database handle into the statement and sets the statement
60944 ** program counter to 0 to ensure that when the statement is
60945 ** finalized or reset the parser error message is available via
60946 ** sqlite3_errmsg() and sqlite3_errcode().
60948 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
60949 sqlite3DbFree(db, v->zErrMsg);
60950 if( !db->mallocFailed ){
60951 v->zErrMsg = sqlite3DbStrDup(db, zErr);
60952 v->rc = rc2;
60953 } else {
60954 v->zErrMsg = 0;
60955 v->rc = rc = SQLITE_NOMEM;
60958 rc = sqlite3ApiExit(db, rc);
60959 sqlite3_mutex_leave(db->mutex);
60960 return rc;
60964 ** Extract the user data from a sqlite3_context structure and return a
60965 ** pointer to it.
60967 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
60968 assert( p && p->pFunc );
60969 return p->pFunc->pUserData;
60973 ** Extract the user data from a sqlite3_context structure and return a
60974 ** pointer to it.
60976 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
60977 ** returns a copy of the pointer to the database connection (the 1st
60978 ** parameter) of the sqlite3_create_function() and
60979 ** sqlite3_create_function16() routines that originally registered the
60980 ** application defined function.
60982 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
60983 assert( p && p->pFunc );
60984 return p->s.db;
60988 ** The following is the implementation of an SQL function that always
60989 ** fails with an error message stating that the function is used in the
60990 ** wrong context. The sqlite3_overload_function() API might construct
60991 ** SQL function that use this routine so that the functions will exist
60992 ** for name resolution but are actually overloaded by the xFindFunction
60993 ** method of virtual tables.
60995 SQLITE_PRIVATE void sqlite3InvalidFunction(
60996 sqlite3_context *context, /* The function calling context */
60997 int NotUsed, /* Number of arguments to the function */
60998 sqlite3_value **NotUsed2 /* Value of each argument */
61000 const char *zName = context->pFunc->zName;
61001 char *zErr;
61002 UNUSED_PARAMETER2(NotUsed, NotUsed2);
61003 zErr = sqlite3_mprintf(
61004 "unable to use function %s in the requested context", zName);
61005 sqlite3_result_error(context, zErr, -1);
61006 sqlite3_free(zErr);
61010 ** Allocate or return the aggregate context for a user function. A new
61011 ** context is allocated on the first call. Subsequent calls return the
61012 ** same context that was returned on prior calls.
61014 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
61015 Mem *pMem;
61016 assert( p && p->pFunc && p->pFunc->xStep );
61017 assert( sqlite3_mutex_held(p->s.db->mutex) );
61018 pMem = p->pMem;
61019 testcase( nByte<0 );
61020 if( (pMem->flags & MEM_Agg)==0 ){
61021 if( nByte<=0 ){
61022 sqlite3VdbeMemReleaseExternal(pMem);
61023 pMem->flags = MEM_Null;
61024 pMem->z = 0;
61025 }else{
61026 sqlite3VdbeMemGrow(pMem, nByte, 0);
61027 pMem->flags = MEM_Agg;
61028 pMem->u.pDef = p->pFunc;
61029 if( pMem->z ){
61030 memset(pMem->z, 0, nByte);
61034 return (void*)pMem->z;
61038 ** Return the auxilary data pointer, if any, for the iArg'th argument to
61039 ** the user-function defined by pCtx.
61041 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
61042 VdbeFunc *pVdbeFunc;
61044 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61045 pVdbeFunc = pCtx->pVdbeFunc;
61046 if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
61047 return 0;
61049 return pVdbeFunc->apAux[iArg].pAux;
61053 ** Set the auxilary data pointer and delete function, for the iArg'th
61054 ** argument to the user-function defined by pCtx. Any previous value is
61055 ** deleted by calling the delete function specified when it was set.
61057 SQLITE_API void sqlite3_set_auxdata(
61058 sqlite3_context *pCtx,
61059 int iArg,
61060 void *pAux,
61061 void (*xDelete)(void*)
61063 struct AuxData *pAuxData;
61064 VdbeFunc *pVdbeFunc;
61065 if( iArg<0 ) goto failed;
61067 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61068 pVdbeFunc = pCtx->pVdbeFunc;
61069 if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
61070 int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
61071 int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
61072 pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
61073 if( !pVdbeFunc ){
61074 goto failed;
61076 pCtx->pVdbeFunc = pVdbeFunc;
61077 memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
61078 pVdbeFunc->nAux = iArg+1;
61079 pVdbeFunc->pFunc = pCtx->pFunc;
61082 pAuxData = &pVdbeFunc->apAux[iArg];
61083 if( pAuxData->pAux && pAuxData->xDelete ){
61084 pAuxData->xDelete(pAuxData->pAux);
61086 pAuxData->pAux = pAux;
61087 pAuxData->xDelete = xDelete;
61088 return;
61090 failed:
61091 if( xDelete ){
61092 xDelete(pAux);
61096 #ifndef SQLITE_OMIT_DEPRECATED
61098 ** Return the number of times the Step function of a aggregate has been
61099 ** called.
61101 ** This function is deprecated. Do not use it for new code. It is
61102 ** provide only to avoid breaking legacy code. New aggregate function
61103 ** implementations should keep their own counts within their aggregate
61104 ** context.
61106 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
61107 assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
61108 return p->pMem->n;
61110 #endif
61113 ** Return the number of columns in the result set for the statement pStmt.
61115 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
61116 Vdbe *pVm = (Vdbe *)pStmt;
61117 return pVm ? pVm->nResColumn : 0;
61121 ** Return the number of values available from the current row of the
61122 ** currently executing statement pStmt.
61124 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
61125 Vdbe *pVm = (Vdbe *)pStmt;
61126 if( pVm==0 || pVm->pResultSet==0 ) return 0;
61127 return pVm->nResColumn;
61132 ** Check to see if column iCol of the given statement is valid. If
61133 ** it is, return a pointer to the Mem for the value of that column.
61134 ** If iCol is not valid, return a pointer to a Mem which has a value
61135 ** of NULL.
61137 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
61138 Vdbe *pVm;
61139 Mem *pOut;
61141 pVm = (Vdbe *)pStmt;
61142 if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
61143 sqlite3_mutex_enter(pVm->db->mutex);
61144 pOut = &pVm->pResultSet[i];
61145 }else{
61146 /* If the value passed as the second argument is out of range, return
61147 ** a pointer to the following static Mem object which contains the
61148 ** value SQL NULL. Even though the Mem structure contains an element
61149 ** of type i64, on certain architecture (x86) with certain compiler
61150 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
61151 ** instead of an 8-byte one. This all works fine, except that when
61152 ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
61153 ** that a Mem structure is located on an 8-byte boundary. To prevent
61154 ** this assert() from failing, when building with SQLITE_DEBUG defined
61155 ** using gcc, force nullMem to be 8-byte aligned using the magical
61156 ** __attribute__((aligned(8))) macro. */
61157 static const Mem nullMem
61158 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
61159 __attribute__((aligned(8)))
61160 #endif
61161 = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
61162 #ifdef SQLITE_DEBUG
61163 0, 0, /* pScopyFrom, pFiller */
61164 #endif
61165 0, 0 };
61167 if( pVm && ALWAYS(pVm->db) ){
61168 sqlite3_mutex_enter(pVm->db->mutex);
61169 sqlite3Error(pVm->db, SQLITE_RANGE, 0);
61171 pOut = (Mem*)&nullMem;
61173 return pOut;
61177 ** This function is called after invoking an sqlite3_value_XXX function on a
61178 ** column value (i.e. a value returned by evaluating an SQL expression in the
61179 ** select list of a SELECT statement) that may cause a malloc() failure. If
61180 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
61181 ** code of statement pStmt set to SQLITE_NOMEM.
61183 ** Specifically, this is called from within:
61185 ** sqlite3_column_int()
61186 ** sqlite3_column_int64()
61187 ** sqlite3_column_text()
61188 ** sqlite3_column_text16()
61189 ** sqlite3_column_real()
61190 ** sqlite3_column_bytes()
61191 ** sqlite3_column_bytes16()
61192 ** sqiite3_column_blob()
61194 static void columnMallocFailure(sqlite3_stmt *pStmt)
61196 /* If malloc() failed during an encoding conversion within an
61197 ** sqlite3_column_XXX API, then set the return code of the statement to
61198 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
61199 ** and _finalize() will return NOMEM.
61201 Vdbe *p = (Vdbe *)pStmt;
61202 if( p ){
61203 p->rc = sqlite3ApiExit(p->db, p->rc);
61204 sqlite3_mutex_leave(p->db->mutex);
61208 /**************************** sqlite3_column_ *******************************
61209 ** The following routines are used to access elements of the current row
61210 ** in the result set.
61212 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
61213 const void *val;
61214 val = sqlite3_value_blob( columnMem(pStmt,i) );
61215 /* Even though there is no encoding conversion, value_blob() might
61216 ** need to call malloc() to expand the result of a zeroblob()
61217 ** expression.
61219 columnMallocFailure(pStmt);
61220 return val;
61222 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
61223 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
61224 columnMallocFailure(pStmt);
61225 return val;
61227 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
61228 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
61229 columnMallocFailure(pStmt);
61230 return val;
61232 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
61233 double val = sqlite3_value_double( columnMem(pStmt,i) );
61234 columnMallocFailure(pStmt);
61235 return val;
61237 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
61238 int val = sqlite3_value_int( columnMem(pStmt,i) );
61239 columnMallocFailure(pStmt);
61240 return val;
61242 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
61243 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
61244 columnMallocFailure(pStmt);
61245 return val;
61247 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
61248 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
61249 columnMallocFailure(pStmt);
61250 return val;
61252 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
61253 Mem *pOut = columnMem(pStmt, i);
61254 if( pOut->flags&MEM_Static ){
61255 pOut->flags &= ~MEM_Static;
61256 pOut->flags |= MEM_Ephem;
61258 columnMallocFailure(pStmt);
61259 return (sqlite3_value *)pOut;
61261 #ifndef SQLITE_OMIT_UTF16
61262 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
61263 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
61264 columnMallocFailure(pStmt);
61265 return val;
61267 #endif /* SQLITE_OMIT_UTF16 */
61268 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
61269 int iType = sqlite3_value_type( columnMem(pStmt,i) );
61270 columnMallocFailure(pStmt);
61271 return iType;
61274 /* The following function is experimental and subject to change or
61275 ** removal */
61276 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
61277 ** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
61282 ** Convert the N-th element of pStmt->pColName[] into a string using
61283 ** xFunc() then return that string. If N is out of range, return 0.
61285 ** There are up to 5 names for each column. useType determines which
61286 ** name is returned. Here are the names:
61288 ** 0 The column name as it should be displayed for output
61289 ** 1 The datatype name for the column
61290 ** 2 The name of the database that the column derives from
61291 ** 3 The name of the table that the column derives from
61292 ** 4 The name of the table column that the result column derives from
61294 ** If the result is not a simple column reference (if it is an expression
61295 ** or a constant) then useTypes 2, 3, and 4 return NULL.
61297 static const void *columnName(
61298 sqlite3_stmt *pStmt,
61299 int N,
61300 const void *(*xFunc)(Mem*),
61301 int useType
61303 const void *ret = 0;
61304 Vdbe *p = (Vdbe *)pStmt;
61305 int n;
61306 sqlite3 *db = p->db;
61308 assert( db!=0 );
61309 n = sqlite3_column_count(pStmt);
61310 if( N<n && N>=0 ){
61311 N += useType*n;
61312 sqlite3_mutex_enter(db->mutex);
61313 assert( db->mallocFailed==0 );
61314 ret = xFunc(&p->aColName[N]);
61315 /* A malloc may have failed inside of the xFunc() call. If this
61316 ** is the case, clear the mallocFailed flag and return NULL.
61318 if( db->mallocFailed ){
61319 db->mallocFailed = 0;
61320 ret = 0;
61322 sqlite3_mutex_leave(db->mutex);
61324 return ret;
61328 ** Return the name of the Nth column of the result set returned by SQL
61329 ** statement pStmt.
61331 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
61332 return columnName(
61333 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
61335 #ifndef SQLITE_OMIT_UTF16
61336 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
61337 return columnName(
61338 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
61340 #endif
61343 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
61344 ** not define OMIT_DECLTYPE.
61346 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
61347 # error "Must not define both SQLITE_OMIT_DECLTYPE \
61348 and SQLITE_ENABLE_COLUMN_METADATA"
61349 #endif
61351 #ifndef SQLITE_OMIT_DECLTYPE
61353 ** Return the column declaration type (if applicable) of the 'i'th column
61354 ** of the result set of SQL statement pStmt.
61356 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
61357 return columnName(
61358 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
61360 #ifndef SQLITE_OMIT_UTF16
61361 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
61362 return columnName(
61363 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
61365 #endif /* SQLITE_OMIT_UTF16 */
61366 #endif /* SQLITE_OMIT_DECLTYPE */
61368 #ifdef SQLITE_ENABLE_COLUMN_METADATA
61370 ** Return the name of the database from which a result column derives.
61371 ** NULL is returned if the result column is an expression or constant or
61372 ** anything else which is not an unabiguous reference to a database column.
61374 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
61375 return columnName(
61376 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
61378 #ifndef SQLITE_OMIT_UTF16
61379 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
61380 return columnName(
61381 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
61383 #endif /* SQLITE_OMIT_UTF16 */
61386 ** Return the name of the table from which a result column derives.
61387 ** NULL is returned if the result column is an expression or constant or
61388 ** anything else which is not an unabiguous reference to a database column.
61390 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
61391 return columnName(
61392 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
61394 #ifndef SQLITE_OMIT_UTF16
61395 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
61396 return columnName(
61397 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
61399 #endif /* SQLITE_OMIT_UTF16 */
61402 ** Return the name of the table column from which a result column derives.
61403 ** NULL is returned if the result column is an expression or constant or
61404 ** anything else which is not an unabiguous reference to a database column.
61406 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
61407 return columnName(
61408 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
61410 #ifndef SQLITE_OMIT_UTF16
61411 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
61412 return columnName(
61413 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
61415 #endif /* SQLITE_OMIT_UTF16 */
61416 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
61419 /******************************* sqlite3_bind_ ***************************
61421 ** Routines used to attach values to wildcards in a compiled SQL statement.
61424 ** Unbind the value bound to variable i in virtual machine p. This is the
61425 ** the same as binding a NULL value to the column. If the "i" parameter is
61426 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
61428 ** A successful evaluation of this routine acquires the mutex on p.
61429 ** the mutex is released if any kind of error occurs.
61431 ** The error code stored in database p->db is overwritten with the return
61432 ** value in any case.
61434 static int vdbeUnbind(Vdbe *p, int i){
61435 Mem *pVar;
61436 if( vdbeSafetyNotNull(p) ){
61437 return SQLITE_MISUSE_BKPT;
61439 sqlite3_mutex_enter(p->db->mutex);
61440 if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
61441 sqlite3Error(p->db, SQLITE_MISUSE, 0);
61442 sqlite3_mutex_leave(p->db->mutex);
61443 sqlite3_log(SQLITE_MISUSE,
61444 "bind on a busy prepared statement: [%s]", p->zSql);
61445 return SQLITE_MISUSE_BKPT;
61447 if( i<1 || i>p->nVar ){
61448 sqlite3Error(p->db, SQLITE_RANGE, 0);
61449 sqlite3_mutex_leave(p->db->mutex);
61450 return SQLITE_RANGE;
61452 i--;
61453 pVar = &p->aVar[i];
61454 sqlite3VdbeMemRelease(pVar);
61455 pVar->flags = MEM_Null;
61456 sqlite3Error(p->db, SQLITE_OK, 0);
61458 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
61459 ** binding a new value to this variable invalidates the current query plan.
61461 ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
61462 ** parameter in the WHERE clause might influence the choice of query plan
61463 ** for a statement, then the statement will be automatically recompiled,
61464 ** as if there had been a schema change, on the first sqlite3_step() call
61465 ** following any change to the bindings of that parameter.
61467 if( p->isPrepareV2 &&
61468 ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
61470 p->expired = 1;
61472 return SQLITE_OK;
61476 ** Bind a text or BLOB value.
61478 static int bindText(
61479 sqlite3_stmt *pStmt, /* The statement to bind against */
61480 int i, /* Index of the parameter to bind */
61481 const void *zData, /* Pointer to the data to be bound */
61482 int nData, /* Number of bytes of data to be bound */
61483 void (*xDel)(void*), /* Destructor for the data */
61484 u8 encoding /* Encoding for the data */
61486 Vdbe *p = (Vdbe *)pStmt;
61487 Mem *pVar;
61488 int rc;
61490 rc = vdbeUnbind(p, i);
61491 if( rc==SQLITE_OK ){
61492 if( zData!=0 ){
61493 pVar = &p->aVar[i-1];
61494 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
61495 if( rc==SQLITE_OK && encoding!=0 ){
61496 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
61498 sqlite3Error(p->db, rc, 0);
61499 rc = sqlite3ApiExit(p->db, rc);
61501 sqlite3_mutex_leave(p->db->mutex);
61502 }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
61503 xDel((void*)zData);
61505 return rc;
61510 ** Bind a blob value to an SQL statement variable.
61512 SQLITE_API int sqlite3_bind_blob(
61513 sqlite3_stmt *pStmt,
61514 int i,
61515 const void *zData,
61516 int nData,
61517 void (*xDel)(void*)
61519 return bindText(pStmt, i, zData, nData, xDel, 0);
61521 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
61522 int rc;
61523 Vdbe *p = (Vdbe *)pStmt;
61524 rc = vdbeUnbind(p, i);
61525 if( rc==SQLITE_OK ){
61526 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
61527 sqlite3_mutex_leave(p->db->mutex);
61529 return rc;
61531 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
61532 return sqlite3_bind_int64(p, i, (i64)iValue);
61534 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
61535 int rc;
61536 Vdbe *p = (Vdbe *)pStmt;
61537 rc = vdbeUnbind(p, i);
61538 if( rc==SQLITE_OK ){
61539 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
61540 sqlite3_mutex_leave(p->db->mutex);
61542 return rc;
61544 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
61545 int rc;
61546 Vdbe *p = (Vdbe*)pStmt;
61547 rc = vdbeUnbind(p, i);
61548 if( rc==SQLITE_OK ){
61549 sqlite3_mutex_leave(p->db->mutex);
61551 return rc;
61553 SQLITE_API int sqlite3_bind_text(
61554 sqlite3_stmt *pStmt,
61555 int i,
61556 const char *zData,
61557 int nData,
61558 void (*xDel)(void*)
61560 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
61562 #ifndef SQLITE_OMIT_UTF16
61563 SQLITE_API int sqlite3_bind_text16(
61564 sqlite3_stmt *pStmt,
61565 int i,
61566 const void *zData,
61567 int nData,
61568 void (*xDel)(void*)
61570 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
61572 #endif /* SQLITE_OMIT_UTF16 */
61573 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
61574 int rc;
61575 switch( pValue->type ){
61576 case SQLITE_INTEGER: {
61577 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
61578 break;
61580 case SQLITE_FLOAT: {
61581 rc = sqlite3_bind_double(pStmt, i, pValue->r);
61582 break;
61584 case SQLITE_BLOB: {
61585 if( pValue->flags & MEM_Zero ){
61586 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
61587 }else{
61588 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
61590 break;
61592 case SQLITE_TEXT: {
61593 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
61594 pValue->enc);
61595 break;
61597 default: {
61598 rc = sqlite3_bind_null(pStmt, i);
61599 break;
61602 return rc;
61604 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
61605 int rc;
61606 Vdbe *p = (Vdbe *)pStmt;
61607 rc = vdbeUnbind(p, i);
61608 if( rc==SQLITE_OK ){
61609 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
61610 sqlite3_mutex_leave(p->db->mutex);
61612 return rc;
61616 ** Return the number of wildcards that can be potentially bound to.
61617 ** This routine is added to support DBD::SQLite.
61619 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
61620 Vdbe *p = (Vdbe*)pStmt;
61621 return p ? p->nVar : 0;
61625 ** Create a mapping from variable numbers to variable names
61626 ** in the Vdbe.azVar[] array, if such a mapping does not already
61627 ** exist.
61629 static void createVarMap(Vdbe *p){
61630 if( !p->okVar ){
61631 int j;
61632 Op *pOp;
61633 sqlite3_mutex_enter(p->db->mutex);
61634 /* The race condition here is harmless. If two threads call this
61635 ** routine on the same Vdbe at the same time, they both might end
61636 ** up initializing the Vdbe.azVar[] array. That is a little extra
61637 ** work but it results in the same answer.
61639 for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
61640 if( pOp->opcode==OP_Variable ){
61641 assert( pOp->p1>0 && pOp->p1<=p->nVar );
61642 p->azVar[pOp->p1-1] = pOp->p4.z;
61645 p->okVar = 1;
61646 sqlite3_mutex_leave(p->db->mutex);
61651 ** Return the name of a wildcard parameter. Return NULL if the index
61652 ** is out of range or if the wildcard is unnamed.
61654 ** The result is always UTF-8.
61656 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
61657 Vdbe *p = (Vdbe*)pStmt;
61658 if( p==0 || i<1 || i>p->nVar ){
61659 return 0;
61661 createVarMap(p);
61662 return p->azVar[i-1];
61666 ** Given a wildcard parameter name, return the index of the variable
61667 ** with that name. If there is no variable with the given name,
61668 ** return 0.
61670 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
61671 int i;
61672 if( p==0 ){
61673 return 0;
61675 createVarMap(p);
61676 if( zName ){
61677 for(i=0; i<p->nVar; i++){
61678 const char *z = p->azVar[i];
61679 if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
61680 return i+1;
61684 return 0;
61686 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
61687 return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
61691 ** Transfer all bindings from the first statement over to the second.
61693 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
61694 Vdbe *pFrom = (Vdbe*)pFromStmt;
61695 Vdbe *pTo = (Vdbe*)pToStmt;
61696 int i;
61697 assert( pTo->db==pFrom->db );
61698 assert( pTo->nVar==pFrom->nVar );
61699 sqlite3_mutex_enter(pTo->db->mutex);
61700 for(i=0; i<pFrom->nVar; i++){
61701 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
61703 sqlite3_mutex_leave(pTo->db->mutex);
61704 return SQLITE_OK;
61707 #ifndef SQLITE_OMIT_DEPRECATED
61709 ** Deprecated external interface. Internal/core SQLite code
61710 ** should call sqlite3TransferBindings.
61712 ** Is is misuse to call this routine with statements from different
61713 ** database connections. But as this is a deprecated interface, we
61714 ** will not bother to check for that condition.
61716 ** If the two statements contain a different number of bindings, then
61717 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
61718 ** SQLITE_OK is returned.
61720 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
61721 Vdbe *pFrom = (Vdbe*)pFromStmt;
61722 Vdbe *pTo = (Vdbe*)pToStmt;
61723 if( pFrom->nVar!=pTo->nVar ){
61724 return SQLITE_ERROR;
61726 if( pTo->isPrepareV2 && pTo->expmask ){
61727 pTo->expired = 1;
61729 if( pFrom->isPrepareV2 && pFrom->expmask ){
61730 pFrom->expired = 1;
61732 return sqlite3TransferBindings(pFromStmt, pToStmt);
61734 #endif
61737 ** Return the sqlite3* database handle to which the prepared statement given
61738 ** in the argument belongs. This is the same database handle that was
61739 ** the first argument to the sqlite3_prepare() that was used to create
61740 ** the statement in the first place.
61742 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
61743 return pStmt ? ((Vdbe*)pStmt)->db : 0;
61747 ** Return true if the prepared statement is guaranteed to not modify the
61748 ** database.
61750 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
61751 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
61755 ** Return a pointer to the next prepared statement after pStmt associated
61756 ** with database connection pDb. If pStmt is NULL, return the first
61757 ** prepared statement for the database connection. Return NULL if there
61758 ** are no more.
61760 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
61761 sqlite3_stmt *pNext;
61762 sqlite3_mutex_enter(pDb->mutex);
61763 if( pStmt==0 ){
61764 pNext = (sqlite3_stmt*)pDb->pVdbe;
61765 }else{
61766 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
61768 sqlite3_mutex_leave(pDb->mutex);
61769 return pNext;
61773 ** Return the value of a status counter for a prepared statement
61775 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
61776 Vdbe *pVdbe = (Vdbe*)pStmt;
61777 int v = pVdbe->aCounter[op-1];
61778 if( resetFlag ) pVdbe->aCounter[op-1] = 0;
61779 return v;
61782 /************** End of vdbeapi.c *********************************************/
61783 /************** Begin file vdbetrace.c ***************************************/
61785 ** 2009 November 25
61787 ** The author disclaims copyright to this source code. In place of
61788 ** a legal notice, here is a blessing:
61790 ** May you do good and not evil.
61791 ** May you find forgiveness for yourself and forgive others.
61792 ** May you share freely, never taking more than you give.
61794 *************************************************************************
61796 ** This file contains code used to insert the values of host parameters
61797 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
61800 #ifndef SQLITE_OMIT_TRACE
61803 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
61804 ** bytes in this text up to but excluding the first character in
61805 ** a host parameter. If the text contains no host parameters, return
61806 ** the total number of bytes in the text.
61808 static int findNextHostParameter(const char *zSql, int *pnToken){
61809 int tokenType;
61810 int nTotal = 0;
61811 int n;
61813 *pnToken = 0;
61814 while( zSql[0] ){
61815 n = sqlite3GetToken((u8*)zSql, &tokenType);
61816 assert( n>0 && tokenType!=TK_ILLEGAL );
61817 if( tokenType==TK_VARIABLE ){
61818 *pnToken = n;
61819 break;
61821 nTotal += n;
61822 zSql += n;
61824 return nTotal;
61828 ** This function returns a pointer to a nul-terminated string in memory
61829 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
61830 ** string contains a copy of zRawSql but with host parameters expanded to
61831 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
61832 ** then the returned string holds a copy of zRawSql with "-- " prepended
61833 ** to each line of text.
61835 ** The calling function is responsible for making sure the memory returned
61836 ** is eventually freed.
61838 ** ALGORITHM: Scan the input string looking for host parameters in any of
61839 ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
61840 ** string literals, quoted identifier names, and comments. For text forms,
61841 ** the host parameter index is found by scanning the perpared
61842 ** statement for the corresponding OP_Variable opcode. Once the host
61843 ** parameter index is known, locate the value in p->aVar[]. Then render
61844 ** the value as a literal in place of the host parameter name.
61846 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
61847 Vdbe *p, /* The prepared statement being evaluated */
61848 const char *zRawSql /* Raw text of the SQL statement */
61850 sqlite3 *db; /* The database connection */
61851 int idx = 0; /* Index of a host parameter */
61852 int nextIndex = 1; /* Index of next ? host parameter */
61853 int n; /* Length of a token prefix */
61854 int nToken; /* Length of the parameter token */
61855 int i; /* Loop counter */
61856 Mem *pVar; /* Value of a host parameter */
61857 StrAccum out; /* Accumulate the output here */
61858 char zBase[100]; /* Initial working space */
61860 db = p->db;
61861 sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
61862 db->aLimit[SQLITE_LIMIT_LENGTH]);
61863 out.db = db;
61864 if( db->vdbeExecCnt>1 ){
61865 while( *zRawSql ){
61866 const char *zStart = zRawSql;
61867 while( *(zRawSql++)!='\n' && *zRawSql );
61868 sqlite3StrAccumAppend(&out, "-- ", 3);
61869 sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
61871 }else{
61872 while( zRawSql[0] ){
61873 n = findNextHostParameter(zRawSql, &nToken);
61874 assert( n>0 );
61875 sqlite3StrAccumAppend(&out, zRawSql, n);
61876 zRawSql += n;
61877 assert( zRawSql[0] || nToken==0 );
61878 if( nToken==0 ) break;
61879 if( zRawSql[0]=='?' ){
61880 if( nToken>1 ){
61881 assert( sqlite3Isdigit(zRawSql[1]) );
61882 sqlite3GetInt32(&zRawSql[1], &idx);
61883 }else{
61884 idx = nextIndex;
61886 }else{
61887 assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
61888 testcase( zRawSql[0]==':' );
61889 testcase( zRawSql[0]=='$' );
61890 testcase( zRawSql[0]=='@' );
61891 idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
61892 assert( idx>0 );
61894 zRawSql += nToken;
61895 nextIndex = idx + 1;
61896 assert( idx>0 && idx<=p->nVar );
61897 pVar = &p->aVar[idx-1];
61898 if( pVar->flags & MEM_Null ){
61899 sqlite3StrAccumAppend(&out, "NULL", 4);
61900 }else if( pVar->flags & MEM_Int ){
61901 sqlite3XPrintf(&out, "%lld", pVar->u.i);
61902 }else if( pVar->flags & MEM_Real ){
61903 sqlite3XPrintf(&out, "%!.15g", pVar->r);
61904 }else if( pVar->flags & MEM_Str ){
61905 #ifndef SQLITE_OMIT_UTF16
61906 u8 enc = ENC(db);
61907 if( enc!=SQLITE_UTF8 ){
61908 Mem utf8;
61909 memset(&utf8, 0, sizeof(utf8));
61910 utf8.db = db;
61911 sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
61912 sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
61913 sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
61914 sqlite3VdbeMemRelease(&utf8);
61915 }else
61916 #endif
61918 sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
61920 }else if( pVar->flags & MEM_Zero ){
61921 sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
61922 }else{
61923 assert( pVar->flags & MEM_Blob );
61924 sqlite3StrAccumAppend(&out, "x'", 2);
61925 for(i=0; i<pVar->n; i++){
61926 sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
61928 sqlite3StrAccumAppend(&out, "'", 1);
61932 return sqlite3StrAccumFinish(&out);
61935 #endif /* #ifndef SQLITE_OMIT_TRACE */
61937 /************** End of vdbetrace.c *******************************************/
61938 /************** Begin file vdbe.c ********************************************/
61940 ** 2001 September 15
61942 ** The author disclaims copyright to this source code. In place of
61943 ** a legal notice, here is a blessing:
61945 ** May you do good and not evil.
61946 ** May you find forgiveness for yourself and forgive others.
61947 ** May you share freely, never taking more than you give.
61949 *************************************************************************
61950 ** The code in this file implements execution method of the
61951 ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
61952 ** handles housekeeping details such as creating and deleting
61953 ** VDBE instances. This file is solely interested in executing
61954 ** the VDBE program.
61956 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
61957 ** to a VDBE.
61959 ** The SQL parser generates a program which is then executed by
61960 ** the VDBE to do the work of the SQL statement. VDBE programs are
61961 ** similar in form to assembly language. The program consists of
61962 ** a linear sequence of operations. Each operation has an opcode
61963 ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
61964 ** is a null-terminated string. Operand P5 is an unsigned character.
61965 ** Few opcodes use all 5 operands.
61967 ** Computation results are stored on a set of registers numbered beginning
61968 ** with 1 and going up to Vdbe.nMem. Each register can store
61969 ** either an integer, a null-terminated string, a floating point
61970 ** number, or the SQL "NULL" value. An implicit conversion from one
61971 ** type to the other occurs as necessary.
61973 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
61974 ** function which does the work of interpreting a VDBE program.
61975 ** But other routines are also provided to help in building up
61976 ** a program instruction by instruction.
61978 ** Various scripts scan this source file in order to generate HTML
61979 ** documentation, headers files, or other derived files. The formatting
61980 ** of the code in this file is, therefore, important. See other comments
61981 ** in this file for details. If in doubt, do not deviate from existing
61982 ** commenting and indentation practices when changing or adding code.
61986 ** Invoke this macro on memory cells just prior to changing the
61987 ** value of the cell. This macro verifies that shallow copies are
61988 ** not misused.
61990 #ifdef SQLITE_DEBUG
61991 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
61992 #else
61993 # define memAboutToChange(P,M)
61994 #endif
61997 ** The following global variable is incremented every time a cursor
61998 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
61999 ** procedures use this information to make sure that indices are
62000 ** working correctly. This variable has no function other than to
62001 ** help verify the correct operation of the library.
62003 #ifdef SQLITE_TEST
62004 SQLITE_API int sqlite3_search_count = 0;
62005 #endif
62008 ** When this global variable is positive, it gets decremented once before
62009 ** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
62010 ** field of the sqlite3 structure is set in order to simulate and interrupt.
62012 ** This facility is used for testing purposes only. It does not function
62013 ** in an ordinary build.
62015 #ifdef SQLITE_TEST
62016 SQLITE_API int sqlite3_interrupt_count = 0;
62017 #endif
62020 ** The next global variable is incremented each type the OP_Sort opcode
62021 ** is executed. The test procedures use this information to make sure that
62022 ** sorting is occurring or not occurring at appropriate times. This variable
62023 ** has no function other than to help verify the correct operation of the
62024 ** library.
62026 #ifdef SQLITE_TEST
62027 SQLITE_API int sqlite3_sort_count = 0;
62028 #endif
62031 ** The next global variable records the size of the largest MEM_Blob
62032 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
62033 ** use this information to make sure that the zero-blob functionality
62034 ** is working correctly. This variable has no function other than to
62035 ** help verify the correct operation of the library.
62037 #ifdef SQLITE_TEST
62038 SQLITE_API int sqlite3_max_blobsize = 0;
62039 static void updateMaxBlobsize(Mem *p){
62040 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
62041 sqlite3_max_blobsize = p->n;
62044 #endif
62047 ** The next global variable is incremented each type the OP_Found opcode
62048 ** is executed. This is used to test whether or not the foreign key
62049 ** operation implemented using OP_FkIsZero is working. This variable
62050 ** has no function other than to help verify the correct operation of the
62051 ** library.
62053 #ifdef SQLITE_TEST
62054 SQLITE_API int sqlite3_found_count = 0;
62055 #endif
62058 ** Test a register to see if it exceeds the current maximum blob size.
62059 ** If it does, record the new maximum blob size.
62061 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
62062 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
62063 #else
62064 # define UPDATE_MAX_BLOBSIZE(P)
62065 #endif
62068 ** Convert the given register into a string if it isn't one
62069 ** already. Return non-zero if a malloc() fails.
62071 #define Stringify(P, enc) \
62072 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
62073 { goto no_mem; }
62076 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
62077 ** a pointer to a dynamically allocated string where some other entity
62078 ** is responsible for deallocating that string. Because the register
62079 ** does not control the string, it might be deleted without the register
62080 ** knowing it.
62082 ** This routine converts an ephemeral string into a dynamically allocated
62083 ** string that the register itself controls. In other words, it
62084 ** converts an MEM_Ephem string into an MEM_Dyn string.
62086 #define Deephemeralize(P) \
62087 if( ((P)->flags&MEM_Ephem)!=0 \
62088 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
62091 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
62092 ** P if required.
62094 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
62097 ** Argument pMem points at a register that will be passed to a
62098 ** user-defined function or returned to the user as the result of a query.
62099 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
62100 ** routines.
62102 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
62103 int flags = pMem->flags;
62104 if( flags & MEM_Null ){
62105 pMem->type = SQLITE_NULL;
62107 else if( flags & MEM_Int ){
62108 pMem->type = SQLITE_INTEGER;
62110 else if( flags & MEM_Real ){
62111 pMem->type = SQLITE_FLOAT;
62113 else if( flags & MEM_Str ){
62114 pMem->type = SQLITE_TEXT;
62115 }else{
62116 pMem->type = SQLITE_BLOB;
62121 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
62122 ** if we run out of memory.
62124 static VdbeCursor *allocateCursor(
62125 Vdbe *p, /* The virtual machine */
62126 int iCur, /* Index of the new VdbeCursor */
62127 int nField, /* Number of fields in the table or index */
62128 int iDb, /* When database the cursor belongs to, or -1 */
62129 int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
62131 /* Find the memory cell that will be used to store the blob of memory
62132 ** required for this VdbeCursor structure. It is convenient to use a
62133 ** vdbe memory cell to manage the memory allocation required for a
62134 ** VdbeCursor structure for the following reasons:
62136 ** * Sometimes cursor numbers are used for a couple of different
62137 ** purposes in a vdbe program. The different uses might require
62138 ** different sized allocations. Memory cells provide growable
62139 ** allocations.
62141 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
62142 ** be freed lazily via the sqlite3_release_memory() API. This
62143 ** minimizes the number of malloc calls made by the system.
62145 ** Memory cells for cursors are allocated at the top of the address
62146 ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
62147 ** cursor 1 is managed by memory cell (p->nMem-1), etc.
62149 Mem *pMem = &p->aMem[p->nMem-iCur];
62151 int nByte;
62152 VdbeCursor *pCx = 0;
62153 nByte =
62154 ROUND8(sizeof(VdbeCursor)) +
62155 (isBtreeCursor?sqlite3BtreeCursorSize():0) +
62156 2*nField*sizeof(u32);
62158 assert( iCur<p->nCursor );
62159 if( p->apCsr[iCur] ){
62160 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
62161 p->apCsr[iCur] = 0;
62163 if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
62164 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
62165 memset(pCx, 0, sizeof(VdbeCursor));
62166 pCx->iDb = iDb;
62167 pCx->nField = nField;
62168 if( nField ){
62169 pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
62171 if( isBtreeCursor ){
62172 pCx->pCursor = (BtCursor*)
62173 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
62174 sqlite3BtreeCursorZero(pCx->pCursor);
62177 return pCx;
62181 ** Try to convert a value into a numeric representation if we can
62182 ** do so without loss of information. In other words, if the string
62183 ** looks like a number, convert it into a number. If it does not
62184 ** look like a number, leave it alone.
62186 static void applyNumericAffinity(Mem *pRec){
62187 if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
62188 double rValue;
62189 i64 iValue;
62190 u8 enc = pRec->enc;
62191 if( (pRec->flags&MEM_Str)==0 ) return;
62192 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
62193 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
62194 pRec->u.i = iValue;
62195 pRec->flags |= MEM_Int;
62196 }else{
62197 pRec->r = rValue;
62198 pRec->flags |= MEM_Real;
62204 ** Processing is determine by the affinity parameter:
62206 ** SQLITE_AFF_INTEGER:
62207 ** SQLITE_AFF_REAL:
62208 ** SQLITE_AFF_NUMERIC:
62209 ** Try to convert pRec to an integer representation or a
62210 ** floating-point representation if an integer representation
62211 ** is not possible. Note that the integer representation is
62212 ** always preferred, even if the affinity is REAL, because
62213 ** an integer representation is more space efficient on disk.
62215 ** SQLITE_AFF_TEXT:
62216 ** Convert pRec to a text representation.
62218 ** SQLITE_AFF_NONE:
62219 ** No-op. pRec is unchanged.
62221 static void applyAffinity(
62222 Mem *pRec, /* The value to apply affinity to */
62223 char affinity, /* The affinity to be applied */
62224 u8 enc /* Use this text encoding */
62226 if( affinity==SQLITE_AFF_TEXT ){
62227 /* Only attempt the conversion to TEXT if there is an integer or real
62228 ** representation (blob and NULL do not get converted) but no string
62229 ** representation.
62231 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
62232 sqlite3VdbeMemStringify(pRec, enc);
62234 pRec->flags &= ~(MEM_Real|MEM_Int);
62235 }else if( affinity!=SQLITE_AFF_NONE ){
62236 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
62237 || affinity==SQLITE_AFF_NUMERIC );
62238 applyNumericAffinity(pRec);
62239 if( pRec->flags & MEM_Real ){
62240 sqlite3VdbeIntegerAffinity(pRec);
62246 ** Try to convert the type of a function argument or a result column
62247 ** into a numeric representation. Use either INTEGER or REAL whichever
62248 ** is appropriate. But only do the conversion if it is possible without
62249 ** loss of information and return the revised type of the argument.
62251 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
62252 Mem *pMem = (Mem*)pVal;
62253 if( pMem->type==SQLITE_TEXT ){
62254 applyNumericAffinity(pMem);
62255 sqlite3VdbeMemStoreType(pMem);
62257 return pMem->type;
62261 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
62262 ** not the internal Mem* type.
62264 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
62265 sqlite3_value *pVal,
62266 u8 affinity,
62267 u8 enc
62269 applyAffinity((Mem *)pVal, affinity, enc);
62272 #ifdef SQLITE_DEBUG
62274 ** Write a nice string representation of the contents of cell pMem
62275 ** into buffer zBuf, length nBuf.
62277 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
62278 char *zCsr = zBuf;
62279 int f = pMem->flags;
62281 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
62283 if( f&MEM_Blob ){
62284 int i;
62285 char c;
62286 if( f & MEM_Dyn ){
62287 c = 'z';
62288 assert( (f & (MEM_Static|MEM_Ephem))==0 );
62289 }else if( f & MEM_Static ){
62290 c = 't';
62291 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62292 }else if( f & MEM_Ephem ){
62293 c = 'e';
62294 assert( (f & (MEM_Static|MEM_Dyn))==0 );
62295 }else{
62296 c = 's';
62299 sqlite3_snprintf(100, zCsr, "%c", c);
62300 zCsr += sqlite3Strlen30(zCsr);
62301 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
62302 zCsr += sqlite3Strlen30(zCsr);
62303 for(i=0; i<16 && i<pMem->n; i++){
62304 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
62305 zCsr += sqlite3Strlen30(zCsr);
62307 for(i=0; i<16 && i<pMem->n; i++){
62308 char z = pMem->z[i];
62309 if( z<32 || z>126 ) *zCsr++ = '.';
62310 else *zCsr++ = z;
62313 sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
62314 zCsr += sqlite3Strlen30(zCsr);
62315 if( f & MEM_Zero ){
62316 sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
62317 zCsr += sqlite3Strlen30(zCsr);
62319 *zCsr = '\0';
62320 }else if( f & MEM_Str ){
62321 int j, k;
62322 zBuf[0] = ' ';
62323 if( f & MEM_Dyn ){
62324 zBuf[1] = 'z';
62325 assert( (f & (MEM_Static|MEM_Ephem))==0 );
62326 }else if( f & MEM_Static ){
62327 zBuf[1] = 't';
62328 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62329 }else if( f & MEM_Ephem ){
62330 zBuf[1] = 'e';
62331 assert( (f & (MEM_Static|MEM_Dyn))==0 );
62332 }else{
62333 zBuf[1] = 's';
62335 k = 2;
62336 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
62337 k += sqlite3Strlen30(&zBuf[k]);
62338 zBuf[k++] = '[';
62339 for(j=0; j<15 && j<pMem->n; j++){
62340 u8 c = pMem->z[j];
62341 if( c>=0x20 && c<0x7f ){
62342 zBuf[k++] = c;
62343 }else{
62344 zBuf[k++] = '.';
62347 zBuf[k++] = ']';
62348 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
62349 k += sqlite3Strlen30(&zBuf[k]);
62350 zBuf[k++] = 0;
62353 #endif
62355 #ifdef SQLITE_DEBUG
62357 ** Print the value of a register for tracing purposes:
62359 static void memTracePrint(FILE *out, Mem *p){
62360 if( p->flags & MEM_Null ){
62361 fprintf(out, " NULL");
62362 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
62363 fprintf(out, " si:%lld", p->u.i);
62364 }else if( p->flags & MEM_Int ){
62365 fprintf(out, " i:%lld", p->u.i);
62366 #ifndef SQLITE_OMIT_FLOATING_POINT
62367 }else if( p->flags & MEM_Real ){
62368 fprintf(out, " r:%g", p->r);
62369 #endif
62370 }else if( p->flags & MEM_RowSet ){
62371 fprintf(out, " (rowset)");
62372 }else{
62373 char zBuf[200];
62374 sqlite3VdbeMemPrettyPrint(p, zBuf);
62375 fprintf(out, " ");
62376 fprintf(out, "%s", zBuf);
62379 static void registerTrace(FILE *out, int iReg, Mem *p){
62380 fprintf(out, "REG[%d] = ", iReg);
62381 memTracePrint(out, p);
62382 fprintf(out, "\n");
62384 #endif
62386 #ifdef SQLITE_DEBUG
62387 # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
62388 #else
62389 # define REGISTER_TRACE(R,M)
62390 #endif
62393 #ifdef VDBE_PROFILE
62396 ** hwtime.h contains inline assembler code for implementing
62397 ** high-performance timing routines.
62399 /************** Include hwtime.h in the middle of vdbe.c *********************/
62400 /************** Begin file hwtime.h ******************************************/
62402 ** 2008 May 27
62404 ** The author disclaims copyright to this source code. In place of
62405 ** a legal notice, here is a blessing:
62407 ** May you do good and not evil.
62408 ** May you find forgiveness for yourself and forgive others.
62409 ** May you share freely, never taking more than you give.
62411 ******************************************************************************
62413 ** This file contains inline asm code for retrieving "high-performance"
62414 ** counters for x86 class CPUs.
62416 #ifndef _HWTIME_H_
62417 #define _HWTIME_H_
62420 ** The following routine only works on pentium-class (or newer) processors.
62421 ** It uses the RDTSC opcode to read the cycle count value out of the
62422 ** processor and returns that value. This can be used for high-res
62423 ** profiling.
62425 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
62426 (defined(i386) || defined(__i386__) || defined(_M_IX86))
62428 #if defined(__GNUC__)
62430 __inline__ sqlite_uint64 sqlite3Hwtime(void){
62431 unsigned int lo, hi;
62432 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
62433 return (sqlite_uint64)hi << 32 | lo;
62436 #elif defined(_MSC_VER)
62438 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
62439 __asm {
62440 rdtsc
62441 ret ; return value at EDX:EAX
62445 #endif
62447 #elif (defined(__GNUC__) && defined(__x86_64__))
62449 __inline__ sqlite_uint64 sqlite3Hwtime(void){
62450 unsigned long val;
62451 __asm__ __volatile__ ("rdtsc" : "=A" (val));
62452 return val;
62455 #elif (defined(__GNUC__) && defined(__ppc__))
62457 __inline__ sqlite_uint64 sqlite3Hwtime(void){
62458 unsigned long long retval;
62459 unsigned long junk;
62460 __asm__ __volatile__ ("\n\
62461 1: mftbu %1\n\
62462 mftb %L0\n\
62463 mftbu %0\n\
62464 cmpw %0,%1\n\
62465 bne 1b"
62466 : "=r" (retval), "=r" (junk));
62467 return retval;
62470 #else
62472 #error Need implementation of sqlite3Hwtime() for your platform.
62475 ** To compile without implementing sqlite3Hwtime() for your platform,
62476 ** you can remove the above #error and use the following
62477 ** stub function. You will lose timing support for many
62478 ** of the debugging and testing utilities, but it should at
62479 ** least compile and run.
62481 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
62483 #endif
62485 #endif /* !defined(_HWTIME_H_) */
62487 /************** End of hwtime.h **********************************************/
62488 /************** Continuing where we left off in vdbe.c ***********************/
62490 #endif
62493 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
62494 ** sqlite3_interrupt() routine has been called. If it has been, then
62495 ** processing of the VDBE program is interrupted.
62497 ** This macro added to every instruction that does a jump in order to
62498 ** implement a loop. This test used to be on every single instruction,
62499 ** but that meant we more testing that we needed. By only testing the
62500 ** flag on jump instructions, we get a (small) speed improvement.
62502 #define CHECK_FOR_INTERRUPT \
62503 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
62506 #ifndef NDEBUG
62508 ** This function is only called from within an assert() expression. It
62509 ** checks that the sqlite3.nTransaction variable is correctly set to
62510 ** the number of non-transaction savepoints currently in the
62511 ** linked list starting at sqlite3.pSavepoint.
62513 ** Usage:
62515 ** assert( checkSavepointCount(db) );
62517 static int checkSavepointCount(sqlite3 *db){
62518 int n = 0;
62519 Savepoint *p;
62520 for(p=db->pSavepoint; p; p=p->pNext) n++;
62521 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
62522 return 1;
62524 #endif
62527 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
62528 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
62529 ** in memory obtained from sqlite3DbMalloc).
62531 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
62532 sqlite3 *db = p->db;
62533 sqlite3DbFree(db, p->zErrMsg);
62534 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
62535 sqlite3_free(pVtab->zErrMsg);
62536 pVtab->zErrMsg = 0;
62541 ** Execute as much of a VDBE program as we can then return.
62543 ** sqlite3VdbeMakeReady() must be called before this routine in order to
62544 ** close the program with a final OP_Halt and to set up the callbacks
62545 ** and the error message pointer.
62547 ** Whenever a row or result data is available, this routine will either
62548 ** invoke the result callback (if there is one) or return with
62549 ** SQLITE_ROW.
62551 ** If an attempt is made to open a locked database, then this routine
62552 ** will either invoke the busy callback (if there is one) or it will
62553 ** return SQLITE_BUSY.
62555 ** If an error occurs, an error message is written to memory obtained
62556 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
62557 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
62559 ** If the callback ever returns non-zero, then the program exits
62560 ** immediately. There will be no error message but the p->rc field is
62561 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
62563 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
62564 ** routine to return SQLITE_ERROR.
62566 ** Other fatal errors return SQLITE_ERROR.
62568 ** After this routine has finished, sqlite3VdbeFinalize() should be
62569 ** used to clean up the mess that was left behind.
62571 SQLITE_PRIVATE int sqlite3VdbeExec(
62572 Vdbe *p /* The VDBE */
62574 int pc=0; /* The program counter */
62575 Op *aOp = p->aOp; /* Copy of p->aOp */
62576 Op *pOp; /* Current operation */
62577 int rc = SQLITE_OK; /* Value to return */
62578 sqlite3 *db = p->db; /* The database */
62579 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
62580 u8 encoding = ENC(db); /* The database encoding */
62581 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62582 int checkProgress; /* True if progress callbacks are enabled */
62583 int nProgressOps = 0; /* Opcodes executed since progress callback. */
62584 #endif
62585 Mem *aMem = p->aMem; /* Copy of p->aMem */
62586 Mem *pIn1 = 0; /* 1st input operand */
62587 Mem *pIn2 = 0; /* 2nd input operand */
62588 Mem *pIn3 = 0; /* 3rd input operand */
62589 Mem *pOut = 0; /* Output operand */
62590 int iCompare = 0; /* Result of last OP_Compare operation */
62591 int *aPermute = 0; /* Permutation of columns for OP_Compare */
62592 #ifdef VDBE_PROFILE
62593 u64 start; /* CPU clock count at start of opcode */
62594 int origPc; /* Program counter at start of opcode */
62595 #endif
62596 /********************************************************************
62597 ** Automatically generated code
62599 ** The following union is automatically generated by the
62600 ** vdbe-compress.tcl script. The purpose of this union is to
62601 ** reduce the amount of stack space required by this function.
62602 ** See comments in the vdbe-compress.tcl script for details.
62604 union vdbeExecUnion {
62605 struct OP_Yield_stack_vars {
62606 int pcDest;
62607 } aa;
62608 struct OP_Variable_stack_vars {
62609 Mem *pVar; /* Value being transferred */
62610 } ab;
62611 struct OP_Move_stack_vars {
62612 char *zMalloc; /* Holding variable for allocated memory */
62613 int n; /* Number of registers left to copy */
62614 int p1; /* Register to copy from */
62615 int p2; /* Register to copy to */
62616 } ac;
62617 struct OP_ResultRow_stack_vars {
62618 Mem *pMem;
62619 int i;
62620 } ad;
62621 struct OP_Concat_stack_vars {
62622 i64 nByte;
62623 } ae;
62624 struct OP_Remainder_stack_vars {
62625 int flags; /* Combined MEM_* flags from both inputs */
62626 i64 iA; /* Integer value of left operand */
62627 i64 iB; /* Integer value of right operand */
62628 double rA; /* Real value of left operand */
62629 double rB; /* Real value of right operand */
62630 } af;
62631 struct OP_Function_stack_vars {
62632 int i;
62633 Mem *pArg;
62634 sqlite3_context ctx;
62635 sqlite3_value **apVal;
62636 int n;
62637 } ag;
62638 struct OP_ShiftRight_stack_vars {
62639 i64 iA;
62640 u64 uA;
62641 i64 iB;
62642 u8 op;
62643 } ah;
62644 struct OP_Ge_stack_vars {
62645 int res; /* Result of the comparison of pIn1 against pIn3 */
62646 char affinity; /* Affinity to use for comparison */
62647 u16 flags1; /* Copy of initial value of pIn1->flags */
62648 u16 flags3; /* Copy of initial value of pIn3->flags */
62649 } ai;
62650 struct OP_Compare_stack_vars {
62651 int n;
62652 int i;
62653 int p1;
62654 int p2;
62655 const KeyInfo *pKeyInfo;
62656 int idx;
62657 CollSeq *pColl; /* Collating sequence to use on this term */
62658 int bRev; /* True for DESCENDING sort order */
62659 } aj;
62660 struct OP_Or_stack_vars {
62661 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62662 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62663 } ak;
62664 struct OP_IfNot_stack_vars {
62665 int c;
62666 } al;
62667 struct OP_Column_stack_vars {
62668 u32 payloadSize; /* Number of bytes in the record */
62669 i64 payloadSize64; /* Number of bytes in the record */
62670 int p1; /* P1 value of the opcode */
62671 int p2; /* column number to retrieve */
62672 VdbeCursor *pC; /* The VDBE cursor */
62673 char *zRec; /* Pointer to complete record-data */
62674 BtCursor *pCrsr; /* The BTree cursor */
62675 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
62676 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
62677 int nField; /* number of fields in the record */
62678 int len; /* The length of the serialized data for the column */
62679 int i; /* Loop counter */
62680 char *zData; /* Part of the record being decoded */
62681 Mem *pDest; /* Where to write the extracted value */
62682 Mem sMem; /* For storing the record being decoded */
62683 u8 *zIdx; /* Index into header */
62684 u8 *zEndHdr; /* Pointer to first byte after the header */
62685 u32 offset; /* Offset into the data */
62686 u32 szField; /* Number of bytes in the content of a field */
62687 int szHdr; /* Size of the header size field at start of record */
62688 int avail; /* Number of bytes of available data */
62689 Mem *pReg; /* PseudoTable input register */
62690 } am;
62691 struct OP_Affinity_stack_vars {
62692 const char *zAffinity; /* The affinity to be applied */
62693 char cAff; /* A single character of affinity */
62694 } an;
62695 struct OP_MakeRecord_stack_vars {
62696 u8 *zNewRecord; /* A buffer to hold the data for the new record */
62697 Mem *pRec; /* The new record */
62698 u64 nData; /* Number of bytes of data space */
62699 int nHdr; /* Number of bytes of header space */
62700 i64 nByte; /* Data space required for this record */
62701 int nZero; /* Number of zero bytes at the end of the record */
62702 int nVarint; /* Number of bytes in a varint */
62703 u32 serial_type; /* Type field */
62704 Mem *pData0; /* First field to be combined into the record */
62705 Mem *pLast; /* Last field of the record */
62706 int nField; /* Number of fields in the record */
62707 char *zAffinity; /* The affinity string for the record */
62708 int file_format; /* File format to use for encoding */
62709 int i; /* Space used in zNewRecord[] */
62710 int len; /* Length of a field */
62711 } ao;
62712 struct OP_Count_stack_vars {
62713 i64 nEntry;
62714 BtCursor *pCrsr;
62715 } ap;
62716 struct OP_Savepoint_stack_vars {
62717 int p1; /* Value of P1 operand */
62718 char *zName; /* Name of savepoint */
62719 int nName;
62720 Savepoint *pNew;
62721 Savepoint *pSavepoint;
62722 Savepoint *pTmp;
62723 int iSavepoint;
62724 int ii;
62725 } aq;
62726 struct OP_AutoCommit_stack_vars {
62727 int desiredAutoCommit;
62728 int iRollback;
62729 int turnOnAC;
62730 } ar;
62731 struct OP_Transaction_stack_vars {
62732 Btree *pBt;
62733 } as;
62734 struct OP_ReadCookie_stack_vars {
62735 int iMeta;
62736 int iDb;
62737 int iCookie;
62738 } at;
62739 struct OP_SetCookie_stack_vars {
62740 Db *pDb;
62741 } au;
62742 struct OP_VerifyCookie_stack_vars {
62743 int iMeta;
62744 int iGen;
62745 Btree *pBt;
62746 } av;
62747 struct OP_OpenWrite_stack_vars {
62748 int nField;
62749 KeyInfo *pKeyInfo;
62750 int p2;
62751 int iDb;
62752 int wrFlag;
62753 Btree *pX;
62754 VdbeCursor *pCur;
62755 Db *pDb;
62756 } aw;
62757 struct OP_OpenEphemeral_stack_vars {
62758 VdbeCursor *pCx;
62759 } ax;
62760 struct OP_OpenPseudo_stack_vars {
62761 VdbeCursor *pCx;
62762 } ay;
62763 struct OP_SeekGt_stack_vars {
62764 int res;
62765 int oc;
62766 VdbeCursor *pC;
62767 UnpackedRecord r;
62768 int nField;
62769 i64 iKey; /* The rowid we are to seek to */
62770 } az;
62771 struct OP_Seek_stack_vars {
62772 VdbeCursor *pC;
62773 } ba;
62774 struct OP_Found_stack_vars {
62775 int alreadyExists;
62776 VdbeCursor *pC;
62777 int res;
62778 UnpackedRecord *pIdxKey;
62779 UnpackedRecord r;
62780 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
62781 } bb;
62782 struct OP_IsUnique_stack_vars {
62783 u16 ii;
62784 VdbeCursor *pCx;
62785 BtCursor *pCrsr;
62786 u16 nField;
62787 Mem *aMx;
62788 UnpackedRecord r; /* B-Tree index search key */
62789 i64 R; /* Rowid stored in register P3 */
62790 } bc;
62791 struct OP_NotExists_stack_vars {
62792 VdbeCursor *pC;
62793 BtCursor *pCrsr;
62794 int res;
62795 u64 iKey;
62796 } bd;
62797 struct OP_NewRowid_stack_vars {
62798 i64 v; /* The new rowid */
62799 VdbeCursor *pC; /* Cursor of table to get the new rowid */
62800 int res; /* Result of an sqlite3BtreeLast() */
62801 int cnt; /* Counter to limit the number of searches */
62802 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
62803 VdbeFrame *pFrame; /* Root frame of VDBE */
62804 } be;
62805 struct OP_InsertInt_stack_vars {
62806 Mem *pData; /* MEM cell holding data for the record to be inserted */
62807 Mem *pKey; /* MEM cell holding key for the record */
62808 i64 iKey; /* The integer ROWID or key for the record to be inserted */
62809 VdbeCursor *pC; /* Cursor to table into which insert is written */
62810 int nZero; /* Number of zero-bytes to append */
62811 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
62812 const char *zDb; /* database name - used by the update hook */
62813 const char *zTbl; /* Table name - used by the opdate hook */
62814 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
62815 } bf;
62816 struct OP_Delete_stack_vars {
62817 i64 iKey;
62818 VdbeCursor *pC;
62819 } bg;
62820 struct OP_RowData_stack_vars {
62821 VdbeCursor *pC;
62822 BtCursor *pCrsr;
62823 u32 n;
62824 i64 n64;
62825 } bh;
62826 struct OP_Rowid_stack_vars {
62827 VdbeCursor *pC;
62828 i64 v;
62829 sqlite3_vtab *pVtab;
62830 const sqlite3_module *pModule;
62831 } bi;
62832 struct OP_NullRow_stack_vars {
62833 VdbeCursor *pC;
62834 } bj;
62835 struct OP_Last_stack_vars {
62836 VdbeCursor *pC;
62837 BtCursor *pCrsr;
62838 int res;
62839 } bk;
62840 struct OP_Rewind_stack_vars {
62841 VdbeCursor *pC;
62842 BtCursor *pCrsr;
62843 int res;
62844 } bl;
62845 struct OP_Next_stack_vars {
62846 VdbeCursor *pC;
62847 BtCursor *pCrsr;
62848 int res;
62849 } bm;
62850 struct OP_IdxInsert_stack_vars {
62851 VdbeCursor *pC;
62852 BtCursor *pCrsr;
62853 int nKey;
62854 const char *zKey;
62855 } bn;
62856 struct OP_IdxDelete_stack_vars {
62857 VdbeCursor *pC;
62858 BtCursor *pCrsr;
62859 int res;
62860 UnpackedRecord r;
62861 } bo;
62862 struct OP_IdxRowid_stack_vars {
62863 BtCursor *pCrsr;
62864 VdbeCursor *pC;
62865 i64 rowid;
62866 } bp;
62867 struct OP_IdxGE_stack_vars {
62868 VdbeCursor *pC;
62869 int res;
62870 UnpackedRecord r;
62871 } bq;
62872 struct OP_Destroy_stack_vars {
62873 int iMoved;
62874 int iCnt;
62875 Vdbe *pVdbe;
62876 int iDb;
62877 } br;
62878 struct OP_Clear_stack_vars {
62879 int nChange;
62880 } bs;
62881 struct OP_CreateTable_stack_vars {
62882 int pgno;
62883 int flags;
62884 Db *pDb;
62885 } bt;
62886 struct OP_ParseSchema_stack_vars {
62887 int iDb;
62888 const char *zMaster;
62889 char *zSql;
62890 InitData initData;
62891 } bu;
62892 struct OP_IntegrityCk_stack_vars {
62893 int nRoot; /* Number of tables to check. (Number of root pages.) */
62894 int *aRoot; /* Array of rootpage numbers for tables to be checked */
62895 int j; /* Loop counter */
62896 int nErr; /* Number of errors reported */
62897 char *z; /* Text of the error report */
62898 Mem *pnErr; /* Register keeping track of errors remaining */
62899 } bv;
62900 struct OP_RowSetRead_stack_vars {
62901 i64 val;
62902 } bw;
62903 struct OP_RowSetTest_stack_vars {
62904 int iSet;
62905 int exists;
62906 } bx;
62907 struct OP_Program_stack_vars {
62908 int nMem; /* Number of memory registers for sub-program */
62909 int nByte; /* Bytes of runtime space required for sub-program */
62910 Mem *pRt; /* Register to allocate runtime space */
62911 Mem *pMem; /* Used to iterate through memory cells */
62912 Mem *pEnd; /* Last memory cell in new array */
62913 VdbeFrame *pFrame; /* New vdbe frame to execute in */
62914 SubProgram *pProgram; /* Sub-program to execute */
62915 void *t; /* Token identifying trigger */
62916 } by;
62917 struct OP_Param_stack_vars {
62918 VdbeFrame *pFrame;
62919 Mem *pIn;
62920 } bz;
62921 struct OP_MemMax_stack_vars {
62922 Mem *pIn1;
62923 VdbeFrame *pFrame;
62924 } ca;
62925 struct OP_AggStep_stack_vars {
62926 int n;
62927 int i;
62928 Mem *pMem;
62929 Mem *pRec;
62930 sqlite3_context ctx;
62931 sqlite3_value **apVal;
62932 } cb;
62933 struct OP_AggFinal_stack_vars {
62934 Mem *pMem;
62935 } cc;
62936 struct OP_Checkpoint_stack_vars {
62937 int i; /* Loop counter */
62938 int aRes[3]; /* Results */
62939 Mem *pMem; /* Write results here */
62940 } cd;
62941 struct OP_JournalMode_stack_vars {
62942 Btree *pBt; /* Btree to change journal mode of */
62943 Pager *pPager; /* Pager associated with pBt */
62944 int eNew; /* New journal mode */
62945 int eOld; /* The old journal mode */
62946 const char *zFilename; /* Name of database file for pPager */
62947 } ce;
62948 struct OP_IncrVacuum_stack_vars {
62949 Btree *pBt;
62950 } cf;
62951 struct OP_VBegin_stack_vars {
62952 VTable *pVTab;
62953 } cg;
62954 struct OP_VOpen_stack_vars {
62955 VdbeCursor *pCur;
62956 sqlite3_vtab_cursor *pVtabCursor;
62957 sqlite3_vtab *pVtab;
62958 sqlite3_module *pModule;
62959 } ch;
62960 struct OP_VFilter_stack_vars {
62961 int nArg;
62962 int iQuery;
62963 const sqlite3_module *pModule;
62964 Mem *pQuery;
62965 Mem *pArgc;
62966 sqlite3_vtab_cursor *pVtabCursor;
62967 sqlite3_vtab *pVtab;
62968 VdbeCursor *pCur;
62969 int res;
62970 int i;
62971 Mem **apArg;
62972 } ci;
62973 struct OP_VColumn_stack_vars {
62974 sqlite3_vtab *pVtab;
62975 const sqlite3_module *pModule;
62976 Mem *pDest;
62977 sqlite3_context sContext;
62978 } cj;
62979 struct OP_VNext_stack_vars {
62980 sqlite3_vtab *pVtab;
62981 const sqlite3_module *pModule;
62982 int res;
62983 VdbeCursor *pCur;
62984 } ck;
62985 struct OP_VRename_stack_vars {
62986 sqlite3_vtab *pVtab;
62987 Mem *pName;
62988 } cl;
62989 struct OP_VUpdate_stack_vars {
62990 sqlite3_vtab *pVtab;
62991 sqlite3_module *pModule;
62992 int nArg;
62993 int i;
62994 sqlite_int64 rowid;
62995 Mem **apArg;
62996 Mem *pX;
62997 } cm;
62998 struct OP_Trace_stack_vars {
62999 char *zTrace;
63000 } cn;
63001 } u;
63002 /* End automatically generated code
63003 ********************************************************************/
63005 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
63006 sqlite3VdbeEnter(p);
63007 if( p->rc==SQLITE_NOMEM ){
63008 /* This happens if a malloc() inside a call to sqlite3_column_text() or
63009 ** sqlite3_column_text16() failed. */
63010 goto no_mem;
63012 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
63013 p->rc = SQLITE_OK;
63014 assert( p->explain==0 );
63015 p->pResultSet = 0;
63016 db->busyHandler.nBusy = 0;
63017 CHECK_FOR_INTERRUPT;
63018 sqlite3VdbeIOTraceSql(p);
63019 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
63020 checkProgress = db->xProgress!=0;
63021 #endif
63022 #ifdef SQLITE_DEBUG
63023 sqlite3BeginBenignMalloc();
63024 if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
63025 int i;
63026 printf("VDBE Program Listing:\n");
63027 sqlite3VdbePrintSql(p);
63028 for(i=0; i<p->nOp; i++){
63029 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
63032 sqlite3EndBenignMalloc();
63033 #endif
63034 for(pc=p->pc; rc==SQLITE_OK; pc++){
63035 assert( pc>=0 && pc<p->nOp );
63036 if( db->mallocFailed ) goto no_mem;
63037 #ifdef VDBE_PROFILE
63038 origPc = pc;
63039 start = sqlite3Hwtime();
63040 #endif
63041 pOp = &aOp[pc];
63043 /* Only allow tracing if SQLITE_DEBUG is defined.
63045 #ifdef SQLITE_DEBUG
63046 if( p->trace ){
63047 if( pc==0 ){
63048 printf("VDBE Execution Trace:\n");
63049 sqlite3VdbePrintSql(p);
63051 sqlite3VdbePrintOp(p->trace, pc, pOp);
63053 #endif
63056 /* Check to see if we need to simulate an interrupt. This only happens
63057 ** if we have a special test build.
63059 #ifdef SQLITE_TEST
63060 if( sqlite3_interrupt_count>0 ){
63061 sqlite3_interrupt_count--;
63062 if( sqlite3_interrupt_count==0 ){
63063 sqlite3_interrupt(db);
63066 #endif
63068 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
63069 /* Call the progress callback if it is configured and the required number
63070 ** of VDBE ops have been executed (either since this invocation of
63071 ** sqlite3VdbeExec() or since last time the progress callback was called).
63072 ** If the progress callback returns non-zero, exit the virtual machine with
63073 ** a return code SQLITE_ABORT.
63075 if( checkProgress ){
63076 if( db->nProgressOps==nProgressOps ){
63077 int prc;
63078 prc = db->xProgress(db->pProgressArg);
63079 if( prc!=0 ){
63080 rc = SQLITE_INTERRUPT;
63081 goto vdbe_error_halt;
63083 nProgressOps = 0;
63085 nProgressOps++;
63087 #endif
63089 /* On any opcode with the "out2-prerelase" tag, free any
63090 ** external allocations out of mem[p2] and set mem[p2] to be
63091 ** an undefined integer. Opcodes will either fill in the integer
63092 ** value or convert mem[p2] to a different type.
63094 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
63095 if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
63096 assert( pOp->p2>0 );
63097 assert( pOp->p2<=p->nMem );
63098 pOut = &aMem[pOp->p2];
63099 memAboutToChange(p, pOut);
63100 sqlite3VdbeMemReleaseExternal(pOut);
63101 pOut->flags = MEM_Int;
63104 /* Sanity checking on other operands */
63105 #ifdef SQLITE_DEBUG
63106 if( (pOp->opflags & OPFLG_IN1)!=0 ){
63107 assert( pOp->p1>0 );
63108 assert( pOp->p1<=p->nMem );
63109 assert( memIsValid(&aMem[pOp->p1]) );
63110 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
63112 if( (pOp->opflags & OPFLG_IN2)!=0 ){
63113 assert( pOp->p2>0 );
63114 assert( pOp->p2<=p->nMem );
63115 assert( memIsValid(&aMem[pOp->p2]) );
63116 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
63118 if( (pOp->opflags & OPFLG_IN3)!=0 ){
63119 assert( pOp->p3>0 );
63120 assert( pOp->p3<=p->nMem );
63121 assert( memIsValid(&aMem[pOp->p3]) );
63122 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
63124 if( (pOp->opflags & OPFLG_OUT2)!=0 ){
63125 assert( pOp->p2>0 );
63126 assert( pOp->p2<=p->nMem );
63127 memAboutToChange(p, &aMem[pOp->p2]);
63129 if( (pOp->opflags & OPFLG_OUT3)!=0 ){
63130 assert( pOp->p3>0 );
63131 assert( pOp->p3<=p->nMem );
63132 memAboutToChange(p, &aMem[pOp->p3]);
63134 #endif
63136 switch( pOp->opcode ){
63138 /*****************************************************************************
63139 ** What follows is a massive switch statement where each case implements a
63140 ** separate instruction in the virtual machine. If we follow the usual
63141 ** indentation conventions, each case should be indented by 6 spaces. But
63142 ** that is a lot of wasted space on the left margin. So the code within
63143 ** the switch statement will break with convention and be flush-left. Another
63144 ** big comment (similar to this one) will mark the point in the code where
63145 ** we transition back to normal indentation.
63147 ** The formatting of each case is important. The makefile for SQLite
63148 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
63149 ** file looking for lines that begin with "case OP_". The opcodes.h files
63150 ** will be filled with #defines that give unique integer values to each
63151 ** opcode and the opcodes.c file is filled with an array of strings where
63152 ** each string is the symbolic name for the corresponding opcode. If the
63153 ** case statement is followed by a comment of the form "/# same as ... #/"
63154 ** that comment is used to determine the particular value of the opcode.
63156 ** Other keywords in the comment that follows each case are used to
63157 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
63158 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
63159 ** the mkopcodeh.awk script for additional information.
63161 ** Documentation about VDBE opcodes is generated by scanning this file
63162 ** for lines of that contain "Opcode:". That line and all subsequent
63163 ** comment lines are used in the generation of the opcode.html documentation
63164 ** file.
63166 ** SUMMARY:
63168 ** Formatting is important to scripts that scan this file.
63169 ** Do not deviate from the formatting style currently in use.
63171 *****************************************************************************/
63173 /* Opcode: Goto * P2 * * *
63175 ** An unconditional jump to address P2.
63176 ** The next instruction executed will be
63177 ** the one at index P2 from the beginning of
63178 ** the program.
63180 case OP_Goto: { /* jump */
63181 CHECK_FOR_INTERRUPT;
63182 pc = pOp->p2 - 1;
63183 break;
63186 /* Opcode: Gosub P1 P2 * * *
63188 ** Write the current address onto register P1
63189 ** and then jump to address P2.
63191 case OP_Gosub: { /* jump, in1 */
63192 pIn1 = &aMem[pOp->p1];
63193 assert( (pIn1->flags & MEM_Dyn)==0 );
63194 memAboutToChange(p, pIn1);
63195 pIn1->flags = MEM_Int;
63196 pIn1->u.i = pc;
63197 REGISTER_TRACE(pOp->p1, pIn1);
63198 pc = pOp->p2 - 1;
63199 break;
63202 /* Opcode: Return P1 * * * *
63204 ** Jump to the next instruction after the address in register P1.
63206 case OP_Return: { /* in1 */
63207 pIn1 = &aMem[pOp->p1];
63208 assert( pIn1->flags & MEM_Int );
63209 pc = (int)pIn1->u.i;
63210 break;
63213 /* Opcode: Yield P1 * * * *
63215 ** Swap the program counter with the value in register P1.
63217 case OP_Yield: { /* in1 */
63218 #if 0 /* local variables moved into u.aa */
63219 int pcDest;
63220 #endif /* local variables moved into u.aa */
63221 pIn1 = &aMem[pOp->p1];
63222 assert( (pIn1->flags & MEM_Dyn)==0 );
63223 pIn1->flags = MEM_Int;
63224 u.aa.pcDest = (int)pIn1->u.i;
63225 pIn1->u.i = pc;
63226 REGISTER_TRACE(pOp->p1, pIn1);
63227 pc = u.aa.pcDest;
63228 break;
63231 /* Opcode: HaltIfNull P1 P2 P3 P4 *
63233 ** Check the value in register P3. If is is NULL then Halt using
63234 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
63235 ** value in register P3 is not NULL, then this routine is a no-op.
63237 case OP_HaltIfNull: { /* in3 */
63238 pIn3 = &aMem[pOp->p3];
63239 if( (pIn3->flags & MEM_Null)==0 ) break;
63240 /* Fall through into OP_Halt */
63243 /* Opcode: Halt P1 P2 * P4 *
63245 ** Exit immediately. All open cursors, etc are closed
63246 ** automatically.
63248 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
63249 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
63250 ** For errors, it can be some other value. If P1!=0 then P2 will determine
63251 ** whether or not to rollback the current transaction. Do not rollback
63252 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
63253 ** then back out all changes that have occurred during this execution of the
63254 ** VDBE, but do not rollback the transaction.
63256 ** If P4 is not null then it is an error message string.
63258 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
63259 ** every program. So a jump past the last instruction of the program
63260 ** is the same as executing Halt.
63262 case OP_Halt: {
63263 if( pOp->p1==SQLITE_OK && p->pFrame ){
63264 /* Halt the sub-program. Return control to the parent frame. */
63265 VdbeFrame *pFrame = p->pFrame;
63266 p->pFrame = pFrame->pParent;
63267 p->nFrame--;
63268 sqlite3VdbeSetChanges(db, p->nChange);
63269 pc = sqlite3VdbeFrameRestore(pFrame);
63270 if( pOp->p2==OE_Ignore ){
63271 /* Instruction pc is the OP_Program that invoked the sub-program
63272 ** currently being halted. If the p2 instruction of this OP_Halt
63273 ** instruction is set to OE_Ignore, then the sub-program is throwing
63274 ** an IGNORE exception. In this case jump to the address specified
63275 ** as the p2 of the calling OP_Program. */
63276 pc = p->aOp[pc].p2-1;
63278 aOp = p->aOp;
63279 aMem = p->aMem;
63280 break;
63283 p->rc = pOp->p1;
63284 p->errorAction = (u8)pOp->p2;
63285 p->pc = pc;
63286 if( pOp->p4.z ){
63287 assert( p->rc!=SQLITE_OK );
63288 sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
63289 testcase( sqlite3GlobalConfig.xLog!=0 );
63290 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
63291 }else if( p->rc ){
63292 testcase( sqlite3GlobalConfig.xLog!=0 );
63293 sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
63295 rc = sqlite3VdbeHalt(p);
63296 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
63297 if( rc==SQLITE_BUSY ){
63298 p->rc = rc = SQLITE_BUSY;
63299 }else{
63300 assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
63301 assert( rc==SQLITE_OK || db->nDeferredCons>0 );
63302 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
63304 goto vdbe_return;
63307 /* Opcode: Integer P1 P2 * * *
63309 ** The 32-bit integer value P1 is written into register P2.
63311 case OP_Integer: { /* out2-prerelease */
63312 pOut->u.i = pOp->p1;
63313 break;
63316 /* Opcode: Int64 * P2 * P4 *
63318 ** P4 is a pointer to a 64-bit integer value.
63319 ** Write that value into register P2.
63321 case OP_Int64: { /* out2-prerelease */
63322 assert( pOp->p4.pI64!=0 );
63323 pOut->u.i = *pOp->p4.pI64;
63324 break;
63327 #ifndef SQLITE_OMIT_FLOATING_POINT
63328 /* Opcode: Real * P2 * P4 *
63330 ** P4 is a pointer to a 64-bit floating point value.
63331 ** Write that value into register P2.
63333 case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
63334 pOut->flags = MEM_Real;
63335 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
63336 pOut->r = *pOp->p4.pReal;
63337 break;
63339 #endif
63341 /* Opcode: String8 * P2 * P4 *
63343 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
63344 ** into an OP_String before it is executed for the first time.
63346 case OP_String8: { /* same as TK_STRING, out2-prerelease */
63347 assert( pOp->p4.z!=0 );
63348 pOp->opcode = OP_String;
63349 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
63351 #ifndef SQLITE_OMIT_UTF16
63352 if( encoding!=SQLITE_UTF8 ){
63353 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
63354 if( rc==SQLITE_TOOBIG ) goto too_big;
63355 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
63356 assert( pOut->zMalloc==pOut->z );
63357 assert( pOut->flags & MEM_Dyn );
63358 pOut->zMalloc = 0;
63359 pOut->flags |= MEM_Static;
63360 pOut->flags &= ~MEM_Dyn;
63361 if( pOp->p4type==P4_DYNAMIC ){
63362 sqlite3DbFree(db, pOp->p4.z);
63364 pOp->p4type = P4_DYNAMIC;
63365 pOp->p4.z = pOut->z;
63366 pOp->p1 = pOut->n;
63368 #endif
63369 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63370 goto too_big;
63372 /* Fall through to the next case, OP_String */
63375 /* Opcode: String P1 P2 * P4 *
63377 ** The string value P4 of length P1 (bytes) is stored in register P2.
63379 case OP_String: { /* out2-prerelease */
63380 assert( pOp->p4.z!=0 );
63381 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
63382 pOut->z = pOp->p4.z;
63383 pOut->n = pOp->p1;
63384 pOut->enc = encoding;
63385 UPDATE_MAX_BLOBSIZE(pOut);
63386 break;
63389 /* Opcode: Null * P2 * * *
63391 ** Write a NULL into register P2.
63393 case OP_Null: { /* out2-prerelease */
63394 pOut->flags = MEM_Null;
63395 break;
63399 /* Opcode: Blob P1 P2 * P4
63401 ** P4 points to a blob of data P1 bytes long. Store this
63402 ** blob in register P2.
63404 case OP_Blob: { /* out2-prerelease */
63405 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
63406 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
63407 pOut->enc = encoding;
63408 UPDATE_MAX_BLOBSIZE(pOut);
63409 break;
63412 /* Opcode: Variable P1 P2 * P4 *
63414 ** Transfer the values of bound parameter P1 into register P2
63416 ** If the parameter is named, then its name appears in P4 and P3==1.
63417 ** The P4 value is used by sqlite3_bind_parameter_name().
63419 case OP_Variable: { /* out2-prerelease */
63420 #if 0 /* local variables moved into u.ab */
63421 Mem *pVar; /* Value being transferred */
63422 #endif /* local variables moved into u.ab */
63424 assert( pOp->p1>0 && pOp->p1<=p->nVar );
63425 u.ab.pVar = &p->aVar[pOp->p1 - 1];
63426 if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
63427 goto too_big;
63429 sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
63430 UPDATE_MAX_BLOBSIZE(pOut);
63431 break;
63434 /* Opcode: Move P1 P2 P3 * *
63436 ** Move the values in register P1..P1+P3-1 over into
63437 ** registers P2..P2+P3-1. Registers P1..P1+P1-1 are
63438 ** left holding a NULL. It is an error for register ranges
63439 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
63441 case OP_Move: {
63442 #if 0 /* local variables moved into u.ac */
63443 char *zMalloc; /* Holding variable for allocated memory */
63444 int n; /* Number of registers left to copy */
63445 int p1; /* Register to copy from */
63446 int p2; /* Register to copy to */
63447 #endif /* local variables moved into u.ac */
63449 u.ac.n = pOp->p3;
63450 u.ac.p1 = pOp->p1;
63451 u.ac.p2 = pOp->p2;
63452 assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
63453 assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
63455 pIn1 = &aMem[u.ac.p1];
63456 pOut = &aMem[u.ac.p2];
63457 while( u.ac.n-- ){
63458 assert( pOut<=&aMem[p->nMem] );
63459 assert( pIn1<=&aMem[p->nMem] );
63460 assert( memIsValid(pIn1) );
63461 memAboutToChange(p, pOut);
63462 u.ac.zMalloc = pOut->zMalloc;
63463 pOut->zMalloc = 0;
63464 sqlite3VdbeMemMove(pOut, pIn1);
63465 pIn1->zMalloc = u.ac.zMalloc;
63466 REGISTER_TRACE(u.ac.p2++, pOut);
63467 pIn1++;
63468 pOut++;
63470 break;
63473 /* Opcode: Copy P1 P2 * * *
63475 ** Make a copy of register P1 into register P2.
63477 ** This instruction makes a deep copy of the value. A duplicate
63478 ** is made of any string or blob constant. See also OP_SCopy.
63480 case OP_Copy: { /* in1, out2 */
63481 pIn1 = &aMem[pOp->p1];
63482 pOut = &aMem[pOp->p2];
63483 assert( pOut!=pIn1 );
63484 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63485 Deephemeralize(pOut);
63486 REGISTER_TRACE(pOp->p2, pOut);
63487 break;
63490 /* Opcode: SCopy P1 P2 * * *
63492 ** Make a shallow copy of register P1 into register P2.
63494 ** This instruction makes a shallow copy of the value. If the value
63495 ** is a string or blob, then the copy is only a pointer to the
63496 ** original and hence if the original changes so will the copy.
63497 ** Worse, if the original is deallocated, the copy becomes invalid.
63498 ** Thus the program must guarantee that the original will not change
63499 ** during the lifetime of the copy. Use OP_Copy to make a complete
63500 ** copy.
63502 case OP_SCopy: { /* in1, out2 */
63503 pIn1 = &aMem[pOp->p1];
63504 pOut = &aMem[pOp->p2];
63505 assert( pOut!=pIn1 );
63506 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63507 #ifdef SQLITE_DEBUG
63508 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
63509 #endif
63510 REGISTER_TRACE(pOp->p2, pOut);
63511 break;
63514 /* Opcode: ResultRow P1 P2 * * *
63516 ** The registers P1 through P1+P2-1 contain a single row of
63517 ** results. This opcode causes the sqlite3_step() call to terminate
63518 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
63519 ** structure to provide access to the top P1 values as the result
63520 ** row.
63522 case OP_ResultRow: {
63523 #if 0 /* local variables moved into u.ad */
63524 Mem *pMem;
63525 int i;
63526 #endif /* local variables moved into u.ad */
63527 assert( p->nResColumn==pOp->p2 );
63528 assert( pOp->p1>0 );
63529 assert( pOp->p1+pOp->p2<=p->nMem+1 );
63531 /* If this statement has violated immediate foreign key constraints, do
63532 ** not return the number of rows modified. And do not RELEASE the statement
63533 ** transaction. It needs to be rolled back. */
63534 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
63535 assert( db->flags&SQLITE_CountRows );
63536 assert( p->usesStmtJournal );
63537 break;
63540 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
63541 ** DML statements invoke this opcode to return the number of rows
63542 ** modified to the user. This is the only way that a VM that
63543 ** opens a statement transaction may invoke this opcode.
63545 ** In case this is such a statement, close any statement transaction
63546 ** opened by this VM before returning control to the user. This is to
63547 ** ensure that statement-transactions are always nested, not overlapping.
63548 ** If the open statement-transaction is not closed here, then the user
63549 ** may step another VM that opens its own statement transaction. This
63550 ** may lead to overlapping statement transactions.
63552 ** The statement transaction is never a top-level transaction. Hence
63553 ** the RELEASE call below can never fail.
63555 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
63556 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
63557 if( NEVER(rc!=SQLITE_OK) ){
63558 break;
63561 /* Invalidate all ephemeral cursor row caches */
63562 p->cacheCtr = (p->cacheCtr + 2)|1;
63564 /* Make sure the results of the current row are \000 terminated
63565 ** and have an assigned type. The results are de-ephemeralized as
63566 ** as side effect.
63568 u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
63569 for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
63570 assert( memIsValid(&u.ad.pMem[u.ad.i]) );
63571 Deephemeralize(&u.ad.pMem[u.ad.i]);
63572 assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
63573 || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
63574 sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
63575 sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
63576 REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
63578 if( db->mallocFailed ) goto no_mem;
63580 /* Return SQLITE_ROW
63582 p->pc = pc + 1;
63583 rc = SQLITE_ROW;
63584 goto vdbe_return;
63587 /* Opcode: Concat P1 P2 P3 * *
63589 ** Add the text in register P1 onto the end of the text in
63590 ** register P2 and store the result in register P3.
63591 ** If either the P1 or P2 text are NULL then store NULL in P3.
63593 ** P3 = P2 || P1
63595 ** It is illegal for P1 and P3 to be the same register. Sometimes,
63596 ** if P3 is the same register as P2, the implementation is able
63597 ** to avoid a memcpy().
63599 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
63600 #if 0 /* local variables moved into u.ae */
63601 i64 nByte;
63602 #endif /* local variables moved into u.ae */
63604 pIn1 = &aMem[pOp->p1];
63605 pIn2 = &aMem[pOp->p2];
63606 pOut = &aMem[pOp->p3];
63607 assert( pIn1!=pOut );
63608 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
63609 sqlite3VdbeMemSetNull(pOut);
63610 break;
63612 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
63613 Stringify(pIn1, encoding);
63614 Stringify(pIn2, encoding);
63615 u.ae.nByte = pIn1->n + pIn2->n;
63616 if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63617 goto too_big;
63619 MemSetTypeFlag(pOut, MEM_Str);
63620 if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
63621 goto no_mem;
63623 if( pOut!=pIn2 ){
63624 memcpy(pOut->z, pIn2->z, pIn2->n);
63626 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
63627 pOut->z[u.ae.nByte] = 0;
63628 pOut->z[u.ae.nByte+1] = 0;
63629 pOut->flags |= MEM_Term;
63630 pOut->n = (int)u.ae.nByte;
63631 pOut->enc = encoding;
63632 UPDATE_MAX_BLOBSIZE(pOut);
63633 break;
63636 /* Opcode: Add P1 P2 P3 * *
63638 ** Add the value in register P1 to the value in register P2
63639 ** and store the result in register P3.
63640 ** If either input is NULL, the result is NULL.
63642 /* Opcode: Multiply P1 P2 P3 * *
63645 ** Multiply the value in register P1 by the value in register P2
63646 ** and store the result in register P3.
63647 ** If either input is NULL, the result is NULL.
63649 /* Opcode: Subtract P1 P2 P3 * *
63651 ** Subtract the value in register P1 from the value in register P2
63652 ** and store the result in register P3.
63653 ** If either input is NULL, the result is NULL.
63655 /* Opcode: Divide P1 P2 P3 * *
63657 ** Divide the value in register P1 by the value in register P2
63658 ** and store the result in register P3 (P3=P2/P1). If the value in
63659 ** register P1 is zero, then the result is NULL. If either input is
63660 ** NULL, the result is NULL.
63662 /* Opcode: Remainder P1 P2 P3 * *
63664 ** Compute the remainder after integer division of the value in
63665 ** register P1 by the value in register P2 and store the result in P3.
63666 ** If the value in register P2 is zero the result is NULL.
63667 ** If either operand is NULL, the result is NULL.
63669 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
63670 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
63671 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
63672 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
63673 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
63674 #if 0 /* local variables moved into u.af */
63675 int flags; /* Combined MEM_* flags from both inputs */
63676 i64 iA; /* Integer value of left operand */
63677 i64 iB; /* Integer value of right operand */
63678 double rA; /* Real value of left operand */
63679 double rB; /* Real value of right operand */
63680 #endif /* local variables moved into u.af */
63682 pIn1 = &aMem[pOp->p1];
63683 applyNumericAffinity(pIn1);
63684 pIn2 = &aMem[pOp->p2];
63685 applyNumericAffinity(pIn2);
63686 pOut = &aMem[pOp->p3];
63687 u.af.flags = pIn1->flags | pIn2->flags;
63688 if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
63689 if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
63690 u.af.iA = pIn1->u.i;
63691 u.af.iB = pIn2->u.i;
63692 switch( pOp->opcode ){
63693 case OP_Add: if( sqlite3AddInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
63694 case OP_Subtract: if( sqlite3SubInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
63695 case OP_Multiply: if( sqlite3MulInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
63696 case OP_Divide: {
63697 if( u.af.iA==0 ) goto arithmetic_result_is_null;
63698 if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) goto fp_math;
63699 u.af.iB /= u.af.iA;
63700 break;
63702 default: {
63703 if( u.af.iA==0 ) goto arithmetic_result_is_null;
63704 if( u.af.iA==-1 ) u.af.iA = 1;
63705 u.af.iB %= u.af.iA;
63706 break;
63709 pOut->u.i = u.af.iB;
63710 MemSetTypeFlag(pOut, MEM_Int);
63711 }else{
63712 fp_math:
63713 u.af.rA = sqlite3VdbeRealValue(pIn1);
63714 u.af.rB = sqlite3VdbeRealValue(pIn2);
63715 switch( pOp->opcode ){
63716 case OP_Add: u.af.rB += u.af.rA; break;
63717 case OP_Subtract: u.af.rB -= u.af.rA; break;
63718 case OP_Multiply: u.af.rB *= u.af.rA; break;
63719 case OP_Divide: {
63720 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
63721 if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
63722 u.af.rB /= u.af.rA;
63723 break;
63725 default: {
63726 u.af.iA = (i64)u.af.rA;
63727 u.af.iB = (i64)u.af.rB;
63728 if( u.af.iA==0 ) goto arithmetic_result_is_null;
63729 if( u.af.iA==-1 ) u.af.iA = 1;
63730 u.af.rB = (double)(u.af.iB % u.af.iA);
63731 break;
63734 #ifdef SQLITE_OMIT_FLOATING_POINT
63735 pOut->u.i = u.af.rB;
63736 MemSetTypeFlag(pOut, MEM_Int);
63737 #else
63738 if( sqlite3IsNaN(u.af.rB) ){
63739 goto arithmetic_result_is_null;
63741 pOut->r = u.af.rB;
63742 MemSetTypeFlag(pOut, MEM_Real);
63743 if( (u.af.flags & MEM_Real)==0 ){
63744 sqlite3VdbeIntegerAffinity(pOut);
63746 #endif
63748 break;
63750 arithmetic_result_is_null:
63751 sqlite3VdbeMemSetNull(pOut);
63752 break;
63755 /* Opcode: CollSeq * * P4
63757 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
63758 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
63759 ** be returned. This is used by the built-in min(), max() and nullif()
63760 ** functions.
63762 ** The interface used by the implementation of the aforementioned functions
63763 ** to retrieve the collation sequence set by this opcode is not available
63764 ** publicly, only to user functions defined in func.c.
63766 case OP_CollSeq: {
63767 assert( pOp->p4type==P4_COLLSEQ );
63768 break;
63771 /* Opcode: Function P1 P2 P3 P4 P5
63773 ** Invoke a user function (P4 is a pointer to a Function structure that
63774 ** defines the function) with P5 arguments taken from register P2 and
63775 ** successors. The result of the function is stored in register P3.
63776 ** Register P3 must not be one of the function inputs.
63778 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
63779 ** function was determined to be constant at compile time. If the first
63780 ** argument was constant then bit 0 of P1 is set. This is used to determine
63781 ** whether meta data associated with a user function argument using the
63782 ** sqlite3_set_auxdata() API may be safely retained until the next
63783 ** invocation of this opcode.
63785 ** See also: AggStep and AggFinal
63787 case OP_Function: {
63788 #if 0 /* local variables moved into u.ag */
63789 int i;
63790 Mem *pArg;
63791 sqlite3_context ctx;
63792 sqlite3_value **apVal;
63793 int n;
63794 #endif /* local variables moved into u.ag */
63796 u.ag.n = pOp->p5;
63797 u.ag.apVal = p->apArg;
63798 assert( u.ag.apVal || u.ag.n==0 );
63799 assert( pOp->p3>0 && pOp->p3<=p->nMem );
63800 pOut = &aMem[pOp->p3];
63801 memAboutToChange(p, pOut);
63803 assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
63804 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
63805 u.ag.pArg = &aMem[pOp->p2];
63806 for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
63807 assert( memIsValid(u.ag.pArg) );
63808 u.ag.apVal[u.ag.i] = u.ag.pArg;
63809 Deephemeralize(u.ag.pArg);
63810 sqlite3VdbeMemStoreType(u.ag.pArg);
63811 REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
63814 assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
63815 if( pOp->p4type==P4_FUNCDEF ){
63816 u.ag.ctx.pFunc = pOp->p4.pFunc;
63817 u.ag.ctx.pVdbeFunc = 0;
63818 }else{
63819 u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
63820 u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
63823 u.ag.ctx.s.flags = MEM_Null;
63824 u.ag.ctx.s.db = db;
63825 u.ag.ctx.s.xDel = 0;
63826 u.ag.ctx.s.zMalloc = 0;
63828 /* The output cell may already have a buffer allocated. Move
63829 ** the pointer to u.ag.ctx.s so in case the user-function can use
63830 ** the already allocated buffer instead of allocating a new one.
63832 sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
63833 MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
63835 u.ag.ctx.isError = 0;
63836 if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
63837 assert( pOp>aOp );
63838 assert( pOp[-1].p4type==P4_COLLSEQ );
63839 assert( pOp[-1].opcode==OP_CollSeq );
63840 u.ag.ctx.pColl = pOp[-1].p4.pColl;
63842 (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
63843 if( db->mallocFailed ){
63844 /* Even though a malloc() has failed, the implementation of the
63845 ** user function may have called an sqlite3_result_XXX() function
63846 ** to return a value. The following call releases any resources
63847 ** associated with such a value.
63849 sqlite3VdbeMemRelease(&u.ag.ctx.s);
63850 goto no_mem;
63853 /* If any auxiliary data functions have been called by this user function,
63854 ** immediately call the destructor for any non-static values.
63856 if( u.ag.ctx.pVdbeFunc ){
63857 sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
63858 pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
63859 pOp->p4type = P4_VDBEFUNC;
63862 /* If the function returned an error, throw an exception */
63863 if( u.ag.ctx.isError ){
63864 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
63865 rc = u.ag.ctx.isError;
63868 /* Copy the result of the function into register P3 */
63869 sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
63870 sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
63871 if( sqlite3VdbeMemTooBig(pOut) ){
63872 goto too_big;
63875 #if 0
63876 /* The app-defined function has done something that as caused this
63877 ** statement to expire. (Perhaps the function called sqlite3_exec()
63878 ** with a CREATE TABLE statement.)
63880 if( p->expired ) rc = SQLITE_ABORT;
63881 #endif
63883 REGISTER_TRACE(pOp->p3, pOut);
63884 UPDATE_MAX_BLOBSIZE(pOut);
63885 break;
63888 /* Opcode: BitAnd P1 P2 P3 * *
63890 ** Take the bit-wise AND of the values in register P1 and P2 and
63891 ** store the result in register P3.
63892 ** If either input is NULL, the result is NULL.
63894 /* Opcode: BitOr P1 P2 P3 * *
63896 ** Take the bit-wise OR of the values in register P1 and P2 and
63897 ** store the result in register P3.
63898 ** If either input is NULL, the result is NULL.
63900 /* Opcode: ShiftLeft P1 P2 P3 * *
63902 ** Shift the integer value in register P2 to the left by the
63903 ** number of bits specified by the integer in register P1.
63904 ** Store the result in register P3.
63905 ** If either input is NULL, the result is NULL.
63907 /* Opcode: ShiftRight P1 P2 P3 * *
63909 ** Shift the integer value in register P2 to the right by the
63910 ** number of bits specified by the integer in register P1.
63911 ** Store the result in register P3.
63912 ** If either input is NULL, the result is NULL.
63914 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
63915 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
63916 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
63917 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
63918 #if 0 /* local variables moved into u.ah */
63919 i64 iA;
63920 u64 uA;
63921 i64 iB;
63922 u8 op;
63923 #endif /* local variables moved into u.ah */
63925 pIn1 = &aMem[pOp->p1];
63926 pIn2 = &aMem[pOp->p2];
63927 pOut = &aMem[pOp->p3];
63928 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
63929 sqlite3VdbeMemSetNull(pOut);
63930 break;
63932 u.ah.iA = sqlite3VdbeIntValue(pIn2);
63933 u.ah.iB = sqlite3VdbeIntValue(pIn1);
63934 u.ah.op = pOp->opcode;
63935 if( u.ah.op==OP_BitAnd ){
63936 u.ah.iA &= u.ah.iB;
63937 }else if( u.ah.op==OP_BitOr ){
63938 u.ah.iA |= u.ah.iB;
63939 }else if( u.ah.iB!=0 ){
63940 assert( u.ah.op==OP_ShiftRight || u.ah.op==OP_ShiftLeft );
63942 /* If shifting by a negative amount, shift in the other direction */
63943 if( u.ah.iB<0 ){
63944 assert( OP_ShiftRight==OP_ShiftLeft+1 );
63945 u.ah.op = 2*OP_ShiftLeft + 1 - u.ah.op;
63946 u.ah.iB = u.ah.iB>(-64) ? -u.ah.iB : 64;
63949 if( u.ah.iB>=64 ){
63950 u.ah.iA = (u.ah.iA>=0 || u.ah.op==OP_ShiftLeft) ? 0 : -1;
63951 }else{
63952 memcpy(&u.ah.uA, &u.ah.iA, sizeof(u.ah.uA));
63953 if( u.ah.op==OP_ShiftLeft ){
63954 u.ah.uA <<= u.ah.iB;
63955 }else{
63956 u.ah.uA >>= u.ah.iB;
63957 /* Sign-extend on a right shift of a negative number */
63958 if( u.ah.iA<0 ) u.ah.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ah.iB);
63960 memcpy(&u.ah.iA, &u.ah.uA, sizeof(u.ah.iA));
63963 pOut->u.i = u.ah.iA;
63964 MemSetTypeFlag(pOut, MEM_Int);
63965 break;
63968 /* Opcode: AddImm P1 P2 * * *
63970 ** Add the constant P2 to the value in register P1.
63971 ** The result is always an integer.
63973 ** To force any register to be an integer, just add 0.
63975 case OP_AddImm: { /* in1 */
63976 pIn1 = &aMem[pOp->p1];
63977 memAboutToChange(p, pIn1);
63978 sqlite3VdbeMemIntegerify(pIn1);
63979 pIn1->u.i += pOp->p2;
63980 break;
63983 /* Opcode: MustBeInt P1 P2 * * *
63985 ** Force the value in register P1 to be an integer. If the value
63986 ** in P1 is not an integer and cannot be converted into an integer
63987 ** without data loss, then jump immediately to P2, or if P2==0
63988 ** raise an SQLITE_MISMATCH exception.
63990 case OP_MustBeInt: { /* jump, in1 */
63991 pIn1 = &aMem[pOp->p1];
63992 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
63993 if( (pIn1->flags & MEM_Int)==0 ){
63994 if( pOp->p2==0 ){
63995 rc = SQLITE_MISMATCH;
63996 goto abort_due_to_error;
63997 }else{
63998 pc = pOp->p2 - 1;
64000 }else{
64001 MemSetTypeFlag(pIn1, MEM_Int);
64003 break;
64006 #ifndef SQLITE_OMIT_FLOATING_POINT
64007 /* Opcode: RealAffinity P1 * * * *
64009 ** If register P1 holds an integer convert it to a real value.
64011 ** This opcode is used when extracting information from a column that
64012 ** has REAL affinity. Such column values may still be stored as
64013 ** integers, for space efficiency, but after extraction we want them
64014 ** to have only a real value.
64016 case OP_RealAffinity: { /* in1 */
64017 pIn1 = &aMem[pOp->p1];
64018 if( pIn1->flags & MEM_Int ){
64019 sqlite3VdbeMemRealify(pIn1);
64021 break;
64023 #endif
64025 #ifndef SQLITE_OMIT_CAST
64026 /* Opcode: ToText P1 * * * *
64028 ** Force the value in register P1 to be text.
64029 ** If the value is numeric, convert it to a string using the
64030 ** equivalent of printf(). Blob values are unchanged and
64031 ** are afterwards simply interpreted as text.
64033 ** A NULL value is not changed by this routine. It remains NULL.
64035 case OP_ToText: { /* same as TK_TO_TEXT, in1 */
64036 pIn1 = &aMem[pOp->p1];
64037 memAboutToChange(p, pIn1);
64038 if( pIn1->flags & MEM_Null ) break;
64039 assert( MEM_Str==(MEM_Blob>>3) );
64040 pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
64041 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
64042 rc = ExpandBlob(pIn1);
64043 assert( pIn1->flags & MEM_Str || db->mallocFailed );
64044 pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
64045 UPDATE_MAX_BLOBSIZE(pIn1);
64046 break;
64049 /* Opcode: ToBlob P1 * * * *
64051 ** Force the value in register P1 to be a BLOB.
64052 ** If the value is numeric, convert it to a string first.
64053 ** Strings are simply reinterpreted as blobs with no change
64054 ** to the underlying data.
64056 ** A NULL value is not changed by this routine. It remains NULL.
64058 case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
64059 pIn1 = &aMem[pOp->p1];
64060 if( pIn1->flags & MEM_Null ) break;
64061 if( (pIn1->flags & MEM_Blob)==0 ){
64062 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
64063 assert( pIn1->flags & MEM_Str || db->mallocFailed );
64064 MemSetTypeFlag(pIn1, MEM_Blob);
64065 }else{
64066 pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
64068 UPDATE_MAX_BLOBSIZE(pIn1);
64069 break;
64072 /* Opcode: ToNumeric P1 * * * *
64074 ** Force the value in register P1 to be numeric (either an
64075 ** integer or a floating-point number.)
64076 ** If the value is text or blob, try to convert it to an using the
64077 ** equivalent of atoi() or atof() and store 0 if no such conversion
64078 ** is possible.
64080 ** A NULL value is not changed by this routine. It remains NULL.
64082 case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
64083 pIn1 = &aMem[pOp->p1];
64084 sqlite3VdbeMemNumerify(pIn1);
64085 break;
64087 #endif /* SQLITE_OMIT_CAST */
64089 /* Opcode: ToInt P1 * * * *
64091 ** Force the value in register P1 to be an integer. If
64092 ** The value is currently a real number, drop its fractional part.
64093 ** If the value is text or blob, try to convert it to an integer using the
64094 ** equivalent of atoi() and store 0 if no such conversion is possible.
64096 ** A NULL value is not changed by this routine. It remains NULL.
64098 case OP_ToInt: { /* same as TK_TO_INT, in1 */
64099 pIn1 = &aMem[pOp->p1];
64100 if( (pIn1->flags & MEM_Null)==0 ){
64101 sqlite3VdbeMemIntegerify(pIn1);
64103 break;
64106 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
64107 /* Opcode: ToReal P1 * * * *
64109 ** Force the value in register P1 to be a floating point number.
64110 ** If The value is currently an integer, convert it.
64111 ** If the value is text or blob, try to convert it to an integer using the
64112 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
64114 ** A NULL value is not changed by this routine. It remains NULL.
64116 case OP_ToReal: { /* same as TK_TO_REAL, in1 */
64117 pIn1 = &aMem[pOp->p1];
64118 memAboutToChange(p, pIn1);
64119 if( (pIn1->flags & MEM_Null)==0 ){
64120 sqlite3VdbeMemRealify(pIn1);
64122 break;
64124 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
64126 /* Opcode: Lt P1 P2 P3 P4 P5
64128 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
64129 ** jump to address P2.
64131 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
64132 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
64133 ** bit is clear then fall through if either operand is NULL.
64135 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
64136 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
64137 ** to coerce both inputs according to this affinity before the
64138 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
64139 ** affinity is used. Note that the affinity conversions are stored
64140 ** back into the input registers P1 and P3. So this opcode can cause
64141 ** persistent changes to registers P1 and P3.
64143 ** Once any conversions have taken place, and neither value is NULL,
64144 ** the values are compared. If both values are blobs then memcmp() is
64145 ** used to determine the results of the comparison. If both values
64146 ** are text, then the appropriate collating function specified in
64147 ** P4 is used to do the comparison. If P4 is not specified then
64148 ** memcmp() is used to compare text string. If both values are
64149 ** numeric, then a numeric comparison is used. If the two values
64150 ** are of different types, then numbers are considered less than
64151 ** strings and strings are considered less than blobs.
64153 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
64154 ** store a boolean result (either 0, or 1, or NULL) in register P2.
64156 /* Opcode: Ne P1 P2 P3 P4 P5
64158 ** This works just like the Lt opcode except that the jump is taken if
64159 ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
64160 ** additional information.
64162 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
64163 ** true or false and is never NULL. If both operands are NULL then the result
64164 ** of comparison is false. If either operand is NULL then the result is true.
64165 ** If neither operand is NULL the the result is the same as it would be if
64166 ** the SQLITE_NULLEQ flag were omitted from P5.
64168 /* Opcode: Eq P1 P2 P3 P4 P5
64170 ** This works just like the Lt opcode except that the jump is taken if
64171 ** the operands in registers P1 and P3 are equal.
64172 ** See the Lt opcode for additional information.
64174 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
64175 ** true or false and is never NULL. If both operands are NULL then the result
64176 ** of comparison is true. If either operand is NULL then the result is false.
64177 ** If neither operand is NULL the the result is the same as it would be if
64178 ** the SQLITE_NULLEQ flag were omitted from P5.
64180 /* Opcode: Le P1 P2 P3 P4 P5
64182 ** This works just like the Lt opcode except that the jump is taken if
64183 ** the content of register P3 is less than or equal to the content of
64184 ** register P1. See the Lt opcode for additional information.
64186 /* Opcode: Gt P1 P2 P3 P4 P5
64188 ** This works just like the Lt opcode except that the jump is taken if
64189 ** the content of register P3 is greater than the content of
64190 ** register P1. See the Lt opcode for additional information.
64192 /* Opcode: Ge P1 P2 P3 P4 P5
64194 ** This works just like the Lt opcode except that the jump is taken if
64195 ** the content of register P3 is greater than or equal to the content of
64196 ** register P1. See the Lt opcode for additional information.
64198 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
64199 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
64200 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
64201 case OP_Le: /* same as TK_LE, jump, in1, in3 */
64202 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
64203 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
64204 #if 0 /* local variables moved into u.ai */
64205 int res; /* Result of the comparison of pIn1 against pIn3 */
64206 char affinity; /* Affinity to use for comparison */
64207 u16 flags1; /* Copy of initial value of pIn1->flags */
64208 u16 flags3; /* Copy of initial value of pIn3->flags */
64209 #endif /* local variables moved into u.ai */
64211 pIn1 = &aMem[pOp->p1];
64212 pIn3 = &aMem[pOp->p3];
64213 u.ai.flags1 = pIn1->flags;
64214 u.ai.flags3 = pIn3->flags;
64215 if( (pIn1->flags | pIn3->flags)&MEM_Null ){
64216 /* One or both operands are NULL */
64217 if( pOp->p5 & SQLITE_NULLEQ ){
64218 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
64219 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
64220 ** or not both operands are null.
64222 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
64223 u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
64224 }else{
64225 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
64226 ** then the result is always NULL.
64227 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
64229 if( pOp->p5 & SQLITE_STOREP2 ){
64230 pOut = &aMem[pOp->p2];
64231 MemSetTypeFlag(pOut, MEM_Null);
64232 REGISTER_TRACE(pOp->p2, pOut);
64233 }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
64234 pc = pOp->p2-1;
64236 break;
64238 }else{
64239 /* Neither operand is NULL. Do a comparison. */
64240 u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
64241 if( u.ai.affinity ){
64242 applyAffinity(pIn1, u.ai.affinity, encoding);
64243 applyAffinity(pIn3, u.ai.affinity, encoding);
64244 if( db->mallocFailed ) goto no_mem;
64247 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
64248 ExpandBlob(pIn1);
64249 ExpandBlob(pIn3);
64250 u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
64252 switch( pOp->opcode ){
64253 case OP_Eq: u.ai.res = u.ai.res==0; break;
64254 case OP_Ne: u.ai.res = u.ai.res!=0; break;
64255 case OP_Lt: u.ai.res = u.ai.res<0; break;
64256 case OP_Le: u.ai.res = u.ai.res<=0; break;
64257 case OP_Gt: u.ai.res = u.ai.res>0; break;
64258 default: u.ai.res = u.ai.res>=0; break;
64261 if( pOp->p5 & SQLITE_STOREP2 ){
64262 pOut = &aMem[pOp->p2];
64263 memAboutToChange(p, pOut);
64264 MemSetTypeFlag(pOut, MEM_Int);
64265 pOut->u.i = u.ai.res;
64266 REGISTER_TRACE(pOp->p2, pOut);
64267 }else if( u.ai.res ){
64268 pc = pOp->p2-1;
64271 /* Undo any changes made by applyAffinity() to the input registers. */
64272 pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
64273 pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
64274 break;
64277 /* Opcode: Permutation * * * P4 *
64279 ** Set the permutation used by the OP_Compare operator to be the array
64280 ** of integers in P4.
64282 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
64283 ** OP_Halt, or OP_ResultRow. Typically the OP_Permutation should occur
64284 ** immediately prior to the OP_Compare.
64286 case OP_Permutation: {
64287 assert( pOp->p4type==P4_INTARRAY );
64288 assert( pOp->p4.ai );
64289 aPermute = pOp->p4.ai;
64290 break;
64293 /* Opcode: Compare P1 P2 P3 P4 *
64295 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
64296 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
64297 ** the comparison for use by the next OP_Jump instruct.
64299 ** P4 is a KeyInfo structure that defines collating sequences and sort
64300 ** orders for the comparison. The permutation applies to registers
64301 ** only. The KeyInfo elements are used sequentially.
64303 ** The comparison is a sort comparison, so NULLs compare equal,
64304 ** NULLs are less than numbers, numbers are less than strings,
64305 ** and strings are less than blobs.
64307 case OP_Compare: {
64308 #if 0 /* local variables moved into u.aj */
64309 int n;
64310 int i;
64311 int p1;
64312 int p2;
64313 const KeyInfo *pKeyInfo;
64314 int idx;
64315 CollSeq *pColl; /* Collating sequence to use on this term */
64316 int bRev; /* True for DESCENDING sort order */
64317 #endif /* local variables moved into u.aj */
64319 u.aj.n = pOp->p3;
64320 u.aj.pKeyInfo = pOp->p4.pKeyInfo;
64321 assert( u.aj.n>0 );
64322 assert( u.aj.pKeyInfo!=0 );
64323 u.aj.p1 = pOp->p1;
64324 u.aj.p2 = pOp->p2;
64325 #if SQLITE_DEBUG
64326 if( aPermute ){
64327 int k, mx = 0;
64328 for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
64329 assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
64330 assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
64331 }else{
64332 assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
64333 assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
64335 #endif /* SQLITE_DEBUG */
64336 for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
64337 u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
64338 assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
64339 assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
64340 REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
64341 REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
64342 assert( u.aj.i<u.aj.pKeyInfo->nField );
64343 u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
64344 u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
64345 iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
64346 if( iCompare ){
64347 if( u.aj.bRev ) iCompare = -iCompare;
64348 break;
64351 aPermute = 0;
64352 break;
64355 /* Opcode: Jump P1 P2 P3 * *
64357 ** Jump to the instruction at address P1, P2, or P3 depending on whether
64358 ** in the most recent OP_Compare instruction the P1 vector was less than
64359 ** equal to, or greater than the P2 vector, respectively.
64361 case OP_Jump: { /* jump */
64362 if( iCompare<0 ){
64363 pc = pOp->p1 - 1;
64364 }else if( iCompare==0 ){
64365 pc = pOp->p2 - 1;
64366 }else{
64367 pc = pOp->p3 - 1;
64369 break;
64372 /* Opcode: And P1 P2 P3 * *
64374 ** Take the logical AND of the values in registers P1 and P2 and
64375 ** write the result into register P3.
64377 ** If either P1 or P2 is 0 (false) then the result is 0 even if
64378 ** the other input is NULL. A NULL and true or two NULLs give
64379 ** a NULL output.
64381 /* Opcode: Or P1 P2 P3 * *
64383 ** Take the logical OR of the values in register P1 and P2 and
64384 ** store the answer in register P3.
64386 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
64387 ** even if the other input is NULL. A NULL and false or two NULLs
64388 ** give a NULL output.
64390 case OP_And: /* same as TK_AND, in1, in2, out3 */
64391 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
64392 #if 0 /* local variables moved into u.ak */
64393 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64394 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64395 #endif /* local variables moved into u.ak */
64397 pIn1 = &aMem[pOp->p1];
64398 if( pIn1->flags & MEM_Null ){
64399 u.ak.v1 = 2;
64400 }else{
64401 u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
64403 pIn2 = &aMem[pOp->p2];
64404 if( pIn2->flags & MEM_Null ){
64405 u.ak.v2 = 2;
64406 }else{
64407 u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
64409 if( pOp->opcode==OP_And ){
64410 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
64411 u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
64412 }else{
64413 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
64414 u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
64416 pOut = &aMem[pOp->p3];
64417 if( u.ak.v1==2 ){
64418 MemSetTypeFlag(pOut, MEM_Null);
64419 }else{
64420 pOut->u.i = u.ak.v1;
64421 MemSetTypeFlag(pOut, MEM_Int);
64423 break;
64426 /* Opcode: Not P1 P2 * * *
64428 ** Interpret the value in register P1 as a boolean value. Store the
64429 ** boolean complement in register P2. If the value in register P1 is
64430 ** NULL, then a NULL is stored in P2.
64432 case OP_Not: { /* same as TK_NOT, in1, out2 */
64433 pIn1 = &aMem[pOp->p1];
64434 pOut = &aMem[pOp->p2];
64435 if( pIn1->flags & MEM_Null ){
64436 sqlite3VdbeMemSetNull(pOut);
64437 }else{
64438 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
64440 break;
64443 /* Opcode: BitNot P1 P2 * * *
64445 ** Interpret the content of register P1 as an integer. Store the
64446 ** ones-complement of the P1 value into register P2. If P1 holds
64447 ** a NULL then store a NULL in P2.
64449 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
64450 pIn1 = &aMem[pOp->p1];
64451 pOut = &aMem[pOp->p2];
64452 if( pIn1->flags & MEM_Null ){
64453 sqlite3VdbeMemSetNull(pOut);
64454 }else{
64455 sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
64457 break;
64460 /* Opcode: If P1 P2 P3 * *
64462 ** Jump to P2 if the value in register P1 is true. The value is
64463 ** is considered true if it is numeric and non-zero. If the value
64464 ** in P1 is NULL then take the jump if P3 is true.
64466 /* Opcode: IfNot P1 P2 P3 * *
64468 ** Jump to P2 if the value in register P1 is False. The value is
64469 ** is considered true if it has a numeric value of zero. If the value
64470 ** in P1 is NULL then take the jump if P3 is true.
64472 case OP_If: /* jump, in1 */
64473 case OP_IfNot: { /* jump, in1 */
64474 #if 0 /* local variables moved into u.al */
64475 int c;
64476 #endif /* local variables moved into u.al */
64477 pIn1 = &aMem[pOp->p1];
64478 if( pIn1->flags & MEM_Null ){
64479 u.al.c = pOp->p3;
64480 }else{
64481 #ifdef SQLITE_OMIT_FLOATING_POINT
64482 u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
64483 #else
64484 u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
64485 #endif
64486 if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
64488 if( u.al.c ){
64489 pc = pOp->p2-1;
64491 break;
64494 /* Opcode: IsNull P1 P2 * * *
64496 ** Jump to P2 if the value in register P1 is NULL.
64498 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
64499 pIn1 = &aMem[pOp->p1];
64500 if( (pIn1->flags & MEM_Null)!=0 ){
64501 pc = pOp->p2 - 1;
64503 break;
64506 /* Opcode: NotNull P1 P2 * * *
64508 ** Jump to P2 if the value in register P1 is not NULL.
64510 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
64511 pIn1 = &aMem[pOp->p1];
64512 if( (pIn1->flags & MEM_Null)==0 ){
64513 pc = pOp->p2 - 1;
64515 break;
64518 /* Opcode: Column P1 P2 P3 P4 P5
64520 ** Interpret the data that cursor P1 points to as a structure built using
64521 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
64522 ** information about the format of the data.) Extract the P2-th column
64523 ** from this record. If there are less that (P2+1)
64524 ** values in the record, extract a NULL.
64526 ** The value extracted is stored in register P3.
64528 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
64529 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
64530 ** the result.
64532 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
64533 ** then the cache of the cursor is reset prior to extracting the column.
64534 ** The first OP_Column against a pseudo-table after the value of the content
64535 ** register has changed should have this bit set.
64537 case OP_Column: {
64538 #if 0 /* local variables moved into u.am */
64539 u32 payloadSize; /* Number of bytes in the record */
64540 i64 payloadSize64; /* Number of bytes in the record */
64541 int p1; /* P1 value of the opcode */
64542 int p2; /* column number to retrieve */
64543 VdbeCursor *pC; /* The VDBE cursor */
64544 char *zRec; /* Pointer to complete record-data */
64545 BtCursor *pCrsr; /* The BTree cursor */
64546 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
64547 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
64548 int nField; /* number of fields in the record */
64549 int len; /* The length of the serialized data for the column */
64550 int i; /* Loop counter */
64551 char *zData; /* Part of the record being decoded */
64552 Mem *pDest; /* Where to write the extracted value */
64553 Mem sMem; /* For storing the record being decoded */
64554 u8 *zIdx; /* Index into header */
64555 u8 *zEndHdr; /* Pointer to first byte after the header */
64556 u32 offset; /* Offset into the data */
64557 u32 szField; /* Number of bytes in the content of a field */
64558 int szHdr; /* Size of the header size field at start of record */
64559 int avail; /* Number of bytes of available data */
64560 Mem *pReg; /* PseudoTable input register */
64561 #endif /* local variables moved into u.am */
64564 u.am.p1 = pOp->p1;
64565 u.am.p2 = pOp->p2;
64566 u.am.pC = 0;
64567 memset(&u.am.sMem, 0, sizeof(u.am.sMem));
64568 assert( u.am.p1<p->nCursor );
64569 assert( pOp->p3>0 && pOp->p3<=p->nMem );
64570 u.am.pDest = &aMem[pOp->p3];
64571 memAboutToChange(p, u.am.pDest);
64572 MemSetTypeFlag(u.am.pDest, MEM_Null);
64573 u.am.zRec = 0;
64575 /* This block sets the variable u.am.payloadSize to be the total number of
64576 ** bytes in the record.
64578 ** u.am.zRec is set to be the complete text of the record if it is available.
64579 ** The complete record text is always available for pseudo-tables
64580 ** If the record is stored in a cursor, the complete record text
64581 ** might be available in the u.am.pC->aRow cache. Or it might not be.
64582 ** If the data is unavailable, u.am.zRec is set to NULL.
64584 ** We also compute the number of columns in the record. For cursors,
64585 ** the number of columns is stored in the VdbeCursor.nField element.
64587 u.am.pC = p->apCsr[u.am.p1];
64588 assert( u.am.pC!=0 );
64589 #ifndef SQLITE_OMIT_VIRTUALTABLE
64590 assert( u.am.pC->pVtabCursor==0 );
64591 #endif
64592 u.am.pCrsr = u.am.pC->pCursor;
64593 if( u.am.pCrsr!=0 ){
64594 /* The record is stored in a B-Tree */
64595 rc = sqlite3VdbeCursorMoveto(u.am.pC);
64596 if( rc ) goto abort_due_to_error;
64597 if( u.am.pC->nullRow ){
64598 u.am.payloadSize = 0;
64599 }else if( u.am.pC->cacheStatus==p->cacheCtr ){
64600 u.am.payloadSize = u.am.pC->payloadSize;
64601 u.am.zRec = (char*)u.am.pC->aRow;
64602 }else if( u.am.pC->isIndex ){
64603 assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64604 rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
64605 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
64606 /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
64607 ** payload size, so it is impossible for u.am.payloadSize64 to be
64608 ** larger than 32 bits. */
64609 assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
64610 u.am.payloadSize = (u32)u.am.payloadSize64;
64611 }else{
64612 assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64613 rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
64614 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
64616 }else if( u.am.pC->pseudoTableReg>0 ){
64617 u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
64618 assert( u.am.pReg->flags & MEM_Blob );
64619 assert( memIsValid(u.am.pReg) );
64620 u.am.payloadSize = u.am.pReg->n;
64621 u.am.zRec = u.am.pReg->z;
64622 u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
64623 assert( u.am.payloadSize==0 || u.am.zRec!=0 );
64624 }else{
64625 /* Consider the row to be NULL */
64626 u.am.payloadSize = 0;
64629 /* If u.am.payloadSize is 0, then just store a NULL */
64630 if( u.am.payloadSize==0 ){
64631 assert( u.am.pDest->flags&MEM_Null );
64632 goto op_column_out;
64634 assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
64635 if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
64636 goto too_big;
64639 u.am.nField = u.am.pC->nField;
64640 assert( u.am.p2<u.am.nField );
64642 /* Read and parse the table header. Store the results of the parse
64643 ** into the record header cache fields of the cursor.
64645 u.am.aType = u.am.pC->aType;
64646 if( u.am.pC->cacheStatus==p->cacheCtr ){
64647 u.am.aOffset = u.am.pC->aOffset;
64648 }else{
64649 assert(u.am.aType);
64650 u.am.avail = 0;
64651 u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
64652 u.am.pC->payloadSize = u.am.payloadSize;
64653 u.am.pC->cacheStatus = p->cacheCtr;
64655 /* Figure out how many bytes are in the header */
64656 if( u.am.zRec ){
64657 u.am.zData = u.am.zRec;
64658 }else{
64659 if( u.am.pC->isIndex ){
64660 u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
64661 }else{
64662 u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
64664 /* If KeyFetch()/DataFetch() managed to get the entire payload,
64665 ** save the payload in the u.am.pC->aRow cache. That will save us from
64666 ** having to make additional calls to fetch the content portion of
64667 ** the record.
64669 assert( u.am.avail>=0 );
64670 if( u.am.payloadSize <= (u32)u.am.avail ){
64671 u.am.zRec = u.am.zData;
64672 u.am.pC->aRow = (u8*)u.am.zData;
64673 }else{
64674 u.am.pC->aRow = 0;
64677 /* The following assert is true in all cases accept when
64678 ** the database file has been corrupted externally.
64679 ** assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
64680 u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
64682 /* Make sure a corrupt database has not given us an oversize header.
64683 ** Do this now to avoid an oversize memory allocation.
64685 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
64686 ** types use so much data space that there can only be 4096 and 32 of
64687 ** them, respectively. So the maximum header length results from a
64688 ** 3-byte type for each of the maximum of 32768 columns plus three
64689 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
64691 if( u.am.offset > 98307 ){
64692 rc = SQLITE_CORRUPT_BKPT;
64693 goto op_column_out;
64696 /* Compute in u.am.len the number of bytes of data we need to read in order
64697 ** to get u.am.nField type values. u.am.offset is an upper bound on this. But
64698 ** u.am.nField might be significantly less than the true number of columns
64699 ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
64700 ** We want to minimize u.am.len in order to limit the size of the memory
64701 ** allocation, especially if a corrupt database file has caused u.am.offset
64702 ** to be oversized. Offset is limited to 98307 above. But 98307 might
64703 ** still exceed Robson memory allocation limits on some configurations.
64704 ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
64705 ** will likely be much smaller since u.am.nField will likely be less than
64706 ** 20 or so. This insures that Robson memory allocation limits are
64707 ** not exceeded even for corrupt database files.
64709 u.am.len = u.am.nField*5 + 3;
64710 if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
64712 /* The KeyFetch() or DataFetch() above are fast and will get the entire
64713 ** record header in most cases. But they will fail to get the complete
64714 ** record header if the record header does not fit on a single page
64715 ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
64716 ** acquire the complete header text.
64718 if( !u.am.zRec && u.am.avail<u.am.len ){
64719 u.am.sMem.flags = 0;
64720 u.am.sMem.db = 0;
64721 rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
64722 if( rc!=SQLITE_OK ){
64723 goto op_column_out;
64725 u.am.zData = u.am.sMem.z;
64727 u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
64728 u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
64730 /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
64731 ** arrays. u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
64732 ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
64733 ** of the record to the start of the data for the u.am.i-th column
64735 for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
64736 if( u.am.zIdx<u.am.zEndHdr ){
64737 u.am.aOffset[u.am.i] = u.am.offset;
64738 u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
64739 u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
64740 u.am.offset += u.am.szField;
64741 if( u.am.offset<u.am.szField ){ /* True if u.am.offset overflows */
64742 u.am.zIdx = &u.am.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
64743 break;
64745 }else{
64746 /* If u.am.i is less that u.am.nField, then there are less fields in this
64747 ** record than SetNumColumns indicated there are columns in the
64748 ** table. Set the u.am.offset for any extra columns not present in
64749 ** the record to 0. This tells code below to store a NULL
64750 ** instead of deserializing a value from the record.
64752 u.am.aOffset[u.am.i] = 0;
64755 sqlite3VdbeMemRelease(&u.am.sMem);
64756 u.am.sMem.flags = MEM_Null;
64758 /* If we have read more header data than was contained in the header,
64759 ** or if the end of the last field appears to be past the end of the
64760 ** record, or if the end of the last field appears to be before the end
64761 ** of the record (when all fields present), then we must be dealing
64762 ** with a corrupt database.
64764 if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
64765 || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
64766 rc = SQLITE_CORRUPT_BKPT;
64767 goto op_column_out;
64771 /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
64772 ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
64773 ** then there are not enough fields in the record to satisfy the
64774 ** request. In this case, set the value NULL or to P4 if P4 is
64775 ** a pointer to a Mem object.
64777 if( u.am.aOffset[u.am.p2] ){
64778 assert( rc==SQLITE_OK );
64779 if( u.am.zRec ){
64780 sqlite3VdbeMemReleaseExternal(u.am.pDest);
64781 sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
64782 }else{
64783 u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
64784 sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
64785 rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
64786 if( rc!=SQLITE_OK ){
64787 goto op_column_out;
64789 u.am.zData = u.am.sMem.z;
64790 sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
64792 u.am.pDest->enc = encoding;
64793 }else{
64794 if( pOp->p4type==P4_MEM ){
64795 sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
64796 }else{
64797 assert( u.am.pDest->flags&MEM_Null );
64801 /* If we dynamically allocated space to hold the data (in the
64802 ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
64803 ** dynamically allocated space over to the u.am.pDest structure.
64804 ** This prevents a memory copy.
64806 if( u.am.sMem.zMalloc ){
64807 assert( u.am.sMem.z==u.am.sMem.zMalloc );
64808 assert( !(u.am.pDest->flags & MEM_Dyn) );
64809 assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
64810 u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
64811 u.am.pDest->flags |= MEM_Term;
64812 u.am.pDest->z = u.am.sMem.z;
64813 u.am.pDest->zMalloc = u.am.sMem.zMalloc;
64816 rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
64818 op_column_out:
64819 UPDATE_MAX_BLOBSIZE(u.am.pDest);
64820 REGISTER_TRACE(pOp->p3, u.am.pDest);
64821 break;
64824 /* Opcode: Affinity P1 P2 * P4 *
64826 ** Apply affinities to a range of P2 registers starting with P1.
64828 ** P4 is a string that is P2 characters long. The nth character of the
64829 ** string indicates the column affinity that should be used for the nth
64830 ** memory cell in the range.
64832 case OP_Affinity: {
64833 #if 0 /* local variables moved into u.an */
64834 const char *zAffinity; /* The affinity to be applied */
64835 char cAff; /* A single character of affinity */
64836 #endif /* local variables moved into u.an */
64838 u.an.zAffinity = pOp->p4.z;
64839 assert( u.an.zAffinity!=0 );
64840 assert( u.an.zAffinity[pOp->p2]==0 );
64841 pIn1 = &aMem[pOp->p1];
64842 while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
64843 assert( pIn1 <= &p->aMem[p->nMem] );
64844 assert( memIsValid(pIn1) );
64845 ExpandBlob(pIn1);
64846 applyAffinity(pIn1, u.an.cAff, encoding);
64847 pIn1++;
64849 break;
64852 /* Opcode: MakeRecord P1 P2 P3 P4 *
64854 ** Convert P2 registers beginning with P1 into the [record format]
64855 ** use as a data record in a database table or as a key
64856 ** in an index. The OP_Column opcode can decode the record later.
64858 ** P4 may be a string that is P2 characters long. The nth character of the
64859 ** string indicates the column affinity that should be used for the nth
64860 ** field of the index key.
64862 ** The mapping from character to affinity is given by the SQLITE_AFF_
64863 ** macros defined in sqliteInt.h.
64865 ** If P4 is NULL then all index fields have the affinity NONE.
64867 case OP_MakeRecord: {
64868 #if 0 /* local variables moved into u.ao */
64869 u8 *zNewRecord; /* A buffer to hold the data for the new record */
64870 Mem *pRec; /* The new record */
64871 u64 nData; /* Number of bytes of data space */
64872 int nHdr; /* Number of bytes of header space */
64873 i64 nByte; /* Data space required for this record */
64874 int nZero; /* Number of zero bytes at the end of the record */
64875 int nVarint; /* Number of bytes in a varint */
64876 u32 serial_type; /* Type field */
64877 Mem *pData0; /* First field to be combined into the record */
64878 Mem *pLast; /* Last field of the record */
64879 int nField; /* Number of fields in the record */
64880 char *zAffinity; /* The affinity string for the record */
64881 int file_format; /* File format to use for encoding */
64882 int i; /* Space used in zNewRecord[] */
64883 int len; /* Length of a field */
64884 #endif /* local variables moved into u.ao */
64886 /* Assuming the record contains N fields, the record format looks
64887 ** like this:
64889 ** ------------------------------------------------------------------------
64890 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
64891 ** ------------------------------------------------------------------------
64893 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
64894 ** and so froth.
64896 ** Each type field is a varint representing the serial type of the
64897 ** corresponding data element (see sqlite3VdbeSerialType()). The
64898 ** hdr-size field is also a varint which is the offset from the beginning
64899 ** of the record to data0.
64901 u.ao.nData = 0; /* Number of bytes of data space */
64902 u.ao.nHdr = 0; /* Number of bytes of header space */
64903 u.ao.nZero = 0; /* Number of zero bytes at the end of the record */
64904 u.ao.nField = pOp->p1;
64905 u.ao.zAffinity = pOp->p4.z;
64906 assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
64907 u.ao.pData0 = &aMem[u.ao.nField];
64908 u.ao.nField = pOp->p2;
64909 u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
64910 u.ao.file_format = p->minWriteFileFormat;
64912 /* Identify the output register */
64913 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
64914 pOut = &aMem[pOp->p3];
64915 memAboutToChange(p, pOut);
64917 /* Loop through the elements that will make up the record to figure
64918 ** out how much space is required for the new record.
64920 for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
64921 assert( memIsValid(u.ao.pRec) );
64922 if( u.ao.zAffinity ){
64923 applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
64925 if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
64926 sqlite3VdbeMemExpandBlob(u.ao.pRec);
64928 u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
64929 u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
64930 u.ao.nData += u.ao.len;
64931 u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
64932 if( u.ao.pRec->flags & MEM_Zero ){
64933 /* Only pure zero-filled BLOBs can be input to this Opcode.
64934 ** We do not allow blobs with a prefix and a zero-filled tail. */
64935 u.ao.nZero += u.ao.pRec->u.nZero;
64936 }else if( u.ao.len ){
64937 u.ao.nZero = 0;
64941 /* Add the initial header varint and total the size */
64942 u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
64943 if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
64944 u.ao.nHdr++;
64946 u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
64947 if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64948 goto too_big;
64951 /* Make sure the output register has a buffer large enough to store
64952 ** the new record. The output register (pOp->p3) is not allowed to
64953 ** be one of the input registers (because the following call to
64954 ** sqlite3VdbeMemGrow() could clobber the value before it is used).
64956 if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
64957 goto no_mem;
64959 u.ao.zNewRecord = (u8 *)pOut->z;
64961 /* Write the record */
64962 u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
64963 for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
64964 u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
64965 u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type); /* serial type */
64967 for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){ /* serial data */
64968 u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
64970 assert( u.ao.i==u.ao.nByte );
64972 assert( pOp->p3>0 && pOp->p3<=p->nMem );
64973 pOut->n = (int)u.ao.nByte;
64974 pOut->flags = MEM_Blob | MEM_Dyn;
64975 pOut->xDel = 0;
64976 if( u.ao.nZero ){
64977 pOut->u.nZero = u.ao.nZero;
64978 pOut->flags |= MEM_Zero;
64980 pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
64981 REGISTER_TRACE(pOp->p3, pOut);
64982 UPDATE_MAX_BLOBSIZE(pOut);
64983 break;
64986 /* Opcode: Count P1 P2 * * *
64988 ** Store the number of entries (an integer value) in the table or index
64989 ** opened by cursor P1 in register P2
64991 #ifndef SQLITE_OMIT_BTREECOUNT
64992 case OP_Count: { /* out2-prerelease */
64993 #if 0 /* local variables moved into u.ap */
64994 i64 nEntry;
64995 BtCursor *pCrsr;
64996 #endif /* local variables moved into u.ap */
64998 u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
64999 if( u.ap.pCrsr ){
65000 rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
65001 }else{
65002 u.ap.nEntry = 0;
65004 pOut->u.i = u.ap.nEntry;
65005 break;
65007 #endif
65009 /* Opcode: Savepoint P1 * * P4 *
65011 ** Open, release or rollback the savepoint named by parameter P4, depending
65012 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
65013 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
65015 case OP_Savepoint: {
65016 #if 0 /* local variables moved into u.aq */
65017 int p1; /* Value of P1 operand */
65018 char *zName; /* Name of savepoint */
65019 int nName;
65020 Savepoint *pNew;
65021 Savepoint *pSavepoint;
65022 Savepoint *pTmp;
65023 int iSavepoint;
65024 int ii;
65025 #endif /* local variables moved into u.aq */
65027 u.aq.p1 = pOp->p1;
65028 u.aq.zName = pOp->p4.z;
65030 /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
65031 ** transaction, then there cannot be any savepoints.
65033 assert( db->pSavepoint==0 || db->autoCommit==0 );
65034 assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
65035 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
65036 assert( checkSavepointCount(db) );
65038 if( u.aq.p1==SAVEPOINT_BEGIN ){
65039 if( db->writeVdbeCnt>0 ){
65040 /* A new savepoint cannot be created if there are active write
65041 ** statements (i.e. open read/write incremental blob handles).
65043 sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
65044 "SQL statements in progress");
65045 rc = SQLITE_BUSY;
65046 }else{
65047 u.aq.nName = sqlite3Strlen30(u.aq.zName);
65049 /* Create a new savepoint structure. */
65050 u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
65051 if( u.aq.pNew ){
65052 u.aq.pNew->zName = (char *)&u.aq.pNew[1];
65053 memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
65055 /* If there is no open transaction, then mark this as a special
65056 ** "transaction savepoint". */
65057 if( db->autoCommit ){
65058 db->autoCommit = 0;
65059 db->isTransactionSavepoint = 1;
65060 }else{
65061 db->nSavepoint++;
65064 /* Link the new savepoint into the database handle's list. */
65065 u.aq.pNew->pNext = db->pSavepoint;
65066 db->pSavepoint = u.aq.pNew;
65067 u.aq.pNew->nDeferredCons = db->nDeferredCons;
65070 }else{
65071 u.aq.iSavepoint = 0;
65073 /* Find the named savepoint. If there is no such savepoint, then an
65074 ** an error is returned to the user. */
65075 for(
65076 u.aq.pSavepoint = db->pSavepoint;
65077 u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
65078 u.aq.pSavepoint = u.aq.pSavepoint->pNext
65080 u.aq.iSavepoint++;
65082 if( !u.aq.pSavepoint ){
65083 sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
65084 rc = SQLITE_ERROR;
65085 }else if(
65086 db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
65088 /* It is not possible to release (commit) a savepoint if there are
65089 ** active write statements. It is not possible to rollback a savepoint
65090 ** if there are any active statements at all.
65092 sqlite3SetString(&p->zErrMsg, db,
65093 "cannot %s savepoint - SQL statements in progress",
65094 (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
65096 rc = SQLITE_BUSY;
65097 }else{
65099 /* Determine whether or not this is a transaction savepoint. If so,
65100 ** and this is a RELEASE command, then the current transaction
65101 ** is committed.
65103 int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
65104 if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
65105 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
65106 goto vdbe_return;
65108 db->autoCommit = 1;
65109 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
65110 p->pc = pc;
65111 db->autoCommit = 0;
65112 p->rc = rc = SQLITE_BUSY;
65113 goto vdbe_return;
65115 db->isTransactionSavepoint = 0;
65116 rc = p->rc;
65117 }else{
65118 u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
65119 for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
65120 rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
65121 if( rc!=SQLITE_OK ){
65122 goto abort_due_to_error;
65125 if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
65126 sqlite3ExpirePreparedStatements(db);
65127 sqlite3ResetInternalSchema(db, -1);
65128 db->flags = (db->flags | SQLITE_InternChanges);
65132 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
65133 ** savepoints nested inside of the savepoint being operated on. */
65134 while( db->pSavepoint!=u.aq.pSavepoint ){
65135 u.aq.pTmp = db->pSavepoint;
65136 db->pSavepoint = u.aq.pTmp->pNext;
65137 sqlite3DbFree(db, u.aq.pTmp);
65138 db->nSavepoint--;
65141 /* If it is a RELEASE, then destroy the savepoint being operated on
65142 ** too. If it is a ROLLBACK TO, then set the number of deferred
65143 ** constraint violations present in the database to the value stored
65144 ** when the savepoint was created. */
65145 if( u.aq.p1==SAVEPOINT_RELEASE ){
65146 assert( u.aq.pSavepoint==db->pSavepoint );
65147 db->pSavepoint = u.aq.pSavepoint->pNext;
65148 sqlite3DbFree(db, u.aq.pSavepoint);
65149 if( !isTransaction ){
65150 db->nSavepoint--;
65152 }else{
65153 db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
65158 break;
65161 /* Opcode: AutoCommit P1 P2 * * *
65163 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
65164 ** back any currently active btree transactions. If there are any active
65165 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
65166 ** there are active writing VMs or active VMs that use shared cache.
65168 ** This instruction causes the VM to halt.
65170 case OP_AutoCommit: {
65171 #if 0 /* local variables moved into u.ar */
65172 int desiredAutoCommit;
65173 int iRollback;
65174 int turnOnAC;
65175 #endif /* local variables moved into u.ar */
65177 u.ar.desiredAutoCommit = pOp->p1;
65178 u.ar.iRollback = pOp->p2;
65179 u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
65180 assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
65181 assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
65182 assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
65184 if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
65185 /* If this instruction implements a ROLLBACK and other VMs are
65186 ** still running, and a transaction is active, return an error indicating
65187 ** that the other VMs must complete first.
65189 sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
65190 "SQL statements in progress");
65191 rc = SQLITE_BUSY;
65192 }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
65193 /* If this instruction implements a COMMIT and other VMs are writing
65194 ** return an error indicating that the other VMs must complete first.
65196 sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
65197 "SQL statements in progress");
65198 rc = SQLITE_BUSY;
65199 }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
65200 if( u.ar.iRollback ){
65201 assert( u.ar.desiredAutoCommit==1 );
65202 sqlite3RollbackAll(db);
65203 db->autoCommit = 1;
65204 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
65205 goto vdbe_return;
65206 }else{
65207 db->autoCommit = (u8)u.ar.desiredAutoCommit;
65208 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
65209 p->pc = pc;
65210 db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
65211 p->rc = rc = SQLITE_BUSY;
65212 goto vdbe_return;
65215 assert( db->nStatement==0 );
65216 sqlite3CloseSavepoints(db);
65217 if( p->rc==SQLITE_OK ){
65218 rc = SQLITE_DONE;
65219 }else{
65220 rc = SQLITE_ERROR;
65222 goto vdbe_return;
65223 }else{
65224 sqlite3SetString(&p->zErrMsg, db,
65225 (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
65226 (u.ar.iRollback)?"cannot rollback - no transaction is active":
65227 "cannot commit - no transaction is active"));
65229 rc = SQLITE_ERROR;
65231 break;
65234 /* Opcode: Transaction P1 P2 * * *
65236 ** Begin a transaction. The transaction ends when a Commit or Rollback
65237 ** opcode is encountered. Depending on the ON CONFLICT setting, the
65238 ** transaction might also be rolled back if an error is encountered.
65240 ** P1 is the index of the database file on which the transaction is
65241 ** started. Index 0 is the main database file and index 1 is the
65242 ** file used for temporary tables. Indices of 2 or more are used for
65243 ** attached databases.
65245 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
65246 ** obtained on the database file when a write-transaction is started. No
65247 ** other process can start another write transaction while this transaction is
65248 ** underway. Starting a write transaction also creates a rollback journal. A
65249 ** write transaction must be started before any changes can be made to the
65250 ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
65251 ** on the file.
65253 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
65254 ** true (this flag is set if the Vdbe may modify more than one row and may
65255 ** throw an ABORT exception), a statement transaction may also be opened.
65256 ** More specifically, a statement transaction is opened iff the database
65257 ** connection is currently not in autocommit mode, or if there are other
65258 ** active statements. A statement transaction allows the affects of this
65259 ** VDBE to be rolled back after an error without having to roll back the
65260 ** entire transaction. If no error is encountered, the statement transaction
65261 ** will automatically commit when the VDBE halts.
65263 ** If P2 is zero, then a read-lock is obtained on the database file.
65265 case OP_Transaction: {
65266 #if 0 /* local variables moved into u.as */
65267 Btree *pBt;
65268 #endif /* local variables moved into u.as */
65270 assert( pOp->p1>=0 && pOp->p1<db->nDb );
65271 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65272 u.as.pBt = db->aDb[pOp->p1].pBt;
65274 if( u.as.pBt ){
65275 rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
65276 if( rc==SQLITE_BUSY ){
65277 p->pc = pc;
65278 p->rc = rc = SQLITE_BUSY;
65279 goto vdbe_return;
65281 if( rc!=SQLITE_OK ){
65282 goto abort_due_to_error;
65285 if( pOp->p2 && p->usesStmtJournal
65286 && (db->autoCommit==0 || db->activeVdbeCnt>1)
65288 assert( sqlite3BtreeIsInTrans(u.as.pBt) );
65289 if( p->iStatement==0 ){
65290 assert( db->nStatement>=0 && db->nSavepoint>=0 );
65291 db->nStatement++;
65292 p->iStatement = db->nSavepoint + db->nStatement;
65294 rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
65296 /* Store the current value of the database handles deferred constraint
65297 ** counter. If the statement transaction needs to be rolled back,
65298 ** the value of this counter needs to be restored too. */
65299 p->nStmtDefCons = db->nDeferredCons;
65302 break;
65305 /* Opcode: ReadCookie P1 P2 P3 * *
65307 ** Read cookie number P3 from database P1 and write it into register P2.
65308 ** P3==1 is the schema version. P3==2 is the database format.
65309 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
65310 ** the main database file and P1==1 is the database file used to store
65311 ** temporary tables.
65313 ** There must be a read-lock on the database (either a transaction
65314 ** must be started or there must be an open cursor) before
65315 ** executing this instruction.
65317 case OP_ReadCookie: { /* out2-prerelease */
65318 #if 0 /* local variables moved into u.at */
65319 int iMeta;
65320 int iDb;
65321 int iCookie;
65322 #endif /* local variables moved into u.at */
65324 u.at.iDb = pOp->p1;
65325 u.at.iCookie = pOp->p3;
65326 assert( pOp->p3<SQLITE_N_BTREE_META );
65327 assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
65328 assert( db->aDb[u.at.iDb].pBt!=0 );
65329 assert( (p->btreeMask & (((yDbMask)1)<<u.at.iDb))!=0 );
65331 sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
65332 pOut->u.i = u.at.iMeta;
65333 break;
65336 /* Opcode: SetCookie P1 P2 P3 * *
65338 ** Write the content of register P3 (interpreted as an integer)
65339 ** into cookie number P2 of database P1. P2==1 is the schema version.
65340 ** P2==2 is the database format. P2==3 is the recommended pager cache
65341 ** size, and so forth. P1==0 is the main database file and P1==1 is the
65342 ** database file used to store temporary tables.
65344 ** A transaction must be started before executing this opcode.
65346 case OP_SetCookie: { /* in3 */
65347 #if 0 /* local variables moved into u.au */
65348 Db *pDb;
65349 #endif /* local variables moved into u.au */
65350 assert( pOp->p2<SQLITE_N_BTREE_META );
65351 assert( pOp->p1>=0 && pOp->p1<db->nDb );
65352 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65353 u.au.pDb = &db->aDb[pOp->p1];
65354 assert( u.au.pDb->pBt!=0 );
65355 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65356 pIn3 = &aMem[pOp->p3];
65357 sqlite3VdbeMemIntegerify(pIn3);
65358 /* See note about index shifting on OP_ReadCookie */
65359 rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
65360 if( pOp->p2==BTREE_SCHEMA_VERSION ){
65361 /* When the schema cookie changes, record the new cookie internally */
65362 u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
65363 db->flags |= SQLITE_InternChanges;
65364 }else if( pOp->p2==BTREE_FILE_FORMAT ){
65365 /* Record changes in the file format */
65366 u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
65368 if( pOp->p1==1 ){
65369 /* Invalidate all prepared statements whenever the TEMP database
65370 ** schema is changed. Ticket #1644 */
65371 sqlite3ExpirePreparedStatements(db);
65372 p->expired = 0;
65374 break;
65377 /* Opcode: VerifyCookie P1 P2 P3 * *
65379 ** Check the value of global database parameter number 0 (the
65380 ** schema version) and make sure it is equal to P2 and that the
65381 ** generation counter on the local schema parse equals P3.
65383 ** P1 is the database number which is 0 for the main database file
65384 ** and 1 for the file holding temporary tables and some higher number
65385 ** for auxiliary databases.
65387 ** The cookie changes its value whenever the database schema changes.
65388 ** This operation is used to detect when that the cookie has changed
65389 ** and that the current process needs to reread the schema.
65391 ** Either a transaction needs to have been started or an OP_Open needs
65392 ** to be executed (to establish a read lock) before this opcode is
65393 ** invoked.
65395 case OP_VerifyCookie: {
65396 #if 0 /* local variables moved into u.av */
65397 int iMeta;
65398 int iGen;
65399 Btree *pBt;
65400 #endif /* local variables moved into u.av */
65402 assert( pOp->p1>=0 && pOp->p1<db->nDb );
65403 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65404 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65405 u.av.pBt = db->aDb[pOp->p1].pBt;
65406 if( u.av.pBt ){
65407 sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
65408 u.av.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
65409 }else{
65410 u.av.iGen = u.av.iMeta = 0;
65412 if( u.av.iMeta!=pOp->p2 || u.av.iGen!=pOp->p3 ){
65413 sqlite3DbFree(db, p->zErrMsg);
65414 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
65415 /* If the schema-cookie from the database file matches the cookie
65416 ** stored with the in-memory representation of the schema, do
65417 ** not reload the schema from the database file.
65419 ** If virtual-tables are in use, this is not just an optimization.
65420 ** Often, v-tables store their data in other SQLite tables, which
65421 ** are queried from within xNext() and other v-table methods using
65422 ** prepared queries. If such a query is out-of-date, we do not want to
65423 ** discard the database schema, as the user code implementing the
65424 ** v-table would have to be ready for the sqlite3_vtab structure itself
65425 ** to be invalidated whenever sqlite3_step() is called from within
65426 ** a v-table method.
65428 if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
65429 sqlite3ResetInternalSchema(db, pOp->p1);
65432 p->expired = 1;
65433 rc = SQLITE_SCHEMA;
65435 break;
65438 /* Opcode: OpenRead P1 P2 P3 P4 P5
65440 ** Open a read-only cursor for the database table whose root page is
65441 ** P2 in a database file. The database file is determined by P3.
65442 ** P3==0 means the main database, P3==1 means the database used for
65443 ** temporary tables, and P3>1 means used the corresponding attached
65444 ** database. Give the new cursor an identifier of P1. The P1
65445 ** values need not be contiguous but all P1 values should be small integers.
65446 ** It is an error for P1 to be negative.
65448 ** If P5!=0 then use the content of register P2 as the root page, not
65449 ** the value of P2 itself.
65451 ** There will be a read lock on the database whenever there is an
65452 ** open cursor. If the database was unlocked prior to this instruction
65453 ** then a read lock is acquired as part of this instruction. A read
65454 ** lock allows other processes to read the database but prohibits
65455 ** any other process from modifying the database. The read lock is
65456 ** released when all cursors are closed. If this instruction attempts
65457 ** to get a read lock but fails, the script terminates with an
65458 ** SQLITE_BUSY error code.
65460 ** The P4 value may be either an integer (P4_INT32) or a pointer to
65461 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
65462 ** structure, then said structure defines the content and collating
65463 ** sequence of the index being opened. Otherwise, if P4 is an integer
65464 ** value, it is set to the number of columns in the table.
65466 ** See also OpenWrite.
65468 /* Opcode: OpenWrite P1 P2 P3 P4 P5
65470 ** Open a read/write cursor named P1 on the table or index whose root
65471 ** page is P2. Or if P5!=0 use the content of register P2 to find the
65472 ** root page.
65474 ** The P4 value may be either an integer (P4_INT32) or a pointer to
65475 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
65476 ** structure, then said structure defines the content and collating
65477 ** sequence of the index being opened. Otherwise, if P4 is an integer
65478 ** value, it is set to the number of columns in the table, or to the
65479 ** largest index of any column of the table that is actually used.
65481 ** This instruction works just like OpenRead except that it opens the cursor
65482 ** in read/write mode. For a given table, there can be one or more read-only
65483 ** cursors or a single read/write cursor but not both.
65485 ** See also OpenRead.
65487 case OP_OpenRead:
65488 case OP_OpenWrite: {
65489 #if 0 /* local variables moved into u.aw */
65490 int nField;
65491 KeyInfo *pKeyInfo;
65492 int p2;
65493 int iDb;
65494 int wrFlag;
65495 Btree *pX;
65496 VdbeCursor *pCur;
65497 Db *pDb;
65498 #endif /* local variables moved into u.aw */
65500 if( p->expired ){
65501 rc = SQLITE_ABORT;
65502 break;
65505 u.aw.nField = 0;
65506 u.aw.pKeyInfo = 0;
65507 u.aw.p2 = pOp->p2;
65508 u.aw.iDb = pOp->p3;
65509 assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
65510 assert( (p->btreeMask & (((yDbMask)1)<<u.aw.iDb))!=0 );
65511 u.aw.pDb = &db->aDb[u.aw.iDb];
65512 u.aw.pX = u.aw.pDb->pBt;
65513 assert( u.aw.pX!=0 );
65514 if( pOp->opcode==OP_OpenWrite ){
65515 u.aw.wrFlag = 1;
65516 assert( sqlite3SchemaMutexHeld(db, u.aw.iDb, 0) );
65517 if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
65518 p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
65520 }else{
65521 u.aw.wrFlag = 0;
65523 if( pOp->p5 ){
65524 assert( u.aw.p2>0 );
65525 assert( u.aw.p2<=p->nMem );
65526 pIn2 = &aMem[u.aw.p2];
65527 assert( memIsValid(pIn2) );
65528 assert( (pIn2->flags & MEM_Int)!=0 );
65529 sqlite3VdbeMemIntegerify(pIn2);
65530 u.aw.p2 = (int)pIn2->u.i;
65531 /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
65532 ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
65533 ** If there were a failure, the prepared statement would have halted
65534 ** before reaching this instruction. */
65535 if( NEVER(u.aw.p2<2) ) {
65536 rc = SQLITE_CORRUPT_BKPT;
65537 goto abort_due_to_error;
65540 if( pOp->p4type==P4_KEYINFO ){
65541 u.aw.pKeyInfo = pOp->p4.pKeyInfo;
65542 u.aw.pKeyInfo->enc = ENC(p->db);
65543 u.aw.nField = u.aw.pKeyInfo->nField+1;
65544 }else if( pOp->p4type==P4_INT32 ){
65545 u.aw.nField = pOp->p4.i;
65547 assert( pOp->p1>=0 );
65548 u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
65549 if( u.aw.pCur==0 ) goto no_mem;
65550 u.aw.pCur->nullRow = 1;
65551 u.aw.pCur->isOrdered = 1;
65552 rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
65553 u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
65555 /* Since it performs no memory allocation or IO, the only values that
65556 ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
65557 ** SQLITE_EMPTY is only returned when attempting to open the table
65558 ** rooted at page 1 of a zero-byte database. */
65559 assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
65560 if( rc==SQLITE_EMPTY ){
65561 u.aw.pCur->pCursor = 0;
65562 rc = SQLITE_OK;
65565 /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
65566 ** SQLite used to check if the root-page flags were sane at this point
65567 ** and report database corruption if they were not, but this check has
65568 ** since moved into the btree layer. */
65569 u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
65570 u.aw.pCur->isIndex = !u.aw.pCur->isTable;
65571 break;
65574 /* Opcode: OpenEphemeral P1 P2 * P4 *
65576 ** Open a new cursor P1 to a transient table.
65577 ** The cursor is always opened read/write even if
65578 ** the main database is read-only. The ephemeral
65579 ** table is deleted automatically when the cursor is closed.
65581 ** P2 is the number of columns in the ephemeral table.
65582 ** The cursor points to a BTree table if P4==0 and to a BTree index
65583 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
65584 ** that defines the format of keys in the index.
65586 ** This opcode was once called OpenTemp. But that created
65587 ** confusion because the term "temp table", might refer either
65588 ** to a TEMP table at the SQL level, or to a table opened by
65589 ** this opcode. Then this opcode was call OpenVirtual. But
65590 ** that created confusion with the whole virtual-table idea.
65592 /* Opcode: OpenAutoindex P1 P2 * P4 *
65594 ** This opcode works the same as OP_OpenEphemeral. It has a
65595 ** different name to distinguish its use. Tables created using
65596 ** by this opcode will be used for automatically created transient
65597 ** indices in joins.
65599 case OP_OpenAutoindex:
65600 case OP_OpenEphemeral: {
65601 #if 0 /* local variables moved into u.ax */
65602 VdbeCursor *pCx;
65603 #endif /* local variables moved into u.ax */
65604 static const int vfsFlags =
65605 SQLITE_OPEN_READWRITE |
65606 SQLITE_OPEN_CREATE |
65607 SQLITE_OPEN_EXCLUSIVE |
65608 SQLITE_OPEN_DELETEONCLOSE |
65609 SQLITE_OPEN_TRANSIENT_DB;
65611 assert( pOp->p1>=0 );
65612 u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
65613 if( u.ax.pCx==0 ) goto no_mem;
65614 u.ax.pCx->nullRow = 1;
65615 rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
65616 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
65617 if( rc==SQLITE_OK ){
65618 rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
65620 if( rc==SQLITE_OK ){
65621 /* If a transient index is required, create it by calling
65622 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
65623 ** opening it. If a transient table is required, just use the
65624 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
65626 if( pOp->p4.pKeyInfo ){
65627 int pgno;
65628 assert( pOp->p4type==P4_KEYINFO );
65629 rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
65630 if( rc==SQLITE_OK ){
65631 assert( pgno==MASTER_ROOT+1 );
65632 rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
65633 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
65634 u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
65635 u.ax.pCx->pKeyInfo->enc = ENC(p->db);
65637 u.ax.pCx->isTable = 0;
65638 }else{
65639 rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
65640 u.ax.pCx->isTable = 1;
65643 u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
65644 u.ax.pCx->isIndex = !u.ax.pCx->isTable;
65645 break;
65648 /* Opcode: OpenPseudo P1 P2 P3 * *
65650 ** Open a new cursor that points to a fake table that contains a single
65651 ** row of data. The content of that one row in the content of memory
65652 ** register P2. In other words, cursor P1 becomes an alias for the
65653 ** MEM_Blob content contained in register P2.
65655 ** A pseudo-table created by this opcode is used to hold a single
65656 ** row output from the sorter so that the row can be decomposed into
65657 ** individual columns using the OP_Column opcode. The OP_Column opcode
65658 ** is the only cursor opcode that works with a pseudo-table.
65660 ** P3 is the number of fields in the records that will be stored by
65661 ** the pseudo-table.
65663 case OP_OpenPseudo: {
65664 #if 0 /* local variables moved into u.ay */
65665 VdbeCursor *pCx;
65666 #endif /* local variables moved into u.ay */
65668 assert( pOp->p1>=0 );
65669 u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
65670 if( u.ay.pCx==0 ) goto no_mem;
65671 u.ay.pCx->nullRow = 1;
65672 u.ay.pCx->pseudoTableReg = pOp->p2;
65673 u.ay.pCx->isTable = 1;
65674 u.ay.pCx->isIndex = 0;
65675 break;
65678 /* Opcode: Close P1 * * * *
65680 ** Close a cursor previously opened as P1. If P1 is not
65681 ** currently open, this instruction is a no-op.
65683 case OP_Close: {
65684 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65685 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
65686 p->apCsr[pOp->p1] = 0;
65687 break;
65690 /* Opcode: SeekGe P1 P2 P3 P4 *
65692 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65693 ** use the value in register P3 as the key. If cursor P1 refers
65694 ** to an SQL index, then P3 is the first in an array of P4 registers
65695 ** that are used as an unpacked index key.
65697 ** Reposition cursor P1 so that it points to the smallest entry that
65698 ** is greater than or equal to the key value. If there are no records
65699 ** greater than or equal to the key and P2 is not zero, then jump to P2.
65701 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
65703 /* Opcode: SeekGt P1 P2 P3 P4 *
65705 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65706 ** use the value in register P3 as a key. If cursor P1 refers
65707 ** to an SQL index, then P3 is the first in an array of P4 registers
65708 ** that are used as an unpacked index key.
65710 ** Reposition cursor P1 so that it points to the smallest entry that
65711 ** is greater than the key value. If there are no records greater than
65712 ** the key and P2 is not zero, then jump to P2.
65714 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
65716 /* Opcode: SeekLt P1 P2 P3 P4 *
65718 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65719 ** use the value in register P3 as a key. If cursor P1 refers
65720 ** to an SQL index, then P3 is the first in an array of P4 registers
65721 ** that are used as an unpacked index key.
65723 ** Reposition cursor P1 so that it points to the largest entry that
65724 ** is less than the key value. If there are no records less than
65725 ** the key and P2 is not zero, then jump to P2.
65727 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
65729 /* Opcode: SeekLe P1 P2 P3 P4 *
65731 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65732 ** use the value in register P3 as a key. If cursor P1 refers
65733 ** to an SQL index, then P3 is the first in an array of P4 registers
65734 ** that are used as an unpacked index key.
65736 ** Reposition cursor P1 so that it points to the largest entry that
65737 ** is less than or equal to the key value. If there are no records
65738 ** less than or equal to the key and P2 is not zero, then jump to P2.
65740 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
65742 case OP_SeekLt: /* jump, in3 */
65743 case OP_SeekLe: /* jump, in3 */
65744 case OP_SeekGe: /* jump, in3 */
65745 case OP_SeekGt: { /* jump, in3 */
65746 #if 0 /* local variables moved into u.az */
65747 int res;
65748 int oc;
65749 VdbeCursor *pC;
65750 UnpackedRecord r;
65751 int nField;
65752 i64 iKey; /* The rowid we are to seek to */
65753 #endif /* local variables moved into u.az */
65755 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65756 assert( pOp->p2!=0 );
65757 u.az.pC = p->apCsr[pOp->p1];
65758 assert( u.az.pC!=0 );
65759 assert( u.az.pC->pseudoTableReg==0 );
65760 assert( OP_SeekLe == OP_SeekLt+1 );
65761 assert( OP_SeekGe == OP_SeekLt+2 );
65762 assert( OP_SeekGt == OP_SeekLt+3 );
65763 assert( u.az.pC->isOrdered );
65764 if( u.az.pC->pCursor!=0 ){
65765 u.az.oc = pOp->opcode;
65766 u.az.pC->nullRow = 0;
65767 if( u.az.pC->isTable ){
65768 /* The input value in P3 might be of any type: integer, real, string,
65769 ** blob, or NULL. But it needs to be an integer before we can do
65770 ** the seek, so covert it. */
65771 pIn3 = &aMem[pOp->p3];
65772 applyNumericAffinity(pIn3);
65773 u.az.iKey = sqlite3VdbeIntValue(pIn3);
65774 u.az.pC->rowidIsValid = 0;
65776 /* If the P3 value could not be converted into an integer without
65777 ** loss of information, then special processing is required... */
65778 if( (pIn3->flags & MEM_Int)==0 ){
65779 if( (pIn3->flags & MEM_Real)==0 ){
65780 /* If the P3 value cannot be converted into any kind of a number,
65781 ** then the seek is not possible, so jump to P2 */
65782 pc = pOp->p2 - 1;
65783 break;
65785 /* If we reach this point, then the P3 value must be a floating
65786 ** point number. */
65787 assert( (pIn3->flags & MEM_Real)!=0 );
65789 if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
65790 /* The P3 value is too large in magnitude to be expressed as an
65791 ** integer. */
65792 u.az.res = 1;
65793 if( pIn3->r<0 ){
65794 if( u.az.oc>=OP_SeekGe ){ assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
65795 rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
65796 if( rc!=SQLITE_OK ) goto abort_due_to_error;
65798 }else{
65799 if( u.az.oc<=OP_SeekLe ){ assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
65800 rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
65801 if( rc!=SQLITE_OK ) goto abort_due_to_error;
65804 if( u.az.res ){
65805 pc = pOp->p2 - 1;
65807 break;
65808 }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
65809 /* Use the ceiling() function to convert real->int */
65810 if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
65811 }else{
65812 /* Use the floor() function to convert real->int */
65813 assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
65814 if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
65817 rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
65818 if( rc!=SQLITE_OK ){
65819 goto abort_due_to_error;
65821 if( u.az.res==0 ){
65822 u.az.pC->rowidIsValid = 1;
65823 u.az.pC->lastRowid = u.az.iKey;
65825 }else{
65826 u.az.nField = pOp->p4.i;
65827 assert( pOp->p4type==P4_INT32 );
65828 assert( u.az.nField>0 );
65829 u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
65830 u.az.r.nField = (u16)u.az.nField;
65832 /* The next line of code computes as follows, only faster:
65833 ** if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
65834 ** u.az.r.flags = UNPACKED_INCRKEY;
65835 ** }else{
65836 ** u.az.r.flags = 0;
65837 ** }
65839 u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
65840 assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
65841 assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
65842 assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
65843 assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
65845 u.az.r.aMem = &aMem[pOp->p3];
65846 #ifdef SQLITE_DEBUG
65847 { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
65848 #endif
65849 ExpandBlob(u.az.r.aMem);
65850 rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
65851 if( rc!=SQLITE_OK ){
65852 goto abort_due_to_error;
65854 u.az.pC->rowidIsValid = 0;
65856 u.az.pC->deferredMoveto = 0;
65857 u.az.pC->cacheStatus = CACHE_STALE;
65858 #ifdef SQLITE_TEST
65859 sqlite3_search_count++;
65860 #endif
65861 if( u.az.oc>=OP_SeekGe ){ assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
65862 if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
65863 rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
65864 if( rc!=SQLITE_OK ) goto abort_due_to_error;
65865 u.az.pC->rowidIsValid = 0;
65866 }else{
65867 u.az.res = 0;
65869 }else{
65870 assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
65871 if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
65872 rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
65873 if( rc!=SQLITE_OK ) goto abort_due_to_error;
65874 u.az.pC->rowidIsValid = 0;
65875 }else{
65876 /* u.az.res might be negative because the table is empty. Check to
65877 ** see if this is the case.
65879 u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
65882 assert( pOp->p2>0 );
65883 if( u.az.res ){
65884 pc = pOp->p2 - 1;
65886 }else{
65887 /* This happens when attempting to open the sqlite3_master table
65888 ** for read access returns SQLITE_EMPTY. In this case always
65889 ** take the jump (since there are no records in the table).
65891 pc = pOp->p2 - 1;
65893 break;
65896 /* Opcode: Seek P1 P2 * * *
65898 ** P1 is an open table cursor and P2 is a rowid integer. Arrange
65899 ** for P1 to move so that it points to the rowid given by P2.
65901 ** This is actually a deferred seek. Nothing actually happens until
65902 ** the cursor is used to read a record. That way, if no reads
65903 ** occur, no unnecessary I/O happens.
65905 case OP_Seek: { /* in2 */
65906 #if 0 /* local variables moved into u.ba */
65907 VdbeCursor *pC;
65908 #endif /* local variables moved into u.ba */
65910 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65911 u.ba.pC = p->apCsr[pOp->p1];
65912 assert( u.ba.pC!=0 );
65913 if( ALWAYS(u.ba.pC->pCursor!=0) ){
65914 assert( u.ba.pC->isTable );
65915 u.ba.pC->nullRow = 0;
65916 pIn2 = &aMem[pOp->p2];
65917 u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
65918 u.ba.pC->rowidIsValid = 0;
65919 u.ba.pC->deferredMoveto = 1;
65921 break;
65925 /* Opcode: Found P1 P2 P3 P4 *
65927 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
65928 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
65929 ** record.
65931 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
65932 ** is a prefix of any entry in P1 then a jump is made to P2 and
65933 ** P1 is left pointing at the matching entry.
65935 /* Opcode: NotFound P1 P2 P3 P4 *
65937 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
65938 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
65939 ** record.
65941 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
65942 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
65943 ** does contain an entry whose prefix matches the P3/P4 record then control
65944 ** falls through to the next instruction and P1 is left pointing at the
65945 ** matching entry.
65947 ** See also: Found, NotExists, IsUnique
65949 case OP_NotFound: /* jump, in3 */
65950 case OP_Found: { /* jump, in3 */
65951 #if 0 /* local variables moved into u.bb */
65952 int alreadyExists;
65953 VdbeCursor *pC;
65954 int res;
65955 UnpackedRecord *pIdxKey;
65956 UnpackedRecord r;
65957 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65958 #endif /* local variables moved into u.bb */
65960 #ifdef SQLITE_TEST
65961 sqlite3_found_count++;
65962 #endif
65964 u.bb.alreadyExists = 0;
65965 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65966 assert( pOp->p4type==P4_INT32 );
65967 u.bb.pC = p->apCsr[pOp->p1];
65968 assert( u.bb.pC!=0 );
65969 pIn3 = &aMem[pOp->p3];
65970 if( ALWAYS(u.bb.pC->pCursor!=0) ){
65972 assert( u.bb.pC->isTable==0 );
65973 if( pOp->p4.i>0 ){
65974 u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
65975 u.bb.r.nField = (u16)pOp->p4.i;
65976 u.bb.r.aMem = pIn3;
65977 #ifdef SQLITE_DEBUG
65978 { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
65979 #endif
65980 u.bb.r.flags = UNPACKED_PREFIX_MATCH;
65981 u.bb.pIdxKey = &u.bb.r;
65982 }else{
65983 assert( pIn3->flags & MEM_Blob );
65984 assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
65985 u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
65986 u.bb.aTempRec, sizeof(u.bb.aTempRec));
65987 if( u.bb.pIdxKey==0 ){
65988 goto no_mem;
65990 u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
65992 rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
65993 if( pOp->p4.i==0 ){
65994 sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
65996 if( rc!=SQLITE_OK ){
65997 break;
65999 u.bb.alreadyExists = (u.bb.res==0);
66000 u.bb.pC->deferredMoveto = 0;
66001 u.bb.pC->cacheStatus = CACHE_STALE;
66003 if( pOp->opcode==OP_Found ){
66004 if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
66005 }else{
66006 if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
66008 break;
66011 /* Opcode: IsUnique P1 P2 P3 P4 *
66013 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
66014 ** no data and where the key are records generated by OP_MakeRecord with
66015 ** the list field being the integer ROWID of the entry that the index
66016 ** entry refers to.
66018 ** The P3 register contains an integer record number. Call this record
66019 ** number R. Register P4 is the first in a set of N contiguous registers
66020 ** that make up an unpacked index key that can be used with cursor P1.
66021 ** The value of N can be inferred from the cursor. N includes the rowid
66022 ** value appended to the end of the index record. This rowid value may
66023 ** or may not be the same as R.
66025 ** If any of the N registers beginning with register P4 contains a NULL
66026 ** value, jump immediately to P2.
66028 ** Otherwise, this instruction checks if cursor P1 contains an entry
66029 ** where the first (N-1) fields match but the rowid value at the end
66030 ** of the index entry is not R. If there is no such entry, control jumps
66031 ** to instruction P2. Otherwise, the rowid of the conflicting index
66032 ** entry is copied to register P3 and control falls through to the next
66033 ** instruction.
66035 ** See also: NotFound, NotExists, Found
66037 case OP_IsUnique: { /* jump, in3 */
66038 #if 0 /* local variables moved into u.bc */
66039 u16 ii;
66040 VdbeCursor *pCx;
66041 BtCursor *pCrsr;
66042 u16 nField;
66043 Mem *aMx;
66044 UnpackedRecord r; /* B-Tree index search key */
66045 i64 R; /* Rowid stored in register P3 */
66046 #endif /* local variables moved into u.bc */
66048 pIn3 = &aMem[pOp->p3];
66049 u.bc.aMx = &aMem[pOp->p4.i];
66050 /* Assert that the values of parameters P1 and P4 are in range. */
66051 assert( pOp->p4type==P4_INT32 );
66052 assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
66053 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66055 /* Find the index cursor. */
66056 u.bc.pCx = p->apCsr[pOp->p1];
66057 assert( u.bc.pCx->deferredMoveto==0 );
66058 u.bc.pCx->seekResult = 0;
66059 u.bc.pCx->cacheStatus = CACHE_STALE;
66060 u.bc.pCrsr = u.bc.pCx->pCursor;
66062 /* If any of the values are NULL, take the jump. */
66063 u.bc.nField = u.bc.pCx->pKeyInfo->nField;
66064 for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
66065 if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
66066 pc = pOp->p2 - 1;
66067 u.bc.pCrsr = 0;
66068 break;
66071 assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
66073 if( u.bc.pCrsr!=0 ){
66074 /* Populate the index search key. */
66075 u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
66076 u.bc.r.nField = u.bc.nField + 1;
66077 u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
66078 u.bc.r.aMem = u.bc.aMx;
66079 #ifdef SQLITE_DEBUG
66080 { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
66081 #endif
66083 /* Extract the value of u.bc.R from register P3. */
66084 sqlite3VdbeMemIntegerify(pIn3);
66085 u.bc.R = pIn3->u.i;
66087 /* Search the B-Tree index. If no conflicting record is found, jump
66088 ** to P2. Otherwise, copy the rowid of the conflicting record to
66089 ** register P3 and fall through to the next instruction. */
66090 rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
66091 if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
66092 pc = pOp->p2 - 1;
66093 }else{
66094 pIn3->u.i = u.bc.r.rowid;
66097 break;
66100 /* Opcode: NotExists P1 P2 P3 * *
66102 ** Use the content of register P3 as a integer key. If a record
66103 ** with that key does not exist in table of P1, then jump to P2.
66104 ** If the record does exist, then fall through. The cursor is left
66105 ** pointing to the record if it exists.
66107 ** The difference between this operation and NotFound is that this
66108 ** operation assumes the key is an integer and that P1 is a table whereas
66109 ** NotFound assumes key is a blob constructed from MakeRecord and
66110 ** P1 is an index.
66112 ** See also: Found, NotFound, IsUnique
66114 case OP_NotExists: { /* jump, in3 */
66115 #if 0 /* local variables moved into u.bd */
66116 VdbeCursor *pC;
66117 BtCursor *pCrsr;
66118 int res;
66119 u64 iKey;
66120 #endif /* local variables moved into u.bd */
66122 pIn3 = &aMem[pOp->p3];
66123 assert( pIn3->flags & MEM_Int );
66124 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66125 u.bd.pC = p->apCsr[pOp->p1];
66126 assert( u.bd.pC!=0 );
66127 assert( u.bd.pC->isTable );
66128 assert( u.bd.pC->pseudoTableReg==0 );
66129 u.bd.pCrsr = u.bd.pC->pCursor;
66130 if( u.bd.pCrsr!=0 ){
66131 u.bd.res = 0;
66132 u.bd.iKey = pIn3->u.i;
66133 rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
66134 u.bd.pC->lastRowid = pIn3->u.i;
66135 u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
66136 u.bd.pC->nullRow = 0;
66137 u.bd.pC->cacheStatus = CACHE_STALE;
66138 u.bd.pC->deferredMoveto = 0;
66139 if( u.bd.res!=0 ){
66140 pc = pOp->p2 - 1;
66141 assert( u.bd.pC->rowidIsValid==0 );
66143 u.bd.pC->seekResult = u.bd.res;
66144 }else{
66145 /* This happens when an attempt to open a read cursor on the
66146 ** sqlite_master table returns SQLITE_EMPTY.
66148 pc = pOp->p2 - 1;
66149 assert( u.bd.pC->rowidIsValid==0 );
66150 u.bd.pC->seekResult = 0;
66152 break;
66155 /* Opcode: Sequence P1 P2 * * *
66157 ** Find the next available sequence number for cursor P1.
66158 ** Write the sequence number into register P2.
66159 ** The sequence number on the cursor is incremented after this
66160 ** instruction.
66162 case OP_Sequence: { /* out2-prerelease */
66163 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66164 assert( p->apCsr[pOp->p1]!=0 );
66165 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
66166 break;
66170 /* Opcode: NewRowid P1 P2 P3 * *
66172 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
66173 ** The record number is not previously used as a key in the database
66174 ** table that cursor P1 points to. The new record number is written
66175 ** written to register P2.
66177 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
66178 ** the largest previously generated record number. No new record numbers are
66179 ** allowed to be less than this value. When this value reaches its maximum,
66180 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
66181 ** generated record number. This P3 mechanism is used to help implement the
66182 ** AUTOINCREMENT feature.
66184 case OP_NewRowid: { /* out2-prerelease */
66185 #if 0 /* local variables moved into u.be */
66186 i64 v; /* The new rowid */
66187 VdbeCursor *pC; /* Cursor of table to get the new rowid */
66188 int res; /* Result of an sqlite3BtreeLast() */
66189 int cnt; /* Counter to limit the number of searches */
66190 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
66191 VdbeFrame *pFrame; /* Root frame of VDBE */
66192 #endif /* local variables moved into u.be */
66194 u.be.v = 0;
66195 u.be.res = 0;
66196 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66197 u.be.pC = p->apCsr[pOp->p1];
66198 assert( u.be.pC!=0 );
66199 if( NEVER(u.be.pC->pCursor==0) ){
66200 /* The zero initialization above is all that is needed */
66201 }else{
66202 /* The next rowid or record number (different terms for the same
66203 ** thing) is obtained in a two-step algorithm.
66205 ** First we attempt to find the largest existing rowid and add one
66206 ** to that. But if the largest existing rowid is already the maximum
66207 ** positive integer, we have to fall through to the second
66208 ** probabilistic algorithm
66210 ** The second algorithm is to select a rowid at random and see if
66211 ** it already exists in the table. If it does not exist, we have
66212 ** succeeded. If the random rowid does exist, we select a new one
66213 ** and try again, up to 100 times.
66215 assert( u.be.pC->isTable );
66217 #ifdef SQLITE_32BIT_ROWID
66218 # define MAX_ROWID 0x7fffffff
66219 #else
66220 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
66221 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
66222 ** to provide the constant while making all compilers happy.
66224 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
66225 #endif
66227 if( !u.be.pC->useRandomRowid ){
66228 u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
66229 if( u.be.v==0 ){
66230 rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
66231 if( rc!=SQLITE_OK ){
66232 goto abort_due_to_error;
66234 if( u.be.res ){
66235 u.be.v = 1; /* IMP: R-61914-48074 */
66236 }else{
66237 assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
66238 rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
66239 assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
66240 if( u.be.v==MAX_ROWID ){
66241 u.be.pC->useRandomRowid = 1;
66242 }else{
66243 u.be.v++; /* IMP: R-29538-34987 */
66248 #ifndef SQLITE_OMIT_AUTOINCREMENT
66249 if( pOp->p3 ){
66250 /* Assert that P3 is a valid memory cell. */
66251 assert( pOp->p3>0 );
66252 if( p->pFrame ){
66253 for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
66254 /* Assert that P3 is a valid memory cell. */
66255 assert( pOp->p3<=u.be.pFrame->nMem );
66256 u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
66257 }else{
66258 /* Assert that P3 is a valid memory cell. */
66259 assert( pOp->p3<=p->nMem );
66260 u.be.pMem = &aMem[pOp->p3];
66261 memAboutToChange(p, u.be.pMem);
66263 assert( memIsValid(u.be.pMem) );
66265 REGISTER_TRACE(pOp->p3, u.be.pMem);
66266 sqlite3VdbeMemIntegerify(u.be.pMem);
66267 assert( (u.be.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
66268 if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
66269 rc = SQLITE_FULL; /* IMP: R-12275-61338 */
66270 goto abort_due_to_error;
66272 if( u.be.v<u.be.pMem->u.i+1 ){
66273 u.be.v = u.be.pMem->u.i + 1;
66275 u.be.pMem->u.i = u.be.v;
66277 #endif
66279 sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
66281 if( u.be.pC->useRandomRowid ){
66282 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
66283 ** largest possible integer (9223372036854775807) then the database
66284 ** engine starts picking positive candidate ROWIDs at random until
66285 ** it finds one that is not previously used. */
66286 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
66287 ** an AUTOINCREMENT table. */
66288 /* on the first attempt, simply do one more than previous */
66289 u.be.v = db->lastRowid;
66290 u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66291 u.be.v++; /* ensure non-zero */
66292 u.be.cnt = 0;
66293 while( ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
66294 0, &u.be.res))==SQLITE_OK)
66295 && (u.be.res==0)
66296 && (++u.be.cnt<100)){
66297 /* collision - try another random rowid */
66298 sqlite3_randomness(sizeof(u.be.v), &u.be.v);
66299 if( u.be.cnt<5 ){
66300 /* try "small" random rowids for the initial attempts */
66301 u.be.v &= 0xffffff;
66302 }else{
66303 u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66305 u.be.v++; /* ensure non-zero */
66307 if( rc==SQLITE_OK && u.be.res==0 ){
66308 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
66309 goto abort_due_to_error;
66311 assert( u.be.v>0 ); /* EV: R-40812-03570 */
66313 u.be.pC->rowidIsValid = 0;
66314 u.be.pC->deferredMoveto = 0;
66315 u.be.pC->cacheStatus = CACHE_STALE;
66317 pOut->u.i = u.be.v;
66318 break;
66321 /* Opcode: Insert P1 P2 P3 P4 P5
66323 ** Write an entry into the table of cursor P1. A new entry is
66324 ** created if it doesn't already exist or the data for an existing
66325 ** entry is overwritten. The data is the value MEM_Blob stored in register
66326 ** number P2. The key is stored in register P3. The key must
66327 ** be a MEM_Int.
66329 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
66330 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
66331 ** then rowid is stored for subsequent return by the
66332 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
66334 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
66335 ** the last seek operation (OP_NotExists) was a success, then this
66336 ** operation will not attempt to find the appropriate row before doing
66337 ** the insert but will instead overwrite the row that the cursor is
66338 ** currently pointing to. Presumably, the prior OP_NotExists opcode
66339 ** has already positioned the cursor correctly. This is an optimization
66340 ** that boosts performance by avoiding redundant seeks.
66342 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
66343 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
66344 ** is part of an INSERT operation. The difference is only important to
66345 ** the update hook.
66347 ** Parameter P4 may point to a string containing the table-name, or
66348 ** may be NULL. If it is not NULL, then the update-hook
66349 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
66351 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
66352 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
66353 ** and register P2 becomes ephemeral. If the cursor is changed, the
66354 ** value of register P2 will then change. Make sure this does not
66355 ** cause any problems.)
66357 ** This instruction only works on tables. The equivalent instruction
66358 ** for indices is OP_IdxInsert.
66360 /* Opcode: InsertInt P1 P2 P3 P4 P5
66362 ** This works exactly like OP_Insert except that the key is the
66363 ** integer value P3, not the value of the integer stored in register P3.
66365 case OP_Insert:
66366 case OP_InsertInt: {
66367 #if 0 /* local variables moved into u.bf */
66368 Mem *pData; /* MEM cell holding data for the record to be inserted */
66369 Mem *pKey; /* MEM cell holding key for the record */
66370 i64 iKey; /* The integer ROWID or key for the record to be inserted */
66371 VdbeCursor *pC; /* Cursor to table into which insert is written */
66372 int nZero; /* Number of zero-bytes to append */
66373 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
66374 const char *zDb; /* database name - used by the update hook */
66375 const char *zTbl; /* Table name - used by the opdate hook */
66376 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
66377 #endif /* local variables moved into u.bf */
66379 u.bf.pData = &aMem[pOp->p2];
66380 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66381 assert( memIsValid(u.bf.pData) );
66382 u.bf.pC = p->apCsr[pOp->p1];
66383 assert( u.bf.pC!=0 );
66384 assert( u.bf.pC->pCursor!=0 );
66385 assert( u.bf.pC->pseudoTableReg==0 );
66386 assert( u.bf.pC->isTable );
66387 REGISTER_TRACE(pOp->p2, u.bf.pData);
66389 if( pOp->opcode==OP_Insert ){
66390 u.bf.pKey = &aMem[pOp->p3];
66391 assert( u.bf.pKey->flags & MEM_Int );
66392 assert( memIsValid(u.bf.pKey) );
66393 REGISTER_TRACE(pOp->p3, u.bf.pKey);
66394 u.bf.iKey = u.bf.pKey->u.i;
66395 }else{
66396 assert( pOp->opcode==OP_InsertInt );
66397 u.bf.iKey = pOp->p3;
66400 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
66401 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
66402 if( u.bf.pData->flags & MEM_Null ){
66403 u.bf.pData->z = 0;
66404 u.bf.pData->n = 0;
66405 }else{
66406 assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
66408 u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
66409 if( u.bf.pData->flags & MEM_Zero ){
66410 u.bf.nZero = u.bf.pData->u.nZero;
66411 }else{
66412 u.bf.nZero = 0;
66414 sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
66415 rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
66416 u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
66417 pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
66419 u.bf.pC->rowidIsValid = 0;
66420 u.bf.pC->deferredMoveto = 0;
66421 u.bf.pC->cacheStatus = CACHE_STALE;
66423 /* Invoke the update-hook if required. */
66424 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66425 u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
66426 u.bf.zTbl = pOp->p4.z;
66427 u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
66428 assert( u.bf.pC->isTable );
66429 db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
66430 assert( u.bf.pC->iDb>=0 );
66432 break;
66435 /* Opcode: Delete P1 P2 * P4 *
66437 ** Delete the record at which the P1 cursor is currently pointing.
66439 ** The cursor will be left pointing at either the next or the previous
66440 ** record in the table. If it is left pointing at the next record, then
66441 ** the next Next instruction will be a no-op. Hence it is OK to delete
66442 ** a record from within an Next loop.
66444 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
66445 ** incremented (otherwise not).
66447 ** P1 must not be pseudo-table. It has to be a real table with
66448 ** multiple rows.
66450 ** If P4 is not NULL, then it is the name of the table that P1 is
66451 ** pointing to. The update hook will be invoked, if it exists.
66452 ** If P4 is not NULL then the P1 cursor must have been positioned
66453 ** using OP_NotFound prior to invoking this opcode.
66455 case OP_Delete: {
66456 #if 0 /* local variables moved into u.bg */
66457 i64 iKey;
66458 VdbeCursor *pC;
66459 #endif /* local variables moved into u.bg */
66461 u.bg.iKey = 0;
66462 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66463 u.bg.pC = p->apCsr[pOp->p1];
66464 assert( u.bg.pC!=0 );
66465 assert( u.bg.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
66467 /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
66468 ** row being deleted.
66470 if( db->xUpdateCallback && pOp->p4.z ){
66471 assert( u.bg.pC->isTable );
66472 assert( u.bg.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
66473 u.bg.iKey = u.bg.pC->lastRowid;
66476 /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
66477 ** OP_Column on the same table without any intervening operations that
66478 ** might move or invalidate the cursor. Hence cursor u.bg.pC is always pointing
66479 ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
66480 ** below is always a no-op and cannot fail. We will run it anyhow, though,
66481 ** to guard against future changes to the code generator.
66483 assert( u.bg.pC->deferredMoveto==0 );
66484 rc = sqlite3VdbeCursorMoveto(u.bg.pC);
66485 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66487 sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
66488 rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
66489 u.bg.pC->cacheStatus = CACHE_STALE;
66491 /* Invoke the update-hook if required. */
66492 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66493 const char *zDb = db->aDb[u.bg.pC->iDb].zName;
66494 const char *zTbl = pOp->p4.z;
66495 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
66496 assert( u.bg.pC->iDb>=0 );
66498 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
66499 break;
66501 /* Opcode: ResetCount * * * * *
66503 ** The value of the change counter is copied to the database handle
66504 ** change counter (returned by subsequent calls to sqlite3_changes()).
66505 ** Then the VMs internal change counter resets to 0.
66506 ** This is used by trigger programs.
66508 case OP_ResetCount: {
66509 sqlite3VdbeSetChanges(db, p->nChange);
66510 p->nChange = 0;
66511 break;
66514 /* Opcode: RowData P1 P2 * * *
66516 ** Write into register P2 the complete row data for cursor P1.
66517 ** There is no interpretation of the data.
66518 ** It is just copied onto the P2 register exactly as
66519 ** it is found in the database file.
66521 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
66522 ** of a real table, not a pseudo-table.
66524 /* Opcode: RowKey P1 P2 * * *
66526 ** Write into register P2 the complete row key for cursor P1.
66527 ** There is no interpretation of the data.
66528 ** The key is copied onto the P3 register exactly as
66529 ** it is found in the database file.
66531 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
66532 ** of a real table, not a pseudo-table.
66534 case OP_RowKey:
66535 case OP_RowData: {
66536 #if 0 /* local variables moved into u.bh */
66537 VdbeCursor *pC;
66538 BtCursor *pCrsr;
66539 u32 n;
66540 i64 n64;
66541 #endif /* local variables moved into u.bh */
66543 pOut = &aMem[pOp->p2];
66544 memAboutToChange(p, pOut);
66546 /* Note that RowKey and RowData are really exactly the same instruction */
66547 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66548 u.bh.pC = p->apCsr[pOp->p1];
66549 assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
66550 assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
66551 assert( u.bh.pC!=0 );
66552 assert( u.bh.pC->nullRow==0 );
66553 assert( u.bh.pC->pseudoTableReg==0 );
66554 assert( u.bh.pC->pCursor!=0 );
66555 u.bh.pCrsr = u.bh.pC->pCursor;
66556 assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
66558 /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
66559 ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
66560 ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
66561 ** a no-op and can never fail. But we leave it in place as a safety.
66563 assert( u.bh.pC->deferredMoveto==0 );
66564 rc = sqlite3VdbeCursorMoveto(u.bh.pC);
66565 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66567 if( u.bh.pC->isIndex ){
66568 assert( !u.bh.pC->isTable );
66569 rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
66570 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
66571 if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66572 goto too_big;
66574 u.bh.n = (u32)u.bh.n64;
66575 }else{
66576 rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
66577 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
66578 if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
66579 goto too_big;
66582 if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
66583 goto no_mem;
66585 pOut->n = u.bh.n;
66586 MemSetTypeFlag(pOut, MEM_Blob);
66587 if( u.bh.pC->isIndex ){
66588 rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66589 }else{
66590 rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66592 pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
66593 UPDATE_MAX_BLOBSIZE(pOut);
66594 break;
66597 /* Opcode: Rowid P1 P2 * * *
66599 ** Store in register P2 an integer which is the key of the table entry that
66600 ** P1 is currently point to.
66602 ** P1 can be either an ordinary table or a virtual table. There used to
66603 ** be a separate OP_VRowid opcode for use with virtual tables, but this
66604 ** one opcode now works for both table types.
66606 case OP_Rowid: { /* out2-prerelease */
66607 #if 0 /* local variables moved into u.bi */
66608 VdbeCursor *pC;
66609 i64 v;
66610 sqlite3_vtab *pVtab;
66611 const sqlite3_module *pModule;
66612 #endif /* local variables moved into u.bi */
66614 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66615 u.bi.pC = p->apCsr[pOp->p1];
66616 assert( u.bi.pC!=0 );
66617 assert( u.bi.pC->pseudoTableReg==0 );
66618 if( u.bi.pC->nullRow ){
66619 pOut->flags = MEM_Null;
66620 break;
66621 }else if( u.bi.pC->deferredMoveto ){
66622 u.bi.v = u.bi.pC->movetoTarget;
66623 #ifndef SQLITE_OMIT_VIRTUALTABLE
66624 }else if( u.bi.pC->pVtabCursor ){
66625 u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
66626 u.bi.pModule = u.bi.pVtab->pModule;
66627 assert( u.bi.pModule->xRowid );
66628 rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
66629 importVtabErrMsg(p, u.bi.pVtab);
66630 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66631 }else{
66632 assert( u.bi.pC->pCursor!=0 );
66633 rc = sqlite3VdbeCursorMoveto(u.bi.pC);
66634 if( rc ) goto abort_due_to_error;
66635 if( u.bi.pC->rowidIsValid ){
66636 u.bi.v = u.bi.pC->lastRowid;
66637 }else{
66638 rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
66639 assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
66642 pOut->u.i = u.bi.v;
66643 break;
66646 /* Opcode: NullRow P1 * * * *
66648 ** Move the cursor P1 to a null row. Any OP_Column operations
66649 ** that occur while the cursor is on the null row will always
66650 ** write a NULL.
66652 case OP_NullRow: {
66653 #if 0 /* local variables moved into u.bj */
66654 VdbeCursor *pC;
66655 #endif /* local variables moved into u.bj */
66657 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66658 u.bj.pC = p->apCsr[pOp->p1];
66659 assert( u.bj.pC!=0 );
66660 u.bj.pC->nullRow = 1;
66661 u.bj.pC->rowidIsValid = 0;
66662 if( u.bj.pC->pCursor ){
66663 sqlite3BtreeClearCursor(u.bj.pC->pCursor);
66665 break;
66668 /* Opcode: Last P1 P2 * * *
66670 ** The next use of the Rowid or Column or Next instruction for P1
66671 ** will refer to the last entry in the database table or index.
66672 ** If the table or index is empty and P2>0, then jump immediately to P2.
66673 ** If P2 is 0 or if the table or index is not empty, fall through
66674 ** to the following instruction.
66676 case OP_Last: { /* jump */
66677 #if 0 /* local variables moved into u.bk */
66678 VdbeCursor *pC;
66679 BtCursor *pCrsr;
66680 int res;
66681 #endif /* local variables moved into u.bk */
66683 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66684 u.bk.pC = p->apCsr[pOp->p1];
66685 assert( u.bk.pC!=0 );
66686 u.bk.pCrsr = u.bk.pC->pCursor;
66687 if( u.bk.pCrsr==0 ){
66688 u.bk.res = 1;
66689 }else{
66690 rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
66692 u.bk.pC->nullRow = (u8)u.bk.res;
66693 u.bk.pC->deferredMoveto = 0;
66694 u.bk.pC->rowidIsValid = 0;
66695 u.bk.pC->cacheStatus = CACHE_STALE;
66696 if( pOp->p2>0 && u.bk.res ){
66697 pc = pOp->p2 - 1;
66699 break;
66703 /* Opcode: Sort P1 P2 * * *
66705 ** This opcode does exactly the same thing as OP_Rewind except that
66706 ** it increments an undocumented global variable used for testing.
66708 ** Sorting is accomplished by writing records into a sorting index,
66709 ** then rewinding that index and playing it back from beginning to
66710 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
66711 ** rewinding so that the global variable will be incremented and
66712 ** regression tests can determine whether or not the optimizer is
66713 ** correctly optimizing out sorts.
66715 case OP_Sort: { /* jump */
66716 #ifdef SQLITE_TEST
66717 sqlite3_sort_count++;
66718 sqlite3_search_count--;
66719 #endif
66720 p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
66721 /* Fall through into OP_Rewind */
66723 /* Opcode: Rewind P1 P2 * * *
66725 ** The next use of the Rowid or Column or Next instruction for P1
66726 ** will refer to the first entry in the database table or index.
66727 ** If the table or index is empty and P2>0, then jump immediately to P2.
66728 ** If P2 is 0 or if the table or index is not empty, fall through
66729 ** to the following instruction.
66731 case OP_Rewind: { /* jump */
66732 #if 0 /* local variables moved into u.bl */
66733 VdbeCursor *pC;
66734 BtCursor *pCrsr;
66735 int res;
66736 #endif /* local variables moved into u.bl */
66738 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66739 u.bl.pC = p->apCsr[pOp->p1];
66740 assert( u.bl.pC!=0 );
66741 u.bl.res = 1;
66742 if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
66743 rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
66744 u.bl.pC->atFirst = u.bl.res==0 ?1:0;
66745 u.bl.pC->deferredMoveto = 0;
66746 u.bl.pC->cacheStatus = CACHE_STALE;
66747 u.bl.pC->rowidIsValid = 0;
66749 u.bl.pC->nullRow = (u8)u.bl.res;
66750 assert( pOp->p2>0 && pOp->p2<p->nOp );
66751 if( u.bl.res ){
66752 pc = pOp->p2 - 1;
66754 break;
66757 /* Opcode: Next P1 P2 * * P5
66759 ** Advance cursor P1 so that it points to the next key/data pair in its
66760 ** table or index. If there are no more key/value pairs then fall through
66761 ** to the following instruction. But if the cursor advance was successful,
66762 ** jump immediately to P2.
66764 ** The P1 cursor must be for a real table, not a pseudo-table.
66766 ** If P5 is positive and the jump is taken, then event counter
66767 ** number P5-1 in the prepared statement is incremented.
66769 ** See also: Prev
66771 /* Opcode: Prev P1 P2 * * P5
66773 ** Back up cursor P1 so that it points to the previous key/data pair in its
66774 ** table or index. If there is no previous key/value pairs then fall through
66775 ** to the following instruction. But if the cursor backup was successful,
66776 ** jump immediately to P2.
66778 ** The P1 cursor must be for a real table, not a pseudo-table.
66780 ** If P5 is positive and the jump is taken, then event counter
66781 ** number P5-1 in the prepared statement is incremented.
66783 case OP_Prev: /* jump */
66784 case OP_Next: { /* jump */
66785 #if 0 /* local variables moved into u.bm */
66786 VdbeCursor *pC;
66787 BtCursor *pCrsr;
66788 int res;
66789 #endif /* local variables moved into u.bm */
66791 CHECK_FOR_INTERRUPT;
66792 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66793 assert( pOp->p5<=ArraySize(p->aCounter) );
66794 u.bm.pC = p->apCsr[pOp->p1];
66795 if( u.bm.pC==0 ){
66796 break; /* See ticket #2273 */
66798 u.bm.pCrsr = u.bm.pC->pCursor;
66799 if( u.bm.pCrsr==0 ){
66800 u.bm.pC->nullRow = 1;
66801 break;
66803 u.bm.res = 1;
66804 assert( u.bm.pC->deferredMoveto==0 );
66805 rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
66806 sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
66807 u.bm.pC->nullRow = (u8)u.bm.res;
66808 u.bm.pC->cacheStatus = CACHE_STALE;
66809 if( u.bm.res==0 ){
66810 pc = pOp->p2 - 1;
66811 if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
66812 #ifdef SQLITE_TEST
66813 sqlite3_search_count++;
66814 #endif
66816 u.bm.pC->rowidIsValid = 0;
66817 break;
66820 /* Opcode: IdxInsert P1 P2 P3 * P5
66822 ** Register P2 holds a SQL index key made using the
66823 ** MakeRecord instructions. This opcode writes that key
66824 ** into the index P1. Data for the entry is nil.
66826 ** P3 is a flag that provides a hint to the b-tree layer that this
66827 ** insert is likely to be an append.
66829 ** This instruction only works for indices. The equivalent instruction
66830 ** for tables is OP_Insert.
66832 case OP_IdxInsert: { /* in2 */
66833 #if 0 /* local variables moved into u.bn */
66834 VdbeCursor *pC;
66835 BtCursor *pCrsr;
66836 int nKey;
66837 const char *zKey;
66838 #endif /* local variables moved into u.bn */
66840 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66841 u.bn.pC = p->apCsr[pOp->p1];
66842 assert( u.bn.pC!=0 );
66843 pIn2 = &aMem[pOp->p2];
66844 assert( pIn2->flags & MEM_Blob );
66845 u.bn.pCrsr = u.bn.pC->pCursor;
66846 if( ALWAYS(u.bn.pCrsr!=0) ){
66847 assert( u.bn.pC->isTable==0 );
66848 rc = ExpandBlob(pIn2);
66849 if( rc==SQLITE_OK ){
66850 u.bn.nKey = pIn2->n;
66851 u.bn.zKey = pIn2->z;
66852 rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
66853 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
66855 assert( u.bn.pC->deferredMoveto==0 );
66856 u.bn.pC->cacheStatus = CACHE_STALE;
66859 break;
66862 /* Opcode: IdxDelete P1 P2 P3 * *
66864 ** The content of P3 registers starting at register P2 form
66865 ** an unpacked index key. This opcode removes that entry from the
66866 ** index opened by cursor P1.
66868 case OP_IdxDelete: {
66869 #if 0 /* local variables moved into u.bo */
66870 VdbeCursor *pC;
66871 BtCursor *pCrsr;
66872 int res;
66873 UnpackedRecord r;
66874 #endif /* local variables moved into u.bo */
66876 assert( pOp->p3>0 );
66877 assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
66878 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66879 u.bo.pC = p->apCsr[pOp->p1];
66880 assert( u.bo.pC!=0 );
66881 u.bo.pCrsr = u.bo.pC->pCursor;
66882 if( ALWAYS(u.bo.pCrsr!=0) ){
66883 u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
66884 u.bo.r.nField = (u16)pOp->p3;
66885 u.bo.r.flags = 0;
66886 u.bo.r.aMem = &aMem[pOp->p2];
66887 #ifdef SQLITE_DEBUG
66888 { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
66889 #endif
66890 rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
66891 if( rc==SQLITE_OK && u.bo.res==0 ){
66892 rc = sqlite3BtreeDelete(u.bo.pCrsr);
66894 assert( u.bo.pC->deferredMoveto==0 );
66895 u.bo.pC->cacheStatus = CACHE_STALE;
66897 break;
66900 /* Opcode: IdxRowid P1 P2 * * *
66902 ** Write into register P2 an integer which is the last entry in the record at
66903 ** the end of the index key pointed to by cursor P1. This integer should be
66904 ** the rowid of the table entry to which this index entry points.
66906 ** See also: Rowid, MakeRecord.
66908 case OP_IdxRowid: { /* out2-prerelease */
66909 #if 0 /* local variables moved into u.bp */
66910 BtCursor *pCrsr;
66911 VdbeCursor *pC;
66912 i64 rowid;
66913 #endif /* local variables moved into u.bp */
66915 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66916 u.bp.pC = p->apCsr[pOp->p1];
66917 assert( u.bp.pC!=0 );
66918 u.bp.pCrsr = u.bp.pC->pCursor;
66919 pOut->flags = MEM_Null;
66920 if( ALWAYS(u.bp.pCrsr!=0) ){
66921 rc = sqlite3VdbeCursorMoveto(u.bp.pC);
66922 if( NEVER(rc) ) goto abort_due_to_error;
66923 assert( u.bp.pC->deferredMoveto==0 );
66924 assert( u.bp.pC->isTable==0 );
66925 if( !u.bp.pC->nullRow ){
66926 rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
66927 if( rc!=SQLITE_OK ){
66928 goto abort_due_to_error;
66930 pOut->u.i = u.bp.rowid;
66931 pOut->flags = MEM_Int;
66934 break;
66937 /* Opcode: IdxGE P1 P2 P3 P4 P5
66939 ** The P4 register values beginning with P3 form an unpacked index
66940 ** key that omits the ROWID. Compare this key value against the index
66941 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
66943 ** If the P1 index entry is greater than or equal to the key value
66944 ** then jump to P2. Otherwise fall through to the next instruction.
66946 ** If P5 is non-zero then the key value is increased by an epsilon
66947 ** prior to the comparison. This make the opcode work like IdxGT except
66948 ** that if the key from register P3 is a prefix of the key in the cursor,
66949 ** the result is false whereas it would be true with IdxGT.
66951 /* Opcode: IdxLT P1 P2 P3 P4 P5
66953 ** The P4 register values beginning with P3 form an unpacked index
66954 ** key that omits the ROWID. Compare this key value against the index
66955 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
66957 ** If the P1 index entry is less than the key value then jump to P2.
66958 ** Otherwise fall through to the next instruction.
66960 ** If P5 is non-zero then the key value is increased by an epsilon prior
66961 ** to the comparison. This makes the opcode work like IdxLE.
66963 case OP_IdxLT: /* jump */
66964 case OP_IdxGE: { /* jump */
66965 #if 0 /* local variables moved into u.bq */
66966 VdbeCursor *pC;
66967 int res;
66968 UnpackedRecord r;
66969 #endif /* local variables moved into u.bq */
66971 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66972 u.bq.pC = p->apCsr[pOp->p1];
66973 assert( u.bq.pC!=0 );
66974 assert( u.bq.pC->isOrdered );
66975 if( ALWAYS(u.bq.pC->pCursor!=0) ){
66976 assert( u.bq.pC->deferredMoveto==0 );
66977 assert( pOp->p5==0 || pOp->p5==1 );
66978 assert( pOp->p4type==P4_INT32 );
66979 u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
66980 u.bq.r.nField = (u16)pOp->p4.i;
66981 if( pOp->p5 ){
66982 u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
66983 }else{
66984 u.bq.r.flags = UNPACKED_IGNORE_ROWID;
66986 u.bq.r.aMem = &aMem[pOp->p3];
66987 #ifdef SQLITE_DEBUG
66988 { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
66989 #endif
66990 rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
66991 if( pOp->opcode==OP_IdxLT ){
66992 u.bq.res = -u.bq.res;
66993 }else{
66994 assert( pOp->opcode==OP_IdxGE );
66995 u.bq.res++;
66997 if( u.bq.res>0 ){
66998 pc = pOp->p2 - 1 ;
67001 break;
67004 /* Opcode: Destroy P1 P2 P3 * *
67006 ** Delete an entire database table or index whose root page in the database
67007 ** file is given by P1.
67009 ** The table being destroyed is in the main database file if P3==0. If
67010 ** P3==1 then the table to be clear is in the auxiliary database file
67011 ** that is used to store tables create using CREATE TEMPORARY TABLE.
67013 ** If AUTOVACUUM is enabled then it is possible that another root page
67014 ** might be moved into the newly deleted root page in order to keep all
67015 ** root pages contiguous at the beginning of the database. The former
67016 ** value of the root page that moved - its value before the move occurred -
67017 ** is stored in register P2. If no page
67018 ** movement was required (because the table being dropped was already
67019 ** the last one in the database) then a zero is stored in register P2.
67020 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
67022 ** See also: Clear
67024 case OP_Destroy: { /* out2-prerelease */
67025 #if 0 /* local variables moved into u.br */
67026 int iMoved;
67027 int iCnt;
67028 Vdbe *pVdbe;
67029 int iDb;
67030 #endif /* local variables moved into u.br */
67031 #ifndef SQLITE_OMIT_VIRTUALTABLE
67032 u.br.iCnt = 0;
67033 for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
67034 if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
67035 u.br.iCnt++;
67038 #else
67039 u.br.iCnt = db->activeVdbeCnt;
67040 #endif
67041 pOut->flags = MEM_Null;
67042 if( u.br.iCnt>1 ){
67043 rc = SQLITE_LOCKED;
67044 p->errorAction = OE_Abort;
67045 }else{
67046 u.br.iDb = pOp->p3;
67047 assert( u.br.iCnt==1 );
67048 assert( (p->btreeMask & (((yDbMask)1)<<u.br.iDb))!=0 );
67049 rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
67050 pOut->flags = MEM_Int;
67051 pOut->u.i = u.br.iMoved;
67052 #ifndef SQLITE_OMIT_AUTOVACUUM
67053 if( rc==SQLITE_OK && u.br.iMoved!=0 ){
67054 sqlite3RootPageMoved(db, u.br.iDb, u.br.iMoved, pOp->p1);
67055 /* All OP_Destroy operations occur on the same btree */
67056 assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.br.iDb+1 );
67057 resetSchemaOnFault = u.br.iDb+1;
67059 #endif
67061 break;
67064 /* Opcode: Clear P1 P2 P3
67066 ** Delete all contents of the database table or index whose root page
67067 ** in the database file is given by P1. But, unlike Destroy, do not
67068 ** remove the table or index from the database file.
67070 ** The table being clear is in the main database file if P2==0. If
67071 ** P2==1 then the table to be clear is in the auxiliary database file
67072 ** that is used to store tables create using CREATE TEMPORARY TABLE.
67074 ** If the P3 value is non-zero, then the table referred to must be an
67075 ** intkey table (an SQL table, not an index). In this case the row change
67076 ** count is incremented by the number of rows in the table being cleared.
67077 ** If P3 is greater than zero, then the value stored in register P3 is
67078 ** also incremented by the number of rows in the table being cleared.
67080 ** See also: Destroy
67082 case OP_Clear: {
67083 #if 0 /* local variables moved into u.bs */
67084 int nChange;
67085 #endif /* local variables moved into u.bs */
67087 u.bs.nChange = 0;
67088 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
67089 rc = sqlite3BtreeClearTable(
67090 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
67092 if( pOp->p3 ){
67093 p->nChange += u.bs.nChange;
67094 if( pOp->p3>0 ){
67095 assert( memIsValid(&aMem[pOp->p3]) );
67096 memAboutToChange(p, &aMem[pOp->p3]);
67097 aMem[pOp->p3].u.i += u.bs.nChange;
67100 break;
67103 /* Opcode: CreateTable P1 P2 * * *
67105 ** Allocate a new table in the main database file if P1==0 or in the
67106 ** auxiliary database file if P1==1 or in an attached database if
67107 ** P1>1. Write the root page number of the new table into
67108 ** register P2
67110 ** The difference between a table and an index is this: A table must
67111 ** have a 4-byte integer key and can have arbitrary data. An index
67112 ** has an arbitrary key but no data.
67114 ** See also: CreateIndex
67116 /* Opcode: CreateIndex P1 P2 * * *
67118 ** Allocate a new index in the main database file if P1==0 or in the
67119 ** auxiliary database file if P1==1 or in an attached database if
67120 ** P1>1. Write the root page number of the new table into
67121 ** register P2.
67123 ** See documentation on OP_CreateTable for additional information.
67125 case OP_CreateIndex: /* out2-prerelease */
67126 case OP_CreateTable: { /* out2-prerelease */
67127 #if 0 /* local variables moved into u.bt */
67128 int pgno;
67129 int flags;
67130 Db *pDb;
67131 #endif /* local variables moved into u.bt */
67133 u.bt.pgno = 0;
67134 assert( pOp->p1>=0 && pOp->p1<db->nDb );
67135 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67136 u.bt.pDb = &db->aDb[pOp->p1];
67137 assert( u.bt.pDb->pBt!=0 );
67138 if( pOp->opcode==OP_CreateTable ){
67139 /* u.bt.flags = BTREE_INTKEY; */
67140 u.bt.flags = BTREE_INTKEY;
67141 }else{
67142 u.bt.flags = BTREE_BLOBKEY;
67144 rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
67145 pOut->u.i = u.bt.pgno;
67146 break;
67149 /* Opcode: ParseSchema P1 * * P4 *
67151 ** Read and parse all entries from the SQLITE_MASTER table of database P1
67152 ** that match the WHERE clause P4.
67154 ** This opcode invokes the parser to create a new virtual machine,
67155 ** then runs the new virtual machine. It is thus a re-entrant opcode.
67157 case OP_ParseSchema: {
67158 #if 0 /* local variables moved into u.bu */
67159 int iDb;
67160 const char *zMaster;
67161 char *zSql;
67162 InitData initData;
67163 #endif /* local variables moved into u.bu */
67165 /* Any prepared statement that invokes this opcode will hold mutexes
67166 ** on every btree. This is a prerequisite for invoking
67167 ** sqlite3InitCallback().
67169 #ifdef SQLITE_DEBUG
67170 for(u.bu.iDb=0; u.bu.iDb<db->nDb; u.bu.iDb++){
67171 assert( u.bu.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
67173 #endif
67175 u.bu.iDb = pOp->p1;
67176 assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
67177 assert( DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) );
67178 /* Used to be a conditional */ {
67179 u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
67180 u.bu.initData.db = db;
67181 u.bu.initData.iDb = pOp->p1;
67182 u.bu.initData.pzErrMsg = &p->zErrMsg;
67183 u.bu.zSql = sqlite3MPrintf(db,
67184 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
67185 db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
67186 if( u.bu.zSql==0 ){
67187 rc = SQLITE_NOMEM;
67188 }else{
67189 assert( db->init.busy==0 );
67190 db->init.busy = 1;
67191 u.bu.initData.rc = SQLITE_OK;
67192 assert( !db->mallocFailed );
67193 rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
67194 if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
67195 sqlite3DbFree(db, u.bu.zSql);
67196 db->init.busy = 0;
67199 if( rc==SQLITE_NOMEM ){
67200 goto no_mem;
67202 break;
67205 #if !defined(SQLITE_OMIT_ANALYZE)
67206 /* Opcode: LoadAnalysis P1 * * * *
67208 ** Read the sqlite_stat1 table for database P1 and load the content
67209 ** of that table into the internal index hash table. This will cause
67210 ** the analysis to be used when preparing all subsequent queries.
67212 case OP_LoadAnalysis: {
67213 assert( pOp->p1>=0 && pOp->p1<db->nDb );
67214 rc = sqlite3AnalysisLoad(db, pOp->p1);
67215 break;
67217 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
67219 /* Opcode: DropTable P1 * * P4 *
67221 ** Remove the internal (in-memory) data structures that describe
67222 ** the table named P4 in database P1. This is called after a table
67223 ** is dropped in order to keep the internal representation of the
67224 ** schema consistent with what is on disk.
67226 case OP_DropTable: {
67227 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
67228 break;
67231 /* Opcode: DropIndex P1 * * P4 *
67233 ** Remove the internal (in-memory) data structures that describe
67234 ** the index named P4 in database P1. This is called after an index
67235 ** is dropped in order to keep the internal representation of the
67236 ** schema consistent with what is on disk.
67238 case OP_DropIndex: {
67239 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
67240 break;
67243 /* Opcode: DropTrigger P1 * * P4 *
67245 ** Remove the internal (in-memory) data structures that describe
67246 ** the trigger named P4 in database P1. This is called after a trigger
67247 ** is dropped in order to keep the internal representation of the
67248 ** schema consistent with what is on disk.
67250 case OP_DropTrigger: {
67251 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
67252 break;
67256 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67257 /* Opcode: IntegrityCk P1 P2 P3 * P5
67259 ** Do an analysis of the currently open database. Store in
67260 ** register P1 the text of an error message describing any problems.
67261 ** If no problems are found, store a NULL in register P1.
67263 ** The register P3 contains the maximum number of allowed errors.
67264 ** At most reg(P3) errors will be reported.
67265 ** In other words, the analysis stops as soon as reg(P1) errors are
67266 ** seen. Reg(P1) is updated with the number of errors remaining.
67268 ** The root page numbers of all tables in the database are integer
67269 ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
67270 ** total.
67272 ** If P5 is not zero, the check is done on the auxiliary database
67273 ** file, not the main database file.
67275 ** This opcode is used to implement the integrity_check pragma.
67277 case OP_IntegrityCk: {
67278 #if 0 /* local variables moved into u.bv */
67279 int nRoot; /* Number of tables to check. (Number of root pages.) */
67280 int *aRoot; /* Array of rootpage numbers for tables to be checked */
67281 int j; /* Loop counter */
67282 int nErr; /* Number of errors reported */
67283 char *z; /* Text of the error report */
67284 Mem *pnErr; /* Register keeping track of errors remaining */
67285 #endif /* local variables moved into u.bv */
67287 u.bv.nRoot = pOp->p2;
67288 assert( u.bv.nRoot>0 );
67289 u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
67290 if( u.bv.aRoot==0 ) goto no_mem;
67291 assert( pOp->p3>0 && pOp->p3<=p->nMem );
67292 u.bv.pnErr = &aMem[pOp->p3];
67293 assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
67294 assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
67295 pIn1 = &aMem[pOp->p1];
67296 for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
67297 u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
67299 u.bv.aRoot[u.bv.j] = 0;
67300 assert( pOp->p5<db->nDb );
67301 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
67302 u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
67303 (int)u.bv.pnErr->u.i, &u.bv.nErr);
67304 sqlite3DbFree(db, u.bv.aRoot);
67305 u.bv.pnErr->u.i -= u.bv.nErr;
67306 sqlite3VdbeMemSetNull(pIn1);
67307 if( u.bv.nErr==0 ){
67308 assert( u.bv.z==0 );
67309 }else if( u.bv.z==0 ){
67310 goto no_mem;
67311 }else{
67312 sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
67314 UPDATE_MAX_BLOBSIZE(pIn1);
67315 sqlite3VdbeChangeEncoding(pIn1, encoding);
67316 break;
67318 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67320 /* Opcode: RowSetAdd P1 P2 * * *
67322 ** Insert the integer value held by register P2 into a boolean index
67323 ** held in register P1.
67325 ** An assertion fails if P2 is not an integer.
67327 case OP_RowSetAdd: { /* in1, in2 */
67328 pIn1 = &aMem[pOp->p1];
67329 pIn2 = &aMem[pOp->p2];
67330 assert( (pIn2->flags & MEM_Int)!=0 );
67331 if( (pIn1->flags & MEM_RowSet)==0 ){
67332 sqlite3VdbeMemSetRowSet(pIn1);
67333 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67335 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
67336 break;
67339 /* Opcode: RowSetRead P1 P2 P3 * *
67341 ** Extract the smallest value from boolean index P1 and put that value into
67342 ** register P3. Or, if boolean index P1 is initially empty, leave P3
67343 ** unchanged and jump to instruction P2.
67345 case OP_RowSetRead: { /* jump, in1, out3 */
67346 #if 0 /* local variables moved into u.bw */
67347 i64 val;
67348 #endif /* local variables moved into u.bw */
67349 CHECK_FOR_INTERRUPT;
67350 pIn1 = &aMem[pOp->p1];
67351 if( (pIn1->flags & MEM_RowSet)==0
67352 || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
67354 /* The boolean index is empty */
67355 sqlite3VdbeMemSetNull(pIn1);
67356 pc = pOp->p2 - 1;
67357 }else{
67358 /* A value was pulled from the index */
67359 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
67361 break;
67364 /* Opcode: RowSetTest P1 P2 P3 P4
67366 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
67367 ** contains a RowSet object and that RowSet object contains
67368 ** the value held in P3, jump to register P2. Otherwise, insert the
67369 ** integer in P3 into the RowSet and continue on to the
67370 ** next opcode.
67372 ** The RowSet object is optimized for the case where successive sets
67373 ** of integers, where each set contains no duplicates. Each set
67374 ** of values is identified by a unique P4 value. The first set
67375 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
67376 ** non-negative. For non-negative values of P4 only the lower 4
67377 ** bits are significant.
67379 ** This allows optimizations: (a) when P4==0 there is no need to test
67380 ** the rowset object for P3, as it is guaranteed not to contain it,
67381 ** (b) when P4==-1 there is no need to insert the value, as it will
67382 ** never be tested for, and (c) when a value that is part of set X is
67383 ** inserted, there is no need to search to see if the same value was
67384 ** previously inserted as part of set X (only if it was previously
67385 ** inserted as part of some other set).
67387 case OP_RowSetTest: { /* jump, in1, in3 */
67388 #if 0 /* local variables moved into u.bx */
67389 int iSet;
67390 int exists;
67391 #endif /* local variables moved into u.bx */
67393 pIn1 = &aMem[pOp->p1];
67394 pIn3 = &aMem[pOp->p3];
67395 u.bx.iSet = pOp->p4.i;
67396 assert( pIn3->flags&MEM_Int );
67398 /* If there is anything other than a rowset object in memory cell P1,
67399 ** delete it now and initialize P1 with an empty rowset
67401 if( (pIn1->flags & MEM_RowSet)==0 ){
67402 sqlite3VdbeMemSetRowSet(pIn1);
67403 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67406 assert( pOp->p4type==P4_INT32 );
67407 assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
67408 if( u.bx.iSet ){
67409 u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
67410 (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
67411 pIn3->u.i);
67412 if( u.bx.exists ){
67413 pc = pOp->p2 - 1;
67414 break;
67417 if( u.bx.iSet>=0 ){
67418 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
67420 break;
67424 #ifndef SQLITE_OMIT_TRIGGER
67426 /* Opcode: Program P1 P2 P3 P4 *
67428 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
67430 ** P1 contains the address of the memory cell that contains the first memory
67431 ** cell in an array of values used as arguments to the sub-program. P2
67432 ** contains the address to jump to if the sub-program throws an IGNORE
67433 ** exception using the RAISE() function. Register P3 contains the address
67434 ** of a memory cell in this (the parent) VM that is used to allocate the
67435 ** memory required by the sub-vdbe at runtime.
67437 ** P4 is a pointer to the VM containing the trigger program.
67439 case OP_Program: { /* jump */
67440 #if 0 /* local variables moved into u.by */
67441 int nMem; /* Number of memory registers for sub-program */
67442 int nByte; /* Bytes of runtime space required for sub-program */
67443 Mem *pRt; /* Register to allocate runtime space */
67444 Mem *pMem; /* Used to iterate through memory cells */
67445 Mem *pEnd; /* Last memory cell in new array */
67446 VdbeFrame *pFrame; /* New vdbe frame to execute in */
67447 SubProgram *pProgram; /* Sub-program to execute */
67448 void *t; /* Token identifying trigger */
67449 #endif /* local variables moved into u.by */
67451 u.by.pProgram = pOp->p4.pProgram;
67452 u.by.pRt = &aMem[pOp->p3];
67453 assert( memIsValid(u.by.pRt) );
67454 assert( u.by.pProgram->nOp>0 );
67456 /* If the p5 flag is clear, then recursive invocation of triggers is
67457 ** disabled for backwards compatibility (p5 is set if this sub-program
67458 ** is really a trigger, not a foreign key action, and the flag set
67459 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
67461 ** It is recursive invocation of triggers, at the SQL level, that is
67462 ** disabled. In some cases a single trigger may generate more than one
67463 ** SubProgram (if the trigger may be executed with more than one different
67464 ** ON CONFLICT algorithm). SubProgram structures associated with a
67465 ** single trigger all have the same value for the SubProgram.token
67466 ** variable. */
67467 if( pOp->p5 ){
67468 u.by.t = u.by.pProgram->token;
67469 for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
67470 if( u.by.pFrame ) break;
67473 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
67474 rc = SQLITE_ERROR;
67475 sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
67476 break;
67479 /* Register u.by.pRt is used to store the memory required to save the state
67480 ** of the current program, and the memory required at runtime to execute
67481 ** the trigger program. If this trigger has been fired before, then u.by.pRt
67482 ** is already allocated. Otherwise, it must be initialized. */
67483 if( (u.by.pRt->flags&MEM_Frame)==0 ){
67484 /* SubProgram.nMem is set to the number of memory cells used by the
67485 ** program stored in SubProgram.aOp. As well as these, one memory
67486 ** cell is required for each cursor used by the program. Set local
67487 ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
67489 u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
67490 u.by.nByte = ROUND8(sizeof(VdbeFrame))
67491 + u.by.nMem * sizeof(Mem)
67492 + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
67493 u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
67494 if( !u.by.pFrame ){
67495 goto no_mem;
67497 sqlite3VdbeMemRelease(u.by.pRt);
67498 u.by.pRt->flags = MEM_Frame;
67499 u.by.pRt->u.pFrame = u.by.pFrame;
67501 u.by.pFrame->v = p;
67502 u.by.pFrame->nChildMem = u.by.nMem;
67503 u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
67504 u.by.pFrame->pc = pc;
67505 u.by.pFrame->aMem = p->aMem;
67506 u.by.pFrame->nMem = p->nMem;
67507 u.by.pFrame->apCsr = p->apCsr;
67508 u.by.pFrame->nCursor = p->nCursor;
67509 u.by.pFrame->aOp = p->aOp;
67510 u.by.pFrame->nOp = p->nOp;
67511 u.by.pFrame->token = u.by.pProgram->token;
67513 u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
67514 for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
67515 u.by.pMem->flags = MEM_Null;
67516 u.by.pMem->db = db;
67518 }else{
67519 u.by.pFrame = u.by.pRt->u.pFrame;
67520 assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
67521 assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
67522 assert( pc==u.by.pFrame->pc );
67525 p->nFrame++;
67526 u.by.pFrame->pParent = p->pFrame;
67527 u.by.pFrame->lastRowid = db->lastRowid;
67528 u.by.pFrame->nChange = p->nChange;
67529 p->nChange = 0;
67530 p->pFrame = u.by.pFrame;
67531 p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
67532 p->nMem = u.by.pFrame->nChildMem;
67533 p->nCursor = (u16)u.by.pFrame->nChildCsr;
67534 p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
67535 p->aOp = aOp = u.by.pProgram->aOp;
67536 p->nOp = u.by.pProgram->nOp;
67537 pc = -1;
67539 break;
67542 /* Opcode: Param P1 P2 * * *
67544 ** This opcode is only ever present in sub-programs called via the
67545 ** OP_Program instruction. Copy a value currently stored in a memory
67546 ** cell of the calling (parent) frame to cell P2 in the current frames
67547 ** address space. This is used by trigger programs to access the new.*
67548 ** and old.* values.
67550 ** The address of the cell in the parent frame is determined by adding
67551 ** the value of the P1 argument to the value of the P1 argument to the
67552 ** calling OP_Program instruction.
67554 case OP_Param: { /* out2-prerelease */
67555 #if 0 /* local variables moved into u.bz */
67556 VdbeFrame *pFrame;
67557 Mem *pIn;
67558 #endif /* local variables moved into u.bz */
67559 u.bz.pFrame = p->pFrame;
67560 u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
67561 sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
67562 break;
67565 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
67567 #ifndef SQLITE_OMIT_FOREIGN_KEY
67568 /* Opcode: FkCounter P1 P2 * * *
67570 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
67571 ** If P1 is non-zero, the database constraint counter is incremented
67572 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
67573 ** statement counter is incremented (immediate foreign key constraints).
67575 case OP_FkCounter: {
67576 if( pOp->p1 ){
67577 db->nDeferredCons += pOp->p2;
67578 }else{
67579 p->nFkConstraint += pOp->p2;
67581 break;
67584 /* Opcode: FkIfZero P1 P2 * * *
67586 ** This opcode tests if a foreign key constraint-counter is currently zero.
67587 ** If so, jump to instruction P2. Otherwise, fall through to the next
67588 ** instruction.
67590 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
67591 ** is zero (the one that counts deferred constraint violations). If P1 is
67592 ** zero, the jump is taken if the statement constraint-counter is zero
67593 ** (immediate foreign key constraint violations).
67595 case OP_FkIfZero: { /* jump */
67596 if( pOp->p1 ){
67597 if( db->nDeferredCons==0 ) pc = pOp->p2-1;
67598 }else{
67599 if( p->nFkConstraint==0 ) pc = pOp->p2-1;
67601 break;
67603 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
67605 #ifndef SQLITE_OMIT_AUTOINCREMENT
67606 /* Opcode: MemMax P1 P2 * * *
67608 ** P1 is a register in the root frame of this VM (the root frame is
67609 ** different from the current frame if this instruction is being executed
67610 ** within a sub-program). Set the value of register P1 to the maximum of
67611 ** its current value and the value in register P2.
67613 ** This instruction throws an error if the memory cell is not initially
67614 ** an integer.
67616 case OP_MemMax: { /* in2 */
67617 #if 0 /* local variables moved into u.ca */
67618 Mem *pIn1;
67619 VdbeFrame *pFrame;
67620 #endif /* local variables moved into u.ca */
67621 if( p->pFrame ){
67622 for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
67623 u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
67624 }else{
67625 u.ca.pIn1 = &aMem[pOp->p1];
67627 assert( memIsValid(u.ca.pIn1) );
67628 sqlite3VdbeMemIntegerify(u.ca.pIn1);
67629 pIn2 = &aMem[pOp->p2];
67630 sqlite3VdbeMemIntegerify(pIn2);
67631 if( u.ca.pIn1->u.i<pIn2->u.i){
67632 u.ca.pIn1->u.i = pIn2->u.i;
67634 break;
67636 #endif /* SQLITE_OMIT_AUTOINCREMENT */
67638 /* Opcode: IfPos P1 P2 * * *
67640 ** If the value of register P1 is 1 or greater, jump to P2.
67642 ** It is illegal to use this instruction on a register that does
67643 ** not contain an integer. An assertion fault will result if you try.
67645 case OP_IfPos: { /* jump, in1 */
67646 pIn1 = &aMem[pOp->p1];
67647 assert( pIn1->flags&MEM_Int );
67648 if( pIn1->u.i>0 ){
67649 pc = pOp->p2 - 1;
67651 break;
67654 /* Opcode: IfNeg P1 P2 * * *
67656 ** If the value of register P1 is less than zero, jump to P2.
67658 ** It is illegal to use this instruction on a register that does
67659 ** not contain an integer. An assertion fault will result if you try.
67661 case OP_IfNeg: { /* jump, in1 */
67662 pIn1 = &aMem[pOp->p1];
67663 assert( pIn1->flags&MEM_Int );
67664 if( pIn1->u.i<0 ){
67665 pc = pOp->p2 - 1;
67667 break;
67670 /* Opcode: IfZero P1 P2 P3 * *
67672 ** The register P1 must contain an integer. Add literal P3 to the
67673 ** value in register P1. If the result is exactly 0, jump to P2.
67675 ** It is illegal to use this instruction on a register that does
67676 ** not contain an integer. An assertion fault will result if you try.
67678 case OP_IfZero: { /* jump, in1 */
67679 pIn1 = &aMem[pOp->p1];
67680 assert( pIn1->flags&MEM_Int );
67681 pIn1->u.i += pOp->p3;
67682 if( pIn1->u.i==0 ){
67683 pc = pOp->p2 - 1;
67685 break;
67688 /* Opcode: AggStep * P2 P3 P4 P5
67690 ** Execute the step function for an aggregate. The
67691 ** function has P5 arguments. P4 is a pointer to the FuncDef
67692 ** structure that specifies the function. Use register
67693 ** P3 as the accumulator.
67695 ** The P5 arguments are taken from register P2 and its
67696 ** successors.
67698 case OP_AggStep: {
67699 #if 0 /* local variables moved into u.cb */
67700 int n;
67701 int i;
67702 Mem *pMem;
67703 Mem *pRec;
67704 sqlite3_context ctx;
67705 sqlite3_value **apVal;
67706 #endif /* local variables moved into u.cb */
67708 u.cb.n = pOp->p5;
67709 assert( u.cb.n>=0 );
67710 u.cb.pRec = &aMem[pOp->p2];
67711 u.cb.apVal = p->apArg;
67712 assert( u.cb.apVal || u.cb.n==0 );
67713 for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
67714 assert( memIsValid(u.cb.pRec) );
67715 u.cb.apVal[u.cb.i] = u.cb.pRec;
67716 memAboutToChange(p, u.cb.pRec);
67717 sqlite3VdbeMemStoreType(u.cb.pRec);
67719 u.cb.ctx.pFunc = pOp->p4.pFunc;
67720 assert( pOp->p3>0 && pOp->p3<=p->nMem );
67721 u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
67722 u.cb.pMem->n++;
67723 u.cb.ctx.s.flags = MEM_Null;
67724 u.cb.ctx.s.z = 0;
67725 u.cb.ctx.s.zMalloc = 0;
67726 u.cb.ctx.s.xDel = 0;
67727 u.cb.ctx.s.db = db;
67728 u.cb.ctx.isError = 0;
67729 u.cb.ctx.pColl = 0;
67730 if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
67731 assert( pOp>p->aOp );
67732 assert( pOp[-1].p4type==P4_COLLSEQ );
67733 assert( pOp[-1].opcode==OP_CollSeq );
67734 u.cb.ctx.pColl = pOp[-1].p4.pColl;
67736 (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
67737 if( u.cb.ctx.isError ){
67738 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
67739 rc = u.cb.ctx.isError;
67742 sqlite3VdbeMemRelease(&u.cb.ctx.s);
67744 break;
67747 /* Opcode: AggFinal P1 P2 * P4 *
67749 ** Execute the finalizer function for an aggregate. P1 is
67750 ** the memory location that is the accumulator for the aggregate.
67752 ** P2 is the number of arguments that the step function takes and
67753 ** P4 is a pointer to the FuncDef for this function. The P2
67754 ** argument is not used by this opcode. It is only there to disambiguate
67755 ** functions that can take varying numbers of arguments. The
67756 ** P4 argument is only needed for the degenerate case where
67757 ** the step function was not previously called.
67759 case OP_AggFinal: {
67760 #if 0 /* local variables moved into u.cc */
67761 Mem *pMem;
67762 #endif /* local variables moved into u.cc */
67763 assert( pOp->p1>0 && pOp->p1<=p->nMem );
67764 u.cc.pMem = &aMem[pOp->p1];
67765 assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
67766 rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
67767 if( rc ){
67768 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
67770 sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
67771 UPDATE_MAX_BLOBSIZE(u.cc.pMem);
67772 if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
67773 goto too_big;
67775 break;
67778 #ifndef SQLITE_OMIT_WAL
67779 /* Opcode: Checkpoint P1 P2 P3 * *
67781 ** Checkpoint database P1. This is a no-op if P1 is not currently in
67782 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
67783 ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
67784 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
67785 ** WAL after the checkpoint into mem[P3+1] and the number of pages
67786 ** in the WAL that have been checkpointed after the checkpoint
67787 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
67788 ** mem[P3+2] are initialized to -1.
67790 case OP_Checkpoint: {
67791 #if 0 /* local variables moved into u.cd */
67792 int i; /* Loop counter */
67793 int aRes[3]; /* Results */
67794 Mem *pMem; /* Write results here */
67795 #endif /* local variables moved into u.cd */
67797 u.cd.aRes[0] = 0;
67798 u.cd.aRes[1] = u.cd.aRes[2] = -1;
67799 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
67800 || pOp->p2==SQLITE_CHECKPOINT_FULL
67801 || pOp->p2==SQLITE_CHECKPOINT_RESTART
67803 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.cd.aRes[1], &u.cd.aRes[2]);
67804 if( rc==SQLITE_BUSY ){
67805 rc = SQLITE_OK;
67806 u.cd.aRes[0] = 1;
67808 for(u.cd.i=0, u.cd.pMem = &aMem[pOp->p3]; u.cd.i<3; u.cd.i++, u.cd.pMem++){
67809 sqlite3VdbeMemSetInt64(u.cd.pMem, (i64)u.cd.aRes[u.cd.i]);
67811 break;
67813 #endif
67815 #ifndef SQLITE_OMIT_PRAGMA
67816 /* Opcode: JournalMode P1 P2 P3 * P5
67818 ** Change the journal mode of database P1 to P3. P3 must be one of the
67819 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
67820 ** modes (delete, truncate, persist, off and memory), this is a simple
67821 ** operation. No IO is required.
67823 ** If changing into or out of WAL mode the procedure is more complicated.
67825 ** Write a string containing the final journal-mode to register P2.
67827 case OP_JournalMode: { /* out2-prerelease */
67828 #if 0 /* local variables moved into u.ce */
67829 Btree *pBt; /* Btree to change journal mode of */
67830 Pager *pPager; /* Pager associated with pBt */
67831 int eNew; /* New journal mode */
67832 int eOld; /* The old journal mode */
67833 const char *zFilename; /* Name of database file for pPager */
67834 #endif /* local variables moved into u.ce */
67836 u.ce.eNew = pOp->p3;
67837 assert( u.ce.eNew==PAGER_JOURNALMODE_DELETE
67838 || u.ce.eNew==PAGER_JOURNALMODE_TRUNCATE
67839 || u.ce.eNew==PAGER_JOURNALMODE_PERSIST
67840 || u.ce.eNew==PAGER_JOURNALMODE_OFF
67841 || u.ce.eNew==PAGER_JOURNALMODE_MEMORY
67842 || u.ce.eNew==PAGER_JOURNALMODE_WAL
67843 || u.ce.eNew==PAGER_JOURNALMODE_QUERY
67845 assert( pOp->p1>=0 && pOp->p1<db->nDb );
67847 u.ce.pBt = db->aDb[pOp->p1].pBt;
67848 u.ce.pPager = sqlite3BtreePager(u.ce.pBt);
67849 u.ce.eOld = sqlite3PagerGetJournalMode(u.ce.pPager);
67850 if( u.ce.eNew==PAGER_JOURNALMODE_QUERY ) u.ce.eNew = u.ce.eOld;
67851 if( !sqlite3PagerOkToChangeJournalMode(u.ce.pPager) ) u.ce.eNew = u.ce.eOld;
67853 #ifndef SQLITE_OMIT_WAL
67854 u.ce.zFilename = sqlite3PagerFilename(u.ce.pPager);
67856 /* Do not allow a transition to journal_mode=WAL for a database
67857 ** in temporary storage or if the VFS does not support shared memory
67859 if( u.ce.eNew==PAGER_JOURNALMODE_WAL
67860 && (u.ce.zFilename[0]==0 /* Temp file */
67861 || !sqlite3PagerWalSupported(u.ce.pPager)) /* No shared-memory support */
67863 u.ce.eNew = u.ce.eOld;
67866 if( (u.ce.eNew!=u.ce.eOld)
67867 && (u.ce.eOld==PAGER_JOURNALMODE_WAL || u.ce.eNew==PAGER_JOURNALMODE_WAL)
67869 if( !db->autoCommit || db->activeVdbeCnt>1 ){
67870 rc = SQLITE_ERROR;
67871 sqlite3SetString(&p->zErrMsg, db,
67872 "cannot change %s wal mode from within a transaction",
67873 (u.ce.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
67875 break;
67876 }else{
67878 if( u.ce.eOld==PAGER_JOURNALMODE_WAL ){
67879 /* If leaving WAL mode, close the log file. If successful, the call
67880 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
67881 ** file. An EXCLUSIVE lock may still be held on the database file
67882 ** after a successful return.
67884 rc = sqlite3PagerCloseWal(u.ce.pPager);
67885 if( rc==SQLITE_OK ){
67886 sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
67888 }else if( u.ce.eOld==PAGER_JOURNALMODE_MEMORY ){
67889 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
67890 ** as an intermediate */
67891 sqlite3PagerSetJournalMode(u.ce.pPager, PAGER_JOURNALMODE_OFF);
67894 /* Open a transaction on the database file. Regardless of the journal
67895 ** mode, this transaction always uses a rollback journal.
67897 assert( sqlite3BtreeIsInTrans(u.ce.pBt)==0 );
67898 if( rc==SQLITE_OK ){
67899 rc = sqlite3BtreeSetVersion(u.ce.pBt, (u.ce.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
67903 #endif /* ifndef SQLITE_OMIT_WAL */
67905 if( rc ){
67906 u.ce.eNew = u.ce.eOld;
67908 u.ce.eNew = sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
67910 pOut = &aMem[pOp->p2];
67911 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
67912 pOut->z = (char *)sqlite3JournalModename(u.ce.eNew);
67913 pOut->n = sqlite3Strlen30(pOut->z);
67914 pOut->enc = SQLITE_UTF8;
67915 sqlite3VdbeChangeEncoding(pOut, encoding);
67916 break;
67918 #endif /* SQLITE_OMIT_PRAGMA */
67920 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
67921 /* Opcode: Vacuum * * * * *
67923 ** Vacuum the entire database. This opcode will cause other virtual
67924 ** machines to be created and run. It may not be called from within
67925 ** a transaction.
67927 case OP_Vacuum: {
67928 rc = sqlite3RunVacuum(&p->zErrMsg, db);
67929 break;
67931 #endif
67933 #if !defined(SQLITE_OMIT_AUTOVACUUM)
67934 /* Opcode: IncrVacuum P1 P2 * * *
67936 ** Perform a single step of the incremental vacuum procedure on
67937 ** the P1 database. If the vacuum has finished, jump to instruction
67938 ** P2. Otherwise, fall through to the next instruction.
67940 case OP_IncrVacuum: { /* jump */
67941 #if 0 /* local variables moved into u.cf */
67942 Btree *pBt;
67943 #endif /* local variables moved into u.cf */
67945 assert( pOp->p1>=0 && pOp->p1<db->nDb );
67946 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67947 u.cf.pBt = db->aDb[pOp->p1].pBt;
67948 rc = sqlite3BtreeIncrVacuum(u.cf.pBt);
67949 if( rc==SQLITE_DONE ){
67950 pc = pOp->p2 - 1;
67951 rc = SQLITE_OK;
67953 break;
67955 #endif
67957 /* Opcode: Expire P1 * * * *
67959 ** Cause precompiled statements to become expired. An expired statement
67960 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
67961 ** (via sqlite3_step()).
67963 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
67964 ** then only the currently executing statement is affected.
67966 case OP_Expire: {
67967 if( !pOp->p1 ){
67968 sqlite3ExpirePreparedStatements(db);
67969 }else{
67970 p->expired = 1;
67972 break;
67975 #ifndef SQLITE_OMIT_SHARED_CACHE
67976 /* Opcode: TableLock P1 P2 P3 P4 *
67978 ** Obtain a lock on a particular table. This instruction is only used when
67979 ** the shared-cache feature is enabled.
67981 ** P1 is the index of the database in sqlite3.aDb[] of the database
67982 ** on which the lock is acquired. A readlock is obtained if P3==0 or
67983 ** a write lock if P3==1.
67985 ** P2 contains the root-page of the table to lock.
67987 ** P4 contains a pointer to the name of the table being locked. This is only
67988 ** used to generate an error message if the lock cannot be obtained.
67990 case OP_TableLock: {
67991 u8 isWriteLock = (u8)pOp->p3;
67992 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
67993 int p1 = pOp->p1;
67994 assert( p1>=0 && p1<db->nDb );
67995 assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
67996 assert( isWriteLock==0 || isWriteLock==1 );
67997 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
67998 if( (rc&0xFF)==SQLITE_LOCKED ){
67999 const char *z = pOp->p4.z;
68000 sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
68003 break;
68005 #endif /* SQLITE_OMIT_SHARED_CACHE */
68007 #ifndef SQLITE_OMIT_VIRTUALTABLE
68008 /* Opcode: VBegin * * * P4 *
68010 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
68011 ** xBegin method for that table.
68013 ** Also, whether or not P4 is set, check that this is not being called from
68014 ** within a callback to a virtual table xSync() method. If it is, the error
68015 ** code will be set to SQLITE_LOCKED.
68017 case OP_VBegin: {
68018 #if 0 /* local variables moved into u.cg */
68019 VTable *pVTab;
68020 #endif /* local variables moved into u.cg */
68021 u.cg.pVTab = pOp->p4.pVtab;
68022 rc = sqlite3VtabBegin(db, u.cg.pVTab);
68023 if( u.cg.pVTab ) importVtabErrMsg(p, u.cg.pVTab->pVtab);
68024 break;
68026 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68028 #ifndef SQLITE_OMIT_VIRTUALTABLE
68029 /* Opcode: VCreate P1 * * P4 *
68031 ** P4 is the name of a virtual table in database P1. Call the xCreate method
68032 ** for that table.
68034 case OP_VCreate: {
68035 rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
68036 break;
68038 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68040 #ifndef SQLITE_OMIT_VIRTUALTABLE
68041 /* Opcode: VDestroy P1 * * P4 *
68043 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
68044 ** of that table.
68046 case OP_VDestroy: {
68047 p->inVtabMethod = 2;
68048 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
68049 p->inVtabMethod = 0;
68050 break;
68052 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68054 #ifndef SQLITE_OMIT_VIRTUALTABLE
68055 /* Opcode: VOpen P1 * * P4 *
68057 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68058 ** P1 is a cursor number. This opcode opens a cursor to the virtual
68059 ** table and stores that cursor in P1.
68061 case OP_VOpen: {
68062 #if 0 /* local variables moved into u.ch */
68063 VdbeCursor *pCur;
68064 sqlite3_vtab_cursor *pVtabCursor;
68065 sqlite3_vtab *pVtab;
68066 sqlite3_module *pModule;
68067 #endif /* local variables moved into u.ch */
68069 u.ch.pCur = 0;
68070 u.ch.pVtabCursor = 0;
68071 u.ch.pVtab = pOp->p4.pVtab->pVtab;
68072 u.ch.pModule = (sqlite3_module *)u.ch.pVtab->pModule;
68073 assert(u.ch.pVtab && u.ch.pModule);
68074 rc = u.ch.pModule->xOpen(u.ch.pVtab, &u.ch.pVtabCursor);
68075 importVtabErrMsg(p, u.ch.pVtab);
68076 if( SQLITE_OK==rc ){
68077 /* Initialize sqlite3_vtab_cursor base class */
68078 u.ch.pVtabCursor->pVtab = u.ch.pVtab;
68080 /* Initialise vdbe cursor object */
68081 u.ch.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
68082 if( u.ch.pCur ){
68083 u.ch.pCur->pVtabCursor = u.ch.pVtabCursor;
68084 u.ch.pCur->pModule = u.ch.pVtabCursor->pVtab->pModule;
68085 }else{
68086 db->mallocFailed = 1;
68087 u.ch.pModule->xClose(u.ch.pVtabCursor);
68090 break;
68092 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68094 #ifndef SQLITE_OMIT_VIRTUALTABLE
68095 /* Opcode: VFilter P1 P2 P3 P4 *
68097 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
68098 ** the filtered result set is empty.
68100 ** P4 is either NULL or a string that was generated by the xBestIndex
68101 ** method of the module. The interpretation of the P4 string is left
68102 ** to the module implementation.
68104 ** This opcode invokes the xFilter method on the virtual table specified
68105 ** by P1. The integer query plan parameter to xFilter is stored in register
68106 ** P3. Register P3+1 stores the argc parameter to be passed to the
68107 ** xFilter method. Registers P3+2..P3+1+argc are the argc
68108 ** additional parameters which are passed to
68109 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
68111 ** A jump is made to P2 if the result set after filtering would be empty.
68113 case OP_VFilter: { /* jump */
68114 #if 0 /* local variables moved into u.ci */
68115 int nArg;
68116 int iQuery;
68117 const sqlite3_module *pModule;
68118 Mem *pQuery;
68119 Mem *pArgc;
68120 sqlite3_vtab_cursor *pVtabCursor;
68121 sqlite3_vtab *pVtab;
68122 VdbeCursor *pCur;
68123 int res;
68124 int i;
68125 Mem **apArg;
68126 #endif /* local variables moved into u.ci */
68128 u.ci.pQuery = &aMem[pOp->p3];
68129 u.ci.pArgc = &u.ci.pQuery[1];
68130 u.ci.pCur = p->apCsr[pOp->p1];
68131 assert( memIsValid(u.ci.pQuery) );
68132 REGISTER_TRACE(pOp->p3, u.ci.pQuery);
68133 assert( u.ci.pCur->pVtabCursor );
68134 u.ci.pVtabCursor = u.ci.pCur->pVtabCursor;
68135 u.ci.pVtab = u.ci.pVtabCursor->pVtab;
68136 u.ci.pModule = u.ci.pVtab->pModule;
68138 /* Grab the index number and argc parameters */
68139 assert( (u.ci.pQuery->flags&MEM_Int)!=0 && u.ci.pArgc->flags==MEM_Int );
68140 u.ci.nArg = (int)u.ci.pArgc->u.i;
68141 u.ci.iQuery = (int)u.ci.pQuery->u.i;
68143 /* Invoke the xFilter method */
68145 u.ci.res = 0;
68146 u.ci.apArg = p->apArg;
68147 for(u.ci.i = 0; u.ci.i<u.ci.nArg; u.ci.i++){
68148 u.ci.apArg[u.ci.i] = &u.ci.pArgc[u.ci.i+1];
68149 sqlite3VdbeMemStoreType(u.ci.apArg[u.ci.i]);
68152 p->inVtabMethod = 1;
68153 rc = u.ci.pModule->xFilter(u.ci.pVtabCursor, u.ci.iQuery, pOp->p4.z, u.ci.nArg, u.ci.apArg);
68154 p->inVtabMethod = 0;
68155 importVtabErrMsg(p, u.ci.pVtab);
68156 if( rc==SQLITE_OK ){
68157 u.ci.res = u.ci.pModule->xEof(u.ci.pVtabCursor);
68160 if( u.ci.res ){
68161 pc = pOp->p2 - 1;
68164 u.ci.pCur->nullRow = 0;
68166 break;
68168 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68170 #ifndef SQLITE_OMIT_VIRTUALTABLE
68171 /* Opcode: VColumn P1 P2 P3 * *
68173 ** Store the value of the P2-th column of
68174 ** the row of the virtual-table that the
68175 ** P1 cursor is pointing to into register P3.
68177 case OP_VColumn: {
68178 #if 0 /* local variables moved into u.cj */
68179 sqlite3_vtab *pVtab;
68180 const sqlite3_module *pModule;
68181 Mem *pDest;
68182 sqlite3_context sContext;
68183 #endif /* local variables moved into u.cj */
68185 VdbeCursor *pCur = p->apCsr[pOp->p1];
68186 assert( pCur->pVtabCursor );
68187 assert( pOp->p3>0 && pOp->p3<=p->nMem );
68188 u.cj.pDest = &aMem[pOp->p3];
68189 memAboutToChange(p, u.cj.pDest);
68190 if( pCur->nullRow ){
68191 sqlite3VdbeMemSetNull(u.cj.pDest);
68192 break;
68194 u.cj.pVtab = pCur->pVtabCursor->pVtab;
68195 u.cj.pModule = u.cj.pVtab->pModule;
68196 assert( u.cj.pModule->xColumn );
68197 memset(&u.cj.sContext, 0, sizeof(u.cj.sContext));
68199 /* The output cell may already have a buffer allocated. Move
68200 ** the current contents to u.cj.sContext.s so in case the user-function
68201 ** can use the already allocated buffer instead of allocating a
68202 ** new one.
68204 sqlite3VdbeMemMove(&u.cj.sContext.s, u.cj.pDest);
68205 MemSetTypeFlag(&u.cj.sContext.s, MEM_Null);
68207 rc = u.cj.pModule->xColumn(pCur->pVtabCursor, &u.cj.sContext, pOp->p2);
68208 importVtabErrMsg(p, u.cj.pVtab);
68209 if( u.cj.sContext.isError ){
68210 rc = u.cj.sContext.isError;
68213 /* Copy the result of the function to the P3 register. We
68214 ** do this regardless of whether or not an error occurred to ensure any
68215 ** dynamic allocation in u.cj.sContext.s (a Mem struct) is released.
68217 sqlite3VdbeChangeEncoding(&u.cj.sContext.s, encoding);
68218 sqlite3VdbeMemMove(u.cj.pDest, &u.cj.sContext.s);
68219 REGISTER_TRACE(pOp->p3, u.cj.pDest);
68220 UPDATE_MAX_BLOBSIZE(u.cj.pDest);
68222 if( sqlite3VdbeMemTooBig(u.cj.pDest) ){
68223 goto too_big;
68225 break;
68227 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68229 #ifndef SQLITE_OMIT_VIRTUALTABLE
68230 /* Opcode: VNext P1 P2 * * *
68232 ** Advance virtual table P1 to the next row in its result set and
68233 ** jump to instruction P2. Or, if the virtual table has reached
68234 ** the end of its result set, then fall through to the next instruction.
68236 case OP_VNext: { /* jump */
68237 #if 0 /* local variables moved into u.ck */
68238 sqlite3_vtab *pVtab;
68239 const sqlite3_module *pModule;
68240 int res;
68241 VdbeCursor *pCur;
68242 #endif /* local variables moved into u.ck */
68244 u.ck.res = 0;
68245 u.ck.pCur = p->apCsr[pOp->p1];
68246 assert( u.ck.pCur->pVtabCursor );
68247 if( u.ck.pCur->nullRow ){
68248 break;
68250 u.ck.pVtab = u.ck.pCur->pVtabCursor->pVtab;
68251 u.ck.pModule = u.ck.pVtab->pModule;
68252 assert( u.ck.pModule->xNext );
68254 /* Invoke the xNext() method of the module. There is no way for the
68255 ** underlying implementation to return an error if one occurs during
68256 ** xNext(). Instead, if an error occurs, true is returned (indicating that
68257 ** data is available) and the error code returned when xColumn or
68258 ** some other method is next invoked on the save virtual table cursor.
68260 p->inVtabMethod = 1;
68261 rc = u.ck.pModule->xNext(u.ck.pCur->pVtabCursor);
68262 p->inVtabMethod = 0;
68263 importVtabErrMsg(p, u.ck.pVtab);
68264 if( rc==SQLITE_OK ){
68265 u.ck.res = u.ck.pModule->xEof(u.ck.pCur->pVtabCursor);
68268 if( !u.ck.res ){
68269 /* If there is data, jump to P2 */
68270 pc = pOp->p2 - 1;
68272 break;
68274 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68276 #ifndef SQLITE_OMIT_VIRTUALTABLE
68277 /* Opcode: VRename P1 * * P4 *
68279 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68280 ** This opcode invokes the corresponding xRename method. The value
68281 ** in register P1 is passed as the zName argument to the xRename method.
68283 case OP_VRename: {
68284 #if 0 /* local variables moved into u.cl */
68285 sqlite3_vtab *pVtab;
68286 Mem *pName;
68287 #endif /* local variables moved into u.cl */
68289 u.cl.pVtab = pOp->p4.pVtab->pVtab;
68290 u.cl.pName = &aMem[pOp->p1];
68291 assert( u.cl.pVtab->pModule->xRename );
68292 assert( memIsValid(u.cl.pName) );
68293 REGISTER_TRACE(pOp->p1, u.cl.pName);
68294 assert( u.cl.pName->flags & MEM_Str );
68295 rc = u.cl.pVtab->pModule->xRename(u.cl.pVtab, u.cl.pName->z);
68296 importVtabErrMsg(p, u.cl.pVtab);
68297 p->expired = 0;
68299 break;
68301 #endif
68303 #ifndef SQLITE_OMIT_VIRTUALTABLE
68304 /* Opcode: VUpdate P1 P2 P3 P4 *
68306 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68307 ** This opcode invokes the corresponding xUpdate method. P2 values
68308 ** are contiguous memory cells starting at P3 to pass to the xUpdate
68309 ** invocation. The value in register (P3+P2-1) corresponds to the
68310 ** p2th element of the argv array passed to xUpdate.
68312 ** The xUpdate method will do a DELETE or an INSERT or both.
68313 ** The argv[0] element (which corresponds to memory cell P3)
68314 ** is the rowid of a row to delete. If argv[0] is NULL then no
68315 ** deletion occurs. The argv[1] element is the rowid of the new
68316 ** row. This can be NULL to have the virtual table select the new
68317 ** rowid for itself. The subsequent elements in the array are
68318 ** the values of columns in the new row.
68320 ** If P2==1 then no insert is performed. argv[0] is the rowid of
68321 ** a row to delete.
68323 ** P1 is a boolean flag. If it is set to true and the xUpdate call
68324 ** is successful, then the value returned by sqlite3_last_insert_rowid()
68325 ** is set to the value of the rowid for the row just inserted.
68327 case OP_VUpdate: {
68328 #if 0 /* local variables moved into u.cm */
68329 sqlite3_vtab *pVtab;
68330 sqlite3_module *pModule;
68331 int nArg;
68332 int i;
68333 sqlite_int64 rowid;
68334 Mem **apArg;
68335 Mem *pX;
68336 #endif /* local variables moved into u.cm */
68338 u.cm.pVtab = pOp->p4.pVtab->pVtab;
68339 u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
68340 u.cm.nArg = pOp->p2;
68341 assert( pOp->p4type==P4_VTAB );
68342 if( ALWAYS(u.cm.pModule->xUpdate) ){
68343 u.cm.apArg = p->apArg;
68344 u.cm.pX = &aMem[pOp->p3];
68345 for(u.cm.i=0; u.cm.i<u.cm.nArg; u.cm.i++){
68346 assert( memIsValid(u.cm.pX) );
68347 memAboutToChange(p, u.cm.pX);
68348 sqlite3VdbeMemStoreType(u.cm.pX);
68349 u.cm.apArg[u.cm.i] = u.cm.pX;
68350 u.cm.pX++;
68352 rc = u.cm.pModule->xUpdate(u.cm.pVtab, u.cm.nArg, u.cm.apArg, &u.cm.rowid);
68353 importVtabErrMsg(p, u.cm.pVtab);
68354 if( rc==SQLITE_OK && pOp->p1 ){
68355 assert( u.cm.nArg>1 && u.cm.apArg[0] && (u.cm.apArg[0]->flags&MEM_Null) );
68356 db->lastRowid = u.cm.rowid;
68358 p->nChange++;
68360 break;
68362 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68364 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
68365 /* Opcode: Pagecount P1 P2 * * *
68367 ** Write the current number of pages in database P1 to memory cell P2.
68369 case OP_Pagecount: { /* out2-prerelease */
68370 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
68371 break;
68373 #endif
68376 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
68377 /* Opcode: MaxPgcnt P1 P2 P3 * *
68379 ** Try to set the maximum page count for database P1 to the value in P3.
68380 ** Do not let the maximum page count fall below the current page count and
68381 ** do not change the maximum page count value if P3==0.
68383 ** Store the maximum page count after the change in register P2.
68385 case OP_MaxPgcnt: { /* out2-prerelease */
68386 unsigned int newMax;
68387 Btree *pBt;
68389 pBt = db->aDb[pOp->p1].pBt;
68390 newMax = 0;
68391 if( pOp->p3 ){
68392 newMax = sqlite3BtreeLastPage(pBt);
68393 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
68395 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
68396 break;
68398 #endif
68401 #ifndef SQLITE_OMIT_TRACE
68402 /* Opcode: Trace * * * P4 *
68404 ** If tracing is enabled (by the sqlite3_trace()) interface, then
68405 ** the UTF-8 string contained in P4 is emitted on the trace callback.
68407 case OP_Trace: {
68408 #if 0 /* local variables moved into u.cn */
68409 char *zTrace;
68410 #endif /* local variables moved into u.cn */
68412 u.cn.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
68413 if( u.cn.zTrace ){
68414 if( db->xTrace ){
68415 char *z = sqlite3VdbeExpandSql(p, u.cn.zTrace);
68416 db->xTrace(db->pTraceArg, z);
68417 sqlite3DbFree(db, z);
68419 #ifdef SQLITE_DEBUG
68420 if( (db->flags & SQLITE_SqlTrace)!=0 ){
68421 sqlite3DebugPrintf("SQL-trace: %s\n", u.cn.zTrace);
68423 #endif /* SQLITE_DEBUG */
68425 break;
68427 #endif
68430 /* Opcode: Noop * * * * *
68432 ** Do nothing. This instruction is often useful as a jump
68433 ** destination.
68436 ** The magic Explain opcode are only inserted when explain==2 (which
68437 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
68438 ** This opcode records information from the optimizer. It is the
68439 ** the same as a no-op. This opcodesnever appears in a real VM program.
68441 default: { /* This is really OP_Noop and OP_Explain */
68442 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
68443 break;
68446 /*****************************************************************************
68447 ** The cases of the switch statement above this line should all be indented
68448 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
68449 ** readability. From this point on down, the normal indentation rules are
68450 ** restored.
68451 *****************************************************************************/
68454 #ifdef VDBE_PROFILE
68456 u64 elapsed = sqlite3Hwtime() - start;
68457 pOp->cycles += elapsed;
68458 pOp->cnt++;
68459 #if 0
68460 fprintf(stdout, "%10llu ", elapsed);
68461 sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
68462 #endif
68464 #endif
68466 /* The following code adds nothing to the actual functionality
68467 ** of the program. It is only here for testing and debugging.
68468 ** On the other hand, it does burn CPU cycles every time through
68469 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
68471 #ifndef NDEBUG
68472 assert( pc>=-1 && pc<p->nOp );
68474 #ifdef SQLITE_DEBUG
68475 if( p->trace ){
68476 if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
68477 if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
68478 registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
68480 if( pOp->opflags & OPFLG_OUT3 ){
68481 registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
68484 #endif /* SQLITE_DEBUG */
68485 #endif /* NDEBUG */
68486 } /* The end of the for(;;) loop the loops through opcodes */
68488 /* If we reach this point, it means that execution is finished with
68489 ** an error of some kind.
68491 vdbe_error_halt:
68492 assert( rc );
68493 p->rc = rc;
68494 testcase( sqlite3GlobalConfig.xLog!=0 );
68495 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
68496 pc, p->zSql, p->zErrMsg);
68497 sqlite3VdbeHalt(p);
68498 if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
68499 rc = SQLITE_ERROR;
68500 if( resetSchemaOnFault>0 ){
68501 sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
68504 /* This is the only way out of this procedure. We have to
68505 ** release the mutexes on btrees that were acquired at the
68506 ** top. */
68507 vdbe_return:
68508 sqlite3VdbeLeave(p);
68509 return rc;
68511 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
68512 ** is encountered.
68514 too_big:
68515 sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
68516 rc = SQLITE_TOOBIG;
68517 goto vdbe_error_halt;
68519 /* Jump to here if a malloc() fails.
68521 no_mem:
68522 db->mallocFailed = 1;
68523 sqlite3SetString(&p->zErrMsg, db, "out of memory");
68524 rc = SQLITE_NOMEM;
68525 goto vdbe_error_halt;
68527 /* Jump to here for any other kind of fatal error. The "rc" variable
68528 ** should hold the error number.
68530 abort_due_to_error:
68531 assert( p->zErrMsg==0 );
68532 if( db->mallocFailed ) rc = SQLITE_NOMEM;
68533 if( rc!=SQLITE_IOERR_NOMEM ){
68534 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68536 goto vdbe_error_halt;
68538 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
68539 ** flag.
68541 abort_due_to_interrupt:
68542 assert( db->u1.isInterrupted );
68543 rc = SQLITE_INTERRUPT;
68544 p->rc = rc;
68545 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68546 goto vdbe_error_halt;
68549 /************** End of vdbe.c ************************************************/
68550 /************** Begin file vdbeblob.c ****************************************/
68552 ** 2007 May 1
68554 ** The author disclaims copyright to this source code. In place of
68555 ** a legal notice, here is a blessing:
68557 ** May you do good and not evil.
68558 ** May you find forgiveness for yourself and forgive others.
68559 ** May you share freely, never taking more than you give.
68561 *************************************************************************
68563 ** This file contains code used to implement incremental BLOB I/O.
68567 #ifndef SQLITE_OMIT_INCRBLOB
68570 ** Valid sqlite3_blob* handles point to Incrblob structures.
68572 typedef struct Incrblob Incrblob;
68573 struct Incrblob {
68574 int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
68575 int nByte; /* Size of open blob, in bytes */
68576 int iOffset; /* Byte offset of blob in cursor data */
68577 int iCol; /* Table column this handle is open on */
68578 BtCursor *pCsr; /* Cursor pointing at blob row */
68579 sqlite3_stmt *pStmt; /* Statement holding cursor open */
68580 sqlite3 *db; /* The associated database */
68585 ** This function is used by both blob_open() and blob_reopen(). It seeks
68586 ** the b-tree cursor associated with blob handle p to point to row iRow.
68587 ** If successful, SQLITE_OK is returned and subsequent calls to
68588 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
68590 ** If an error occurs, or if the specified row does not exist or does not
68591 ** contain a value of type TEXT or BLOB in the column nominated when the
68592 ** blob handle was opened, then an error code is returned and *pzErr may
68593 ** be set to point to a buffer containing an error message. It is the
68594 ** responsibility of the caller to free the error message buffer using
68595 ** sqlite3DbFree().
68597 ** If an error does occur, then the b-tree cursor is closed. All subsequent
68598 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
68599 ** immediately return SQLITE_ABORT.
68601 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
68602 int rc; /* Error code */
68603 char *zErr = 0; /* Error message */
68604 Vdbe *v = (Vdbe *)p->pStmt;
68606 /* Set the value of the SQL statements only variable to integer iRow.
68607 ** This is done directly instead of using sqlite3_bind_int64() to avoid
68608 ** triggering asserts related to mutexes.
68610 assert( v->aVar[0].flags&MEM_Int );
68611 v->aVar[0].u.i = iRow;
68613 rc = sqlite3_step(p->pStmt);
68614 if( rc==SQLITE_ROW ){
68615 u32 type = v->apCsr[0]->aType[p->iCol];
68616 if( type<12 ){
68617 zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
68618 type==0?"null": type==7?"real": "integer"
68620 rc = SQLITE_ERROR;
68621 sqlite3_finalize(p->pStmt);
68622 p->pStmt = 0;
68623 }else{
68624 p->iOffset = v->apCsr[0]->aOffset[p->iCol];
68625 p->nByte = sqlite3VdbeSerialTypeLen(type);
68626 p->pCsr = v->apCsr[0]->pCursor;
68627 sqlite3BtreeEnterCursor(p->pCsr);
68628 sqlite3BtreeCacheOverflow(p->pCsr);
68629 sqlite3BtreeLeaveCursor(p->pCsr);
68633 if( rc==SQLITE_ROW ){
68634 rc = SQLITE_OK;
68635 }else if( p->pStmt ){
68636 rc = sqlite3_finalize(p->pStmt);
68637 p->pStmt = 0;
68638 if( rc==SQLITE_OK ){
68639 zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
68640 rc = SQLITE_ERROR;
68641 }else{
68642 zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
68646 assert( rc!=SQLITE_OK || zErr==0 );
68647 assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
68649 *pzErr = zErr;
68650 return rc;
68654 ** Open a blob handle.
68656 SQLITE_API int sqlite3_blob_open(
68657 sqlite3* db, /* The database connection */
68658 const char *zDb, /* The attached database containing the blob */
68659 const char *zTable, /* The table containing the blob */
68660 const char *zColumn, /* The column containing the blob */
68661 sqlite_int64 iRow, /* The row containing the glob */
68662 int flags, /* True -> read/write access, false -> read-only */
68663 sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
68665 int nAttempt = 0;
68666 int iCol; /* Index of zColumn in row-record */
68668 /* This VDBE program seeks a btree cursor to the identified
68669 ** db/table/row entry. The reason for using a vdbe program instead
68670 ** of writing code to use the b-tree layer directly is that the
68671 ** vdbe program will take advantage of the various transaction,
68672 ** locking and error handling infrastructure built into the vdbe.
68674 ** After seeking the cursor, the vdbe executes an OP_ResultRow.
68675 ** Code external to the Vdbe then "borrows" the b-tree cursor and
68676 ** uses it to implement the blob_read(), blob_write() and
68677 ** blob_bytes() functions.
68679 ** The sqlite3_blob_close() function finalizes the vdbe program,
68680 ** which closes the b-tree cursor and (possibly) commits the
68681 ** transaction.
68683 static const VdbeOpList openBlob[] = {
68684 {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
68685 {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
68686 {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
68688 /* One of the following two instructions is replaced by an OP_Noop. */
68689 {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
68690 {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
68692 {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
68693 {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
68694 {OP_Column, 0, 0, 1}, /* 7 */
68695 {OP_ResultRow, 1, 0, 0}, /* 8 */
68696 {OP_Goto, 0, 5, 0}, /* 9 */
68697 {OP_Close, 0, 0, 0}, /* 10 */
68698 {OP_Halt, 0, 0, 0}, /* 11 */
68701 int rc = SQLITE_OK;
68702 char *zErr = 0;
68703 Table *pTab;
68704 Parse *pParse = 0;
68705 Incrblob *pBlob = 0;
68707 flags = !!flags; /* flags = (flags ? 1 : 0); */
68708 *ppBlob = 0;
68710 sqlite3_mutex_enter(db->mutex);
68712 pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
68713 if( !pBlob ) goto blob_open_out;
68714 pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
68715 if( !pParse ) goto blob_open_out;
68717 do {
68718 memset(pParse, 0, sizeof(Parse));
68719 pParse->db = db;
68720 sqlite3DbFree(db, zErr);
68721 zErr = 0;
68723 sqlite3BtreeEnterAll(db);
68724 pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
68725 if( pTab && IsVirtual(pTab) ){
68726 pTab = 0;
68727 sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
68729 #ifndef SQLITE_OMIT_VIEW
68730 if( pTab && pTab->pSelect ){
68731 pTab = 0;
68732 sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
68734 #endif
68735 if( !pTab ){
68736 if( pParse->zErrMsg ){
68737 sqlite3DbFree(db, zErr);
68738 zErr = pParse->zErrMsg;
68739 pParse->zErrMsg = 0;
68741 rc = SQLITE_ERROR;
68742 sqlite3BtreeLeaveAll(db);
68743 goto blob_open_out;
68746 /* Now search pTab for the exact column. */
68747 for(iCol=0; iCol<pTab->nCol; iCol++) {
68748 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
68749 break;
68752 if( iCol==pTab->nCol ){
68753 sqlite3DbFree(db, zErr);
68754 zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
68755 rc = SQLITE_ERROR;
68756 sqlite3BtreeLeaveAll(db);
68757 goto blob_open_out;
68760 /* If the value is being opened for writing, check that the
68761 ** column is not indexed, and that it is not part of a foreign key.
68762 ** It is against the rules to open a column to which either of these
68763 ** descriptions applies for writing. */
68764 if( flags ){
68765 const char *zFault = 0;
68766 Index *pIdx;
68767 #ifndef SQLITE_OMIT_FOREIGN_KEY
68768 if( db->flags&SQLITE_ForeignKeys ){
68769 /* Check that the column is not part of an FK child key definition. It
68770 ** is not necessary to check if it is part of a parent key, as parent
68771 ** key columns must be indexed. The check below will pick up this
68772 ** case. */
68773 FKey *pFKey;
68774 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
68775 int j;
68776 for(j=0; j<pFKey->nCol; j++){
68777 if( pFKey->aCol[j].iFrom==iCol ){
68778 zFault = "foreign key";
68783 #endif
68784 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68785 int j;
68786 for(j=0; j<pIdx->nColumn; j++){
68787 if( pIdx->aiColumn[j]==iCol ){
68788 zFault = "indexed";
68792 if( zFault ){
68793 sqlite3DbFree(db, zErr);
68794 zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
68795 rc = SQLITE_ERROR;
68796 sqlite3BtreeLeaveAll(db);
68797 goto blob_open_out;
68801 pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
68802 assert( pBlob->pStmt || db->mallocFailed );
68803 if( pBlob->pStmt ){
68804 Vdbe *v = (Vdbe *)pBlob->pStmt;
68805 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68807 sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
68810 /* Configure the OP_Transaction */
68811 sqlite3VdbeChangeP1(v, 0, iDb);
68812 sqlite3VdbeChangeP2(v, 0, flags);
68814 /* Configure the OP_VerifyCookie */
68815 sqlite3VdbeChangeP1(v, 1, iDb);
68816 sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
68817 sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
68819 /* Make sure a mutex is held on the table to be accessed */
68820 sqlite3VdbeUsesBtree(v, iDb);
68822 /* Configure the OP_TableLock instruction */
68823 #ifdef SQLITE_OMIT_SHARED_CACHE
68824 sqlite3VdbeChangeToNoop(v, 2, 1);
68825 #else
68826 sqlite3VdbeChangeP1(v, 2, iDb);
68827 sqlite3VdbeChangeP2(v, 2, pTab->tnum);
68828 sqlite3VdbeChangeP3(v, 2, flags);
68829 sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
68830 #endif
68832 /* Remove either the OP_OpenWrite or OpenRead. Set the P2
68833 ** parameter of the other to pTab->tnum. */
68834 sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
68835 sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
68836 sqlite3VdbeChangeP3(v, 3 + flags, iDb);
68838 /* Configure the number of columns. Configure the cursor to
68839 ** think that the table has one more column than it really
68840 ** does. An OP_Column to retrieve this imaginary column will
68841 ** always return an SQL NULL. This is useful because it means
68842 ** we can invoke OP_Column to fill in the vdbe cursors type
68843 ** and offset cache without causing any IO.
68845 sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
68846 sqlite3VdbeChangeP2(v, 7, pTab->nCol);
68847 if( !db->mallocFailed ){
68848 sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
68852 pBlob->flags = flags;
68853 pBlob->iCol = iCol;
68854 pBlob->db = db;
68855 sqlite3BtreeLeaveAll(db);
68856 if( db->mallocFailed ){
68857 goto blob_open_out;
68859 sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
68860 rc = blobSeekToRow(pBlob, iRow, &zErr);
68861 } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
68863 blob_open_out:
68864 if( rc==SQLITE_OK && db->mallocFailed==0 ){
68865 *ppBlob = (sqlite3_blob *)pBlob;
68866 }else{
68867 if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
68868 sqlite3DbFree(db, pBlob);
68870 sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
68871 sqlite3DbFree(db, zErr);
68872 sqlite3StackFree(db, pParse);
68873 rc = sqlite3ApiExit(db, rc);
68874 sqlite3_mutex_leave(db->mutex);
68875 return rc;
68879 ** Close a blob handle that was previously created using
68880 ** sqlite3_blob_open().
68882 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
68883 Incrblob *p = (Incrblob *)pBlob;
68884 int rc;
68885 sqlite3 *db;
68887 if( p ){
68888 db = p->db;
68889 sqlite3_mutex_enter(db->mutex);
68890 rc = sqlite3_finalize(p->pStmt);
68891 sqlite3DbFree(db, p);
68892 sqlite3_mutex_leave(db->mutex);
68893 }else{
68894 rc = SQLITE_OK;
68896 return rc;
68900 ** Perform a read or write operation on a blob
68902 static int blobReadWrite(
68903 sqlite3_blob *pBlob,
68904 void *z,
68905 int n,
68906 int iOffset,
68907 int (*xCall)(BtCursor*, u32, u32, void*)
68909 int rc;
68910 Incrblob *p = (Incrblob *)pBlob;
68911 Vdbe *v;
68912 sqlite3 *db;
68914 if( p==0 ) return SQLITE_MISUSE_BKPT;
68915 db = p->db;
68916 sqlite3_mutex_enter(db->mutex);
68917 v = (Vdbe*)p->pStmt;
68919 if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
68920 /* Request is out of range. Return a transient error. */
68921 rc = SQLITE_ERROR;
68922 sqlite3Error(db, SQLITE_ERROR, 0);
68923 }else if( v==0 ){
68924 /* If there is no statement handle, then the blob-handle has
68925 ** already been invalidated. Return SQLITE_ABORT in this case.
68927 rc = SQLITE_ABORT;
68928 }else{
68929 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
68930 ** returned, clean-up the statement handle.
68932 assert( db == v->db );
68933 sqlite3BtreeEnterCursor(p->pCsr);
68934 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
68935 sqlite3BtreeLeaveCursor(p->pCsr);
68936 if( rc==SQLITE_ABORT ){
68937 sqlite3VdbeFinalize(v);
68938 p->pStmt = 0;
68939 }else{
68940 db->errCode = rc;
68941 v->rc = rc;
68944 rc = sqlite3ApiExit(db, rc);
68945 sqlite3_mutex_leave(db->mutex);
68946 return rc;
68950 ** Read data from a blob handle.
68952 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
68953 return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
68957 ** Write data to a blob handle.
68959 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
68960 return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
68964 ** Query a blob handle for the size of the data.
68966 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
68967 ** so no mutex is required for access.
68969 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
68970 Incrblob *p = (Incrblob *)pBlob;
68971 return (p && p->pStmt) ? p->nByte : 0;
68975 ** Move an existing blob handle to point to a different row of the same
68976 ** database table.
68978 ** If an error occurs, or if the specified row does not exist or does not
68979 ** contain a blob or text value, then an error code is returned and the
68980 ** database handle error code and message set. If this happens, then all
68981 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
68982 ** immediately return SQLITE_ABORT.
68984 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
68985 int rc;
68986 Incrblob *p = (Incrblob *)pBlob;
68987 sqlite3 *db;
68989 if( p==0 ) return SQLITE_MISUSE_BKPT;
68990 db = p->db;
68991 sqlite3_mutex_enter(db->mutex);
68993 if( p->pStmt==0 ){
68994 /* If there is no statement handle, then the blob-handle has
68995 ** already been invalidated. Return SQLITE_ABORT in this case.
68997 rc = SQLITE_ABORT;
68998 }else{
68999 char *zErr;
69000 rc = blobSeekToRow(p, iRow, &zErr);
69001 if( rc!=SQLITE_OK ){
69002 sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
69003 sqlite3DbFree(db, zErr);
69005 assert( rc!=SQLITE_SCHEMA );
69008 rc = sqlite3ApiExit(db, rc);
69009 assert( rc==SQLITE_OK || p->pStmt==0 );
69010 sqlite3_mutex_leave(db->mutex);
69011 return rc;
69014 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
69016 /************** End of vdbeblob.c ********************************************/
69017 /************** Begin file journal.c *****************************************/
69019 ** 2007 August 22
69021 ** The author disclaims copyright to this source code. In place of
69022 ** a legal notice, here is a blessing:
69024 ** May you do good and not evil.
69025 ** May you find forgiveness for yourself and forgive others.
69026 ** May you share freely, never taking more than you give.
69028 *************************************************************************
69030 ** This file implements a special kind of sqlite3_file object used
69031 ** by SQLite to create journal files if the atomic-write optimization
69032 ** is enabled.
69034 ** The distinctive characteristic of this sqlite3_file is that the
69035 ** actual on disk file is created lazily. When the file is created,
69036 ** the caller specifies a buffer size for an in-memory buffer to
69037 ** be used to service read() and write() requests. The actual file
69038 ** on disk is not created or populated until either:
69040 ** 1) The in-memory representation grows too large for the allocated
69041 ** buffer, or
69042 ** 2) The sqlite3JournalCreate() function is called.
69044 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
69048 ** A JournalFile object is a subclass of sqlite3_file used by
69049 ** as an open file handle for journal files.
69051 struct JournalFile {
69052 sqlite3_io_methods *pMethod; /* I/O methods on journal files */
69053 int nBuf; /* Size of zBuf[] in bytes */
69054 char *zBuf; /* Space to buffer journal writes */
69055 int iSize; /* Amount of zBuf[] currently used */
69056 int flags; /* xOpen flags */
69057 sqlite3_vfs *pVfs; /* The "real" underlying VFS */
69058 sqlite3_file *pReal; /* The "real" underlying file descriptor */
69059 const char *zJournal; /* Name of the journal file */
69061 typedef struct JournalFile JournalFile;
69064 ** If it does not already exists, create and populate the on-disk file
69065 ** for JournalFile p.
69067 static int createFile(JournalFile *p){
69068 int rc = SQLITE_OK;
69069 if( !p->pReal ){
69070 sqlite3_file *pReal = (sqlite3_file *)&p[1];
69071 rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
69072 if( rc==SQLITE_OK ){
69073 p->pReal = pReal;
69074 if( p->iSize>0 ){
69075 assert(p->iSize<=p->nBuf);
69076 rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
69080 return rc;
69084 ** Close the file.
69086 static int jrnlClose(sqlite3_file *pJfd){
69087 JournalFile *p = (JournalFile *)pJfd;
69088 if( p->pReal ){
69089 sqlite3OsClose(p->pReal);
69091 sqlite3_free(p->zBuf);
69092 return SQLITE_OK;
69096 ** Read data from the file.
69098 static int jrnlRead(
69099 sqlite3_file *pJfd, /* The journal file from which to read */
69100 void *zBuf, /* Put the results here */
69101 int iAmt, /* Number of bytes to read */
69102 sqlite_int64 iOfst /* Begin reading at this offset */
69104 int rc = SQLITE_OK;
69105 JournalFile *p = (JournalFile *)pJfd;
69106 if( p->pReal ){
69107 rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
69108 }else if( (iAmt+iOfst)>p->iSize ){
69109 rc = SQLITE_IOERR_SHORT_READ;
69110 }else{
69111 memcpy(zBuf, &p->zBuf[iOfst], iAmt);
69113 return rc;
69117 ** Write data to the file.
69119 static int jrnlWrite(
69120 sqlite3_file *pJfd, /* The journal file into which to write */
69121 const void *zBuf, /* Take data to be written from here */
69122 int iAmt, /* Number of bytes to write */
69123 sqlite_int64 iOfst /* Begin writing at this offset into the file */
69125 int rc = SQLITE_OK;
69126 JournalFile *p = (JournalFile *)pJfd;
69127 if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
69128 rc = createFile(p);
69130 if( rc==SQLITE_OK ){
69131 if( p->pReal ){
69132 rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
69133 }else{
69134 memcpy(&p->zBuf[iOfst], zBuf, iAmt);
69135 if( p->iSize<(iOfst+iAmt) ){
69136 p->iSize = (iOfst+iAmt);
69140 return rc;
69144 ** Truncate the file.
69146 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
69147 int rc = SQLITE_OK;
69148 JournalFile *p = (JournalFile *)pJfd;
69149 if( p->pReal ){
69150 rc = sqlite3OsTruncate(p->pReal, size);
69151 }else if( size<p->iSize ){
69152 p->iSize = size;
69154 return rc;
69158 ** Sync the file.
69160 static int jrnlSync(sqlite3_file *pJfd, int flags){
69161 int rc;
69162 JournalFile *p = (JournalFile *)pJfd;
69163 if( p->pReal ){
69164 rc = sqlite3OsSync(p->pReal, flags);
69165 }else{
69166 rc = SQLITE_OK;
69168 return rc;
69172 ** Query the size of the file in bytes.
69174 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
69175 int rc = SQLITE_OK;
69176 JournalFile *p = (JournalFile *)pJfd;
69177 if( p->pReal ){
69178 rc = sqlite3OsFileSize(p->pReal, pSize);
69179 }else{
69180 *pSize = (sqlite_int64) p->iSize;
69182 return rc;
69186 ** Table of methods for JournalFile sqlite3_file object.
69188 static struct sqlite3_io_methods JournalFileMethods = {
69189 1, /* iVersion */
69190 jrnlClose, /* xClose */
69191 jrnlRead, /* xRead */
69192 jrnlWrite, /* xWrite */
69193 jrnlTruncate, /* xTruncate */
69194 jrnlSync, /* xSync */
69195 jrnlFileSize, /* xFileSize */
69196 0, /* xLock */
69197 0, /* xUnlock */
69198 0, /* xCheckReservedLock */
69199 0, /* xFileControl */
69200 0, /* xSectorSize */
69201 0, /* xDeviceCharacteristics */
69202 0, /* xShmMap */
69203 0, /* xShmLock */
69204 0, /* xShmBarrier */
69205 0 /* xShmUnmap */
69209 ** Open a journal file.
69211 SQLITE_PRIVATE int sqlite3JournalOpen(
69212 sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
69213 const char *zName, /* Name of the journal file */
69214 sqlite3_file *pJfd, /* Preallocated, blank file handle */
69215 int flags, /* Opening flags */
69216 int nBuf /* Bytes buffered before opening the file */
69218 JournalFile *p = (JournalFile *)pJfd;
69219 memset(p, 0, sqlite3JournalSize(pVfs));
69220 if( nBuf>0 ){
69221 p->zBuf = sqlite3MallocZero(nBuf);
69222 if( !p->zBuf ){
69223 return SQLITE_NOMEM;
69225 }else{
69226 return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
69228 p->pMethod = &JournalFileMethods;
69229 p->nBuf = nBuf;
69230 p->flags = flags;
69231 p->zJournal = zName;
69232 p->pVfs = pVfs;
69233 return SQLITE_OK;
69237 ** If the argument p points to a JournalFile structure, and the underlying
69238 ** file has not yet been created, create it now.
69240 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
69241 if( p->pMethods!=&JournalFileMethods ){
69242 return SQLITE_OK;
69244 return createFile((JournalFile *)p);
69248 ** Return the number of bytes required to store a JournalFile that uses vfs
69249 ** pVfs to create the underlying on-disk files.
69251 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
69252 return (pVfs->szOsFile+sizeof(JournalFile));
69254 #endif
69256 /************** End of journal.c *********************************************/
69257 /************** Begin file memjournal.c **************************************/
69259 ** 2008 October 7
69261 ** The author disclaims copyright to this source code. In place of
69262 ** a legal notice, here is a blessing:
69264 ** May you do good and not evil.
69265 ** May you find forgiveness for yourself and forgive others.
69266 ** May you share freely, never taking more than you give.
69268 *************************************************************************
69270 ** This file contains code use to implement an in-memory rollback journal.
69271 ** The in-memory rollback journal is used to journal transactions for
69272 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
69275 /* Forward references to internal structures */
69276 typedef struct MemJournal MemJournal;
69277 typedef struct FilePoint FilePoint;
69278 typedef struct FileChunk FileChunk;
69280 /* Space to hold the rollback journal is allocated in increments of
69281 ** this many bytes.
69283 ** The size chosen is a little less than a power of two. That way,
69284 ** the FileChunk object will have a size that almost exactly fills
69285 ** a power-of-two allocation. This mimimizes wasted space in power-of-two
69286 ** memory allocators.
69288 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
69290 /* Macro to find the minimum of two numeric values.
69292 #ifndef MIN
69293 # define MIN(x,y) ((x)<(y)?(x):(y))
69294 #endif
69297 ** The rollback journal is composed of a linked list of these structures.
69299 struct FileChunk {
69300 FileChunk *pNext; /* Next chunk in the journal */
69301 u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
69305 ** An instance of this object serves as a cursor into the rollback journal.
69306 ** The cursor can be either for reading or writing.
69308 struct FilePoint {
69309 sqlite3_int64 iOffset; /* Offset from the beginning of the file */
69310 FileChunk *pChunk; /* Specific chunk into which cursor points */
69314 ** This subclass is a subclass of sqlite3_file. Each open memory-journal
69315 ** is an instance of this class.
69317 struct MemJournal {
69318 sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
69319 FileChunk *pFirst; /* Head of in-memory chunk-list */
69320 FilePoint endpoint; /* Pointer to the end of the file */
69321 FilePoint readpoint; /* Pointer to the end of the last xRead() */
69325 ** Read data from the in-memory journal file. This is the implementation
69326 ** of the sqlite3_vfs.xRead method.
69328 static int memjrnlRead(
69329 sqlite3_file *pJfd, /* The journal file from which to read */
69330 void *zBuf, /* Put the results here */
69331 int iAmt, /* Number of bytes to read */
69332 sqlite_int64 iOfst /* Begin reading at this offset */
69334 MemJournal *p = (MemJournal *)pJfd;
69335 u8 *zOut = zBuf;
69336 int nRead = iAmt;
69337 int iChunkOffset;
69338 FileChunk *pChunk;
69340 /* SQLite never tries to read past the end of a rollback journal file */
69341 assert( iOfst+iAmt<=p->endpoint.iOffset );
69343 if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
69344 sqlite3_int64 iOff = 0;
69345 for(pChunk=p->pFirst;
69346 ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
69347 pChunk=pChunk->pNext
69349 iOff += JOURNAL_CHUNKSIZE;
69351 }else{
69352 pChunk = p->readpoint.pChunk;
69355 iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
69356 do {
69357 int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
69358 int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
69359 memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
69360 zOut += nCopy;
69361 nRead -= iSpace;
69362 iChunkOffset = 0;
69363 } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
69364 p->readpoint.iOffset = iOfst+iAmt;
69365 p->readpoint.pChunk = pChunk;
69367 return SQLITE_OK;
69371 ** Write data to the file.
69373 static int memjrnlWrite(
69374 sqlite3_file *pJfd, /* The journal file into which to write */
69375 const void *zBuf, /* Take data to be written from here */
69376 int iAmt, /* Number of bytes to write */
69377 sqlite_int64 iOfst /* Begin writing at this offset into the file */
69379 MemJournal *p = (MemJournal *)pJfd;
69380 int nWrite = iAmt;
69381 u8 *zWrite = (u8 *)zBuf;
69383 /* An in-memory journal file should only ever be appended to. Random
69384 ** access writes are not required by sqlite.
69386 assert( iOfst==p->endpoint.iOffset );
69387 UNUSED_PARAMETER(iOfst);
69389 while( nWrite>0 ){
69390 FileChunk *pChunk = p->endpoint.pChunk;
69391 int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
69392 int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
69394 if( iChunkOffset==0 ){
69395 /* New chunk is required to extend the file. */
69396 FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
69397 if( !pNew ){
69398 return SQLITE_IOERR_NOMEM;
69400 pNew->pNext = 0;
69401 if( pChunk ){
69402 assert( p->pFirst );
69403 pChunk->pNext = pNew;
69404 }else{
69405 assert( !p->pFirst );
69406 p->pFirst = pNew;
69408 p->endpoint.pChunk = pNew;
69411 memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
69412 zWrite += iSpace;
69413 nWrite -= iSpace;
69414 p->endpoint.iOffset += iSpace;
69417 return SQLITE_OK;
69421 ** Truncate the file.
69423 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
69424 MemJournal *p = (MemJournal *)pJfd;
69425 FileChunk *pChunk;
69426 assert(size==0);
69427 UNUSED_PARAMETER(size);
69428 pChunk = p->pFirst;
69429 while( pChunk ){
69430 FileChunk *pTmp = pChunk;
69431 pChunk = pChunk->pNext;
69432 sqlite3_free(pTmp);
69434 sqlite3MemJournalOpen(pJfd);
69435 return SQLITE_OK;
69439 ** Close the file.
69441 static int memjrnlClose(sqlite3_file *pJfd){
69442 memjrnlTruncate(pJfd, 0);
69443 return SQLITE_OK;
69448 ** Sync the file.
69450 ** Syncing an in-memory journal is a no-op. And, in fact, this routine
69451 ** is never called in a working implementation. This implementation
69452 ** exists purely as a contingency, in case some malfunction in some other
69453 ** part of SQLite causes Sync to be called by mistake.
69455 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
69456 UNUSED_PARAMETER2(NotUsed, NotUsed2);
69457 return SQLITE_OK;
69461 ** Query the size of the file in bytes.
69463 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
69464 MemJournal *p = (MemJournal *)pJfd;
69465 *pSize = (sqlite_int64) p->endpoint.iOffset;
69466 return SQLITE_OK;
69470 ** Table of methods for MemJournal sqlite3_file object.
69472 static const struct sqlite3_io_methods MemJournalMethods = {
69473 1, /* iVersion */
69474 memjrnlClose, /* xClose */
69475 memjrnlRead, /* xRead */
69476 memjrnlWrite, /* xWrite */
69477 memjrnlTruncate, /* xTruncate */
69478 memjrnlSync, /* xSync */
69479 memjrnlFileSize, /* xFileSize */
69480 0, /* xLock */
69481 0, /* xUnlock */
69482 0, /* xCheckReservedLock */
69483 0, /* xFileControl */
69484 0, /* xSectorSize */
69485 0, /* xDeviceCharacteristics */
69486 0, /* xShmMap */
69487 0, /* xShmLock */
69488 0, /* xShmBarrier */
69489 0 /* xShmUnlock */
69493 ** Open a journal file.
69495 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
69496 MemJournal *p = (MemJournal *)pJfd;
69497 assert( EIGHT_BYTE_ALIGNMENT(p) );
69498 memset(p, 0, sqlite3MemJournalSize());
69499 p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
69503 ** Return true if the file-handle passed as an argument is
69504 ** an in-memory journal
69506 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
69507 return pJfd->pMethods==&MemJournalMethods;
69511 ** Return the number of bytes required to store a MemJournal file descriptor.
69513 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
69514 return sizeof(MemJournal);
69517 /************** End of memjournal.c ******************************************/
69518 /************** Begin file walker.c ******************************************/
69520 ** 2008 August 16
69522 ** The author disclaims copyright to this source code. In place of
69523 ** a legal notice, here is a blessing:
69525 ** May you do good and not evil.
69526 ** May you find forgiveness for yourself and forgive others.
69527 ** May you share freely, never taking more than you give.
69529 *************************************************************************
69530 ** This file contains routines used for walking the parser tree for
69531 ** an SQL statement.
69536 ** Walk an expression tree. Invoke the callback once for each node
69537 ** of the expression, while decending. (In other words, the callback
69538 ** is invoked before visiting children.)
69540 ** The return value from the callback should be one of the WRC_*
69541 ** constants to specify how to proceed with the walk.
69543 ** WRC_Continue Continue descending down the tree.
69545 ** WRC_Prune Do not descend into child nodes. But allow
69546 ** the walk to continue with sibling nodes.
69548 ** WRC_Abort Do no more callbacks. Unwind the stack and
69549 ** return the top-level walk call.
69551 ** The return value from this routine is WRC_Abort to abandon the tree walk
69552 ** and WRC_Continue to continue.
69554 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
69555 int rc;
69556 if( pExpr==0 ) return WRC_Continue;
69557 testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
69558 testcase( ExprHasProperty(pExpr, EP_Reduced) );
69559 rc = pWalker->xExprCallback(pWalker, pExpr);
69560 if( rc==WRC_Continue
69561 && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
69562 if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
69563 if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
69564 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69565 if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
69566 }else{
69567 if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
69570 return rc & WRC_Abort;
69574 ** Call sqlite3WalkExpr() for every expression in list p or until
69575 ** an abort request is seen.
69577 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
69578 int i;
69579 struct ExprList_item *pItem;
69580 if( p ){
69581 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
69582 if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
69585 return WRC_Continue;
69589 ** Walk all expressions associated with SELECT statement p. Do
69590 ** not invoke the SELECT callback on p, but do (of course) invoke
69591 ** any expr callbacks and SELECT callbacks that come from subqueries.
69592 ** Return WRC_Abort or WRC_Continue.
69594 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
69595 if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
69596 if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
69597 if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
69598 if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
69599 if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
69600 if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
69601 if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
69602 return WRC_Continue;
69606 ** Walk the parse trees associated with all subqueries in the
69607 ** FROM clause of SELECT statement p. Do not invoke the select
69608 ** callback on p, but do invoke it on each FROM clause subquery
69609 ** and on any subqueries further down in the tree. Return
69610 ** WRC_Abort or WRC_Continue;
69612 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
69613 SrcList *pSrc;
69614 int i;
69615 struct SrcList_item *pItem;
69617 pSrc = p->pSrc;
69618 if( ALWAYS(pSrc) ){
69619 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
69620 if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
69621 return WRC_Abort;
69625 return WRC_Continue;
69629 ** Call sqlite3WalkExpr() for every expression in Select statement p.
69630 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
69631 ** on the compound select chain, p->pPrior.
69633 ** Return WRC_Continue under normal conditions. Return WRC_Abort if
69634 ** there is an abort request.
69636 ** If the Walker does not have an xSelectCallback() then this routine
69637 ** is a no-op returning WRC_Continue.
69639 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
69640 int rc;
69641 if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
69642 rc = WRC_Continue;
69643 while( p ){
69644 rc = pWalker->xSelectCallback(pWalker, p);
69645 if( rc ) break;
69646 if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
69647 if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
69648 p = p->pPrior;
69650 return rc & WRC_Abort;
69653 /************** End of walker.c **********************************************/
69654 /************** Begin file resolve.c *****************************************/
69656 ** 2008 August 18
69658 ** The author disclaims copyright to this source code. In place of
69659 ** a legal notice, here is a blessing:
69661 ** May you do good and not evil.
69662 ** May you find forgiveness for yourself and forgive others.
69663 ** May you share freely, never taking more than you give.
69665 *************************************************************************
69667 ** This file contains routines used for walking the parser tree and
69668 ** resolve all identifiers by associating them with a particular
69669 ** table and column.
69673 ** Turn the pExpr expression into an alias for the iCol-th column of the
69674 ** result set in pEList.
69676 ** If the result set column is a simple column reference, then this routine
69677 ** makes an exact copy. But for any other kind of expression, this
69678 ** routine make a copy of the result set column as the argument to the
69679 ** TK_AS operator. The TK_AS operator causes the expression to be
69680 ** evaluated just once and then reused for each alias.
69682 ** The reason for suppressing the TK_AS term when the expression is a simple
69683 ** column reference is so that the column reference will be recognized as
69684 ** usable by indices within the WHERE clause processing logic.
69686 ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
69687 ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
69689 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
69691 ** Is equivalent to:
69693 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
69695 ** The result of random()%5 in the GROUP BY clause is probably different
69696 ** from the result in the result-set. We might fix this someday. Or
69697 ** then again, we might not...
69699 static void resolveAlias(
69700 Parse *pParse, /* Parsing context */
69701 ExprList *pEList, /* A result set */
69702 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
69703 Expr *pExpr, /* Transform this into an alias to the result set */
69704 const char *zType /* "GROUP" or "ORDER" or "" */
69706 Expr *pOrig; /* The iCol-th column of the result set */
69707 Expr *pDup; /* Copy of pOrig */
69708 sqlite3 *db; /* The database connection */
69710 assert( iCol>=0 && iCol<pEList->nExpr );
69711 pOrig = pEList->a[iCol].pExpr;
69712 assert( pOrig!=0 );
69713 assert( pOrig->flags & EP_Resolved );
69714 db = pParse->db;
69715 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
69716 pDup = sqlite3ExprDup(db, pOrig, 0);
69717 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
69718 if( pDup==0 ) return;
69719 if( pEList->a[iCol].iAlias==0 ){
69720 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
69722 pDup->iTable = pEList->a[iCol].iAlias;
69723 }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
69724 pDup = sqlite3ExprDup(db, pOrig, 0);
69725 if( pDup==0 ) return;
69726 }else{
69727 char *zToken = pOrig->u.zToken;
69728 assert( zToken!=0 );
69729 pOrig->u.zToken = 0;
69730 pDup = sqlite3ExprDup(db, pOrig, 0);
69731 pOrig->u.zToken = zToken;
69732 if( pDup==0 ) return;
69733 assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
69734 pDup->flags2 |= EP2_MallocedToken;
69735 pDup->u.zToken = sqlite3DbStrDup(db, zToken);
69737 if( pExpr->flags & EP_ExpCollate ){
69738 pDup->pColl = pExpr->pColl;
69739 pDup->flags |= EP_ExpCollate;
69742 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
69743 ** prevents ExprDelete() from deleting the Expr structure itself,
69744 ** allowing it to be repopulated by the memcpy() on the following line.
69746 ExprSetProperty(pExpr, EP_Static);
69747 sqlite3ExprDelete(db, pExpr);
69748 memcpy(pExpr, pDup, sizeof(*pExpr));
69749 sqlite3DbFree(db, pDup);
69753 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
69754 ** that name in the set of source tables in pSrcList and make the pExpr
69755 ** expression node refer back to that source column. The following changes
69756 ** are made to pExpr:
69758 ** pExpr->iDb Set the index in db->aDb[] of the database X
69759 ** (even if X is implied).
69760 ** pExpr->iTable Set to the cursor number for the table obtained
69761 ** from pSrcList.
69762 ** pExpr->pTab Points to the Table structure of X.Y (even if
69763 ** X and/or Y are implied.)
69764 ** pExpr->iColumn Set to the column number within the table.
69765 ** pExpr->op Set to TK_COLUMN.
69766 ** pExpr->pLeft Any expression this points to is deleted
69767 ** pExpr->pRight Any expression this points to is deleted.
69769 ** The zDb variable is the name of the database (the "X"). This value may be
69770 ** NULL meaning that name is of the form Y.Z or Z. Any available database
69771 ** can be used. The zTable variable is the name of the table (the "Y"). This
69772 ** value can be NULL if zDb is also NULL. If zTable is NULL it
69773 ** means that the form of the name is Z and that columns from any table
69774 ** can be used.
69776 ** If the name cannot be resolved unambiguously, leave an error message
69777 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
69779 static int lookupName(
69780 Parse *pParse, /* The parsing context */
69781 const char *zDb, /* Name of the database containing table, or NULL */
69782 const char *zTab, /* Name of table containing column, or NULL */
69783 const char *zCol, /* Name of the column. */
69784 NameContext *pNC, /* The name context used to resolve the name */
69785 Expr *pExpr /* Make this EXPR node point to the selected column */
69787 int i, j; /* Loop counters */
69788 int cnt = 0; /* Number of matching column names */
69789 int cntTab = 0; /* Number of matching table names */
69790 sqlite3 *db = pParse->db; /* The database connection */
69791 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
69792 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
69793 NameContext *pTopNC = pNC; /* First namecontext in the list */
69794 Schema *pSchema = 0; /* Schema of the expression */
69795 int isTrigger = 0;
69797 assert( pNC ); /* the name context cannot be NULL. */
69798 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
69799 assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
69801 /* Initialize the node to no-match */
69802 pExpr->iTable = -1;
69803 pExpr->pTab = 0;
69804 ExprSetIrreducible(pExpr);
69806 /* Start at the inner-most context and move outward until a match is found */
69807 while( pNC && cnt==0 ){
69808 ExprList *pEList;
69809 SrcList *pSrcList = pNC->pSrcList;
69811 if( pSrcList ){
69812 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
69813 Table *pTab;
69814 int iDb;
69815 Column *pCol;
69817 pTab = pItem->pTab;
69818 assert( pTab!=0 && pTab->zName!=0 );
69819 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69820 assert( pTab->nCol>0 );
69821 if( zTab ){
69822 if( pItem->zAlias ){
69823 char *zTabName = pItem->zAlias;
69824 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
69825 }else{
69826 char *zTabName = pTab->zName;
69827 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
69828 continue;
69830 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
69831 continue;
69835 if( 0==(cntTab++) ){
69836 pExpr->iTable = pItem->iCursor;
69837 pExpr->pTab = pTab;
69838 pSchema = pTab->pSchema;
69839 pMatch = pItem;
69841 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
69842 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
69843 IdList *pUsing;
69844 cnt++;
69845 pExpr->iTable = pItem->iCursor;
69846 pExpr->pTab = pTab;
69847 pMatch = pItem;
69848 pSchema = pTab->pSchema;
69849 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
69850 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
69851 if( i<pSrcList->nSrc-1 ){
69852 if( pItem[1].jointype & JT_NATURAL ){
69853 /* If this match occurred in the left table of a natural join,
69854 ** then skip the right table to avoid a duplicate match */
69855 pItem++;
69856 i++;
69857 }else if( (pUsing = pItem[1].pUsing)!=0 ){
69858 /* If this match occurs on a column that is in the USING clause
69859 ** of a join, skip the search of the right table of the join
69860 ** to avoid a duplicate match there. */
69861 int k;
69862 for(k=0; k<pUsing->nId; k++){
69863 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
69864 pItem++;
69865 i++;
69866 break;
69871 break;
69877 #ifndef SQLITE_OMIT_TRIGGER
69878 /* If we have not already resolved the name, then maybe
69879 ** it is a new.* or old.* trigger argument reference
69881 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
69882 int op = pParse->eTriggerOp;
69883 Table *pTab = 0;
69884 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
69885 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
69886 pExpr->iTable = 1;
69887 pTab = pParse->pTriggerTab;
69888 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
69889 pExpr->iTable = 0;
69890 pTab = pParse->pTriggerTab;
69893 if( pTab ){
69894 int iCol;
69895 pSchema = pTab->pSchema;
69896 cntTab++;
69897 for(iCol=0; iCol<pTab->nCol; iCol++){
69898 Column *pCol = &pTab->aCol[iCol];
69899 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
69900 if( iCol==pTab->iPKey ){
69901 iCol = -1;
69903 break;
69906 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
69907 iCol = -1; /* IMP: R-44911-55124 */
69909 if( iCol<pTab->nCol ){
69910 cnt++;
69911 if( iCol<0 ){
69912 pExpr->affinity = SQLITE_AFF_INTEGER;
69913 }else if( pExpr->iTable==0 ){
69914 testcase( iCol==31 );
69915 testcase( iCol==32 );
69916 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
69917 }else{
69918 testcase( iCol==31 );
69919 testcase( iCol==32 );
69920 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
69922 pExpr->iColumn = (i16)iCol;
69923 pExpr->pTab = pTab;
69924 isTrigger = 1;
69928 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
69931 ** Perhaps the name is a reference to the ROWID
69933 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
69934 cnt = 1;
69935 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
69936 pExpr->affinity = SQLITE_AFF_INTEGER;
69940 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
69941 ** might refer to an result-set alias. This happens, for example, when
69942 ** we are resolving names in the WHERE clause of the following command:
69944 ** SELECT a+b AS x FROM table WHERE x<10;
69946 ** In cases like this, replace pExpr with a copy of the expression that
69947 ** forms the result set entry ("a+b" in the example) and return immediately.
69948 ** Note that the expression in the result set should have already been
69949 ** resolved by the time the WHERE clause is resolved.
69951 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
69952 for(j=0; j<pEList->nExpr; j++){
69953 char *zAs = pEList->a[j].zName;
69954 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
69955 Expr *pOrig;
69956 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
69957 assert( pExpr->x.pList==0 );
69958 assert( pExpr->x.pSelect==0 );
69959 pOrig = pEList->a[j].pExpr;
69960 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
69961 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
69962 return WRC_Abort;
69964 resolveAlias(pParse, pEList, j, pExpr, "");
69965 cnt = 1;
69966 pMatch = 0;
69967 assert( zTab==0 && zDb==0 );
69968 goto lookupname_end;
69973 /* Advance to the next name context. The loop will exit when either
69974 ** we have a match (cnt>0) or when we run out of name contexts.
69976 if( cnt==0 ){
69977 pNC = pNC->pNext;
69982 ** If X and Y are NULL (in other words if only the column name Z is
69983 ** supplied) and the value of Z is enclosed in double-quotes, then
69984 ** Z is a string literal if it doesn't match any column names. In that
69985 ** case, we need to return right away and not make any changes to
69986 ** pExpr.
69988 ** Because no reference was made to outer contexts, the pNC->nRef
69989 ** fields are not changed in any context.
69991 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
69992 pExpr->op = TK_STRING;
69993 pExpr->pTab = 0;
69994 return WRC_Prune;
69998 ** cnt==0 means there was not match. cnt>1 means there were two or
69999 ** more matches. Either way, we have an error.
70001 if( cnt!=1 ){
70002 const char *zErr;
70003 zErr = cnt==0 ? "no such column" : "ambiguous column name";
70004 if( zDb ){
70005 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
70006 }else if( zTab ){
70007 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
70008 }else{
70009 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
70011 pParse->checkSchema = 1;
70012 pTopNC->nErr++;
70015 /* If a column from a table in pSrcList is referenced, then record
70016 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
70017 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
70018 ** column number is greater than the number of bits in the bitmask
70019 ** then set the high-order bit of the bitmask.
70021 if( pExpr->iColumn>=0 && pMatch!=0 ){
70022 int n = pExpr->iColumn;
70023 testcase( n==BMS-1 );
70024 if( n>=BMS ){
70025 n = BMS-1;
70027 assert( pMatch->iCursor==pExpr->iTable );
70028 pMatch->colUsed |= ((Bitmask)1)<<n;
70031 /* Clean up and return
70033 sqlite3ExprDelete(db, pExpr->pLeft);
70034 pExpr->pLeft = 0;
70035 sqlite3ExprDelete(db, pExpr->pRight);
70036 pExpr->pRight = 0;
70037 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
70038 lookupname_end:
70039 if( cnt==1 ){
70040 assert( pNC!=0 );
70041 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
70042 /* Increment the nRef value on all name contexts from TopNC up to
70043 ** the point where the name matched. */
70044 for(;;){
70045 assert( pTopNC!=0 );
70046 pTopNC->nRef++;
70047 if( pTopNC==pNC ) break;
70048 pTopNC = pTopNC->pNext;
70050 return WRC_Prune;
70051 } else {
70052 return WRC_Abort;
70057 ** Allocate and return a pointer to an expression to load the column iCol
70058 ** from datasource iSrc in SrcList pSrc.
70060 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
70061 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
70062 if( p ){
70063 struct SrcList_item *pItem = &pSrc->a[iSrc];
70064 p->pTab = pItem->pTab;
70065 p->iTable = pItem->iCursor;
70066 if( p->pTab->iPKey==iCol ){
70067 p->iColumn = -1;
70068 }else{
70069 p->iColumn = (ynVar)iCol;
70070 testcase( iCol==BMS );
70071 testcase( iCol==BMS-1 );
70072 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
70074 ExprSetProperty(p, EP_Resolved);
70076 return p;
70080 ** This routine is callback for sqlite3WalkExpr().
70082 ** Resolve symbolic names into TK_COLUMN operators for the current
70083 ** node in the expression tree. Return 0 to continue the search down
70084 ** the tree or 2 to abort the tree walk.
70086 ** This routine also does error checking and name resolution for
70087 ** function names. The operator for aggregate functions is changed
70088 ** to TK_AGG_FUNCTION.
70090 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
70091 NameContext *pNC;
70092 Parse *pParse;
70094 pNC = pWalker->u.pNC;
70095 assert( pNC!=0 );
70096 pParse = pNC->pParse;
70097 assert( pParse==pWalker->pParse );
70099 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
70100 ExprSetProperty(pExpr, EP_Resolved);
70101 #ifndef NDEBUG
70102 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
70103 SrcList *pSrcList = pNC->pSrcList;
70104 int i;
70105 for(i=0; i<pNC->pSrcList->nSrc; i++){
70106 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
70109 #endif
70110 switch( pExpr->op ){
70112 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
70113 /* The special operator TK_ROW means use the rowid for the first
70114 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
70115 ** clause processing on UPDATE and DELETE statements.
70117 case TK_ROW: {
70118 SrcList *pSrcList = pNC->pSrcList;
70119 struct SrcList_item *pItem;
70120 assert( pSrcList && pSrcList->nSrc==1 );
70121 pItem = pSrcList->a;
70122 pExpr->op = TK_COLUMN;
70123 pExpr->pTab = pItem->pTab;
70124 pExpr->iTable = pItem->iCursor;
70125 pExpr->iColumn = -1;
70126 pExpr->affinity = SQLITE_AFF_INTEGER;
70127 break;
70129 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
70131 /* A lone identifier is the name of a column.
70133 case TK_ID: {
70134 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
70137 /* A table name and column name: ID.ID
70138 ** Or a database, table and column: ID.ID.ID
70140 case TK_DOT: {
70141 const char *zColumn;
70142 const char *zTable;
70143 const char *zDb;
70144 Expr *pRight;
70146 /* if( pSrcList==0 ) break; */
70147 pRight = pExpr->pRight;
70148 if( pRight->op==TK_ID ){
70149 zDb = 0;
70150 zTable = pExpr->pLeft->u.zToken;
70151 zColumn = pRight->u.zToken;
70152 }else{
70153 assert( pRight->op==TK_DOT );
70154 zDb = pExpr->pLeft->u.zToken;
70155 zTable = pRight->pLeft->u.zToken;
70156 zColumn = pRight->pRight->u.zToken;
70158 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
70161 /* Resolve function names
70163 case TK_CONST_FUNC:
70164 case TK_FUNCTION: {
70165 ExprList *pList = pExpr->x.pList; /* The argument list */
70166 int n = pList ? pList->nExpr : 0; /* Number of arguments */
70167 int no_such_func = 0; /* True if no such function exists */
70168 int wrong_num_args = 0; /* True if wrong number of arguments */
70169 int is_agg = 0; /* True if is an aggregate function */
70170 int auth; /* Authorization to use the function */
70171 int nId; /* Number of characters in function name */
70172 const char *zId; /* The function name. */
70173 FuncDef *pDef; /* Information about the function */
70174 u8 enc = ENC(pParse->db); /* The database encoding */
70176 testcase( pExpr->op==TK_CONST_FUNC );
70177 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
70178 zId = pExpr->u.zToken;
70179 nId = sqlite3Strlen30(zId);
70180 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
70181 if( pDef==0 ){
70182 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
70183 if( pDef==0 ){
70184 no_such_func = 1;
70185 }else{
70186 wrong_num_args = 1;
70188 }else{
70189 is_agg = pDef->xFunc==0;
70191 #ifndef SQLITE_OMIT_AUTHORIZATION
70192 if( pDef ){
70193 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
70194 if( auth!=SQLITE_OK ){
70195 if( auth==SQLITE_DENY ){
70196 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
70197 pDef->zName);
70198 pNC->nErr++;
70200 pExpr->op = TK_NULL;
70201 return WRC_Prune;
70204 #endif
70205 if( is_agg && !pNC->allowAgg ){
70206 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
70207 pNC->nErr++;
70208 is_agg = 0;
70209 }else if( no_such_func ){
70210 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
70211 pNC->nErr++;
70212 }else if( wrong_num_args ){
70213 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
70214 nId, zId);
70215 pNC->nErr++;
70217 if( is_agg ){
70218 pExpr->op = TK_AGG_FUNCTION;
70219 pNC->hasAgg = 1;
70221 if( is_agg ) pNC->allowAgg = 0;
70222 sqlite3WalkExprList(pWalker, pList);
70223 if( is_agg ) pNC->allowAgg = 1;
70224 /* FIX ME: Compute pExpr->affinity based on the expected return
70225 ** type of the function
70227 return WRC_Prune;
70229 #ifndef SQLITE_OMIT_SUBQUERY
70230 case TK_SELECT:
70231 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
70232 #endif
70233 case TK_IN: {
70234 testcase( pExpr->op==TK_IN );
70235 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
70236 int nRef = pNC->nRef;
70237 #ifndef SQLITE_OMIT_CHECK
70238 if( pNC->isCheck ){
70239 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
70241 #endif
70242 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
70243 assert( pNC->nRef>=nRef );
70244 if( nRef!=pNC->nRef ){
70245 ExprSetProperty(pExpr, EP_VarSelect);
70248 break;
70250 #ifndef SQLITE_OMIT_CHECK
70251 case TK_VARIABLE: {
70252 if( pNC->isCheck ){
70253 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
70255 break;
70257 #endif
70259 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
70263 ** pEList is a list of expressions which are really the result set of the
70264 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
70265 ** This routine checks to see if pE is a simple identifier which corresponds
70266 ** to the AS-name of one of the terms of the expression list. If it is,
70267 ** this routine return an integer between 1 and N where N is the number of
70268 ** elements in pEList, corresponding to the matching entry. If there is
70269 ** no match, or if pE is not a simple identifier, then this routine
70270 ** return 0.
70272 ** pEList has been resolved. pE has not.
70274 static int resolveAsName(
70275 Parse *pParse, /* Parsing context for error messages */
70276 ExprList *pEList, /* List of expressions to scan */
70277 Expr *pE /* Expression we are trying to match */
70279 int i; /* Loop counter */
70281 UNUSED_PARAMETER(pParse);
70283 if( pE->op==TK_ID ){
70284 char *zCol = pE->u.zToken;
70285 for(i=0; i<pEList->nExpr; i++){
70286 char *zAs = pEList->a[i].zName;
70287 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
70288 return i+1;
70292 return 0;
70296 ** pE is a pointer to an expression which is a single term in the
70297 ** ORDER BY of a compound SELECT. The expression has not been
70298 ** name resolved.
70300 ** At the point this routine is called, we already know that the
70301 ** ORDER BY term is not an integer index into the result set. That
70302 ** case is handled by the calling routine.
70304 ** Attempt to match pE against result set columns in the left-most
70305 ** SELECT statement. Return the index i of the matching column,
70306 ** as an indication to the caller that it should sort by the i-th column.
70307 ** The left-most column is 1. In other words, the value returned is the
70308 ** same integer value that would be used in the SQL statement to indicate
70309 ** the column.
70311 ** If there is no match, return 0. Return -1 if an error occurs.
70313 static int resolveOrderByTermToExprList(
70314 Parse *pParse, /* Parsing context for error messages */
70315 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
70316 Expr *pE /* The specific ORDER BY term */
70318 int i; /* Loop counter */
70319 ExprList *pEList; /* The columns of the result set */
70320 NameContext nc; /* Name context for resolving pE */
70321 sqlite3 *db; /* Database connection */
70322 int rc; /* Return code from subprocedures */
70323 u8 savedSuppErr; /* Saved value of db->suppressErr */
70325 assert( sqlite3ExprIsInteger(pE, &i)==0 );
70326 pEList = pSelect->pEList;
70328 /* Resolve all names in the ORDER BY term expression
70330 memset(&nc, 0, sizeof(nc));
70331 nc.pParse = pParse;
70332 nc.pSrcList = pSelect->pSrc;
70333 nc.pEList = pEList;
70334 nc.allowAgg = 1;
70335 nc.nErr = 0;
70336 db = pParse->db;
70337 savedSuppErr = db->suppressErr;
70338 db->suppressErr = 1;
70339 rc = sqlite3ResolveExprNames(&nc, pE);
70340 db->suppressErr = savedSuppErr;
70341 if( rc ) return 0;
70343 /* Try to match the ORDER BY expression against an expression
70344 ** in the result set. Return an 1-based index of the matching
70345 ** result-set entry.
70347 for(i=0; i<pEList->nExpr; i++){
70348 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
70349 return i+1;
70353 /* If no match, return 0. */
70354 return 0;
70358 ** Generate an ORDER BY or GROUP BY term out-of-range error.
70360 static void resolveOutOfRangeError(
70361 Parse *pParse, /* The error context into which to write the error */
70362 const char *zType, /* "ORDER" or "GROUP" */
70363 int i, /* The index (1-based) of the term out of range */
70364 int mx /* Largest permissible value of i */
70366 sqlite3ErrorMsg(pParse,
70367 "%r %s BY term out of range - should be "
70368 "between 1 and %d", i, zType, mx);
70372 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
70373 ** each term of the ORDER BY clause is a constant integer between 1
70374 ** and N where N is the number of columns in the compound SELECT.
70376 ** ORDER BY terms that are already an integer between 1 and N are
70377 ** unmodified. ORDER BY terms that are integers outside the range of
70378 ** 1 through N generate an error. ORDER BY terms that are expressions
70379 ** are matched against result set expressions of compound SELECT
70380 ** beginning with the left-most SELECT and working toward the right.
70381 ** At the first match, the ORDER BY expression is transformed into
70382 ** the integer column number.
70384 ** Return the number of errors seen.
70386 static int resolveCompoundOrderBy(
70387 Parse *pParse, /* Parsing context. Leave error messages here */
70388 Select *pSelect /* The SELECT statement containing the ORDER BY */
70390 int i;
70391 ExprList *pOrderBy;
70392 ExprList *pEList;
70393 sqlite3 *db;
70394 int moreToDo = 1;
70396 pOrderBy = pSelect->pOrderBy;
70397 if( pOrderBy==0 ) return 0;
70398 db = pParse->db;
70399 #if SQLITE_MAX_COLUMN
70400 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70401 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
70402 return 1;
70404 #endif
70405 for(i=0; i<pOrderBy->nExpr; i++){
70406 pOrderBy->a[i].done = 0;
70408 pSelect->pNext = 0;
70409 while( pSelect->pPrior ){
70410 pSelect->pPrior->pNext = pSelect;
70411 pSelect = pSelect->pPrior;
70413 while( pSelect && moreToDo ){
70414 struct ExprList_item *pItem;
70415 moreToDo = 0;
70416 pEList = pSelect->pEList;
70417 assert( pEList!=0 );
70418 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70419 int iCol = -1;
70420 Expr *pE, *pDup;
70421 if( pItem->done ) continue;
70422 pE = pItem->pExpr;
70423 if( sqlite3ExprIsInteger(pE, &iCol) ){
70424 if( iCol<=0 || iCol>pEList->nExpr ){
70425 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
70426 return 1;
70428 }else{
70429 iCol = resolveAsName(pParse, pEList, pE);
70430 if( iCol==0 ){
70431 pDup = sqlite3ExprDup(db, pE, 0);
70432 if( !db->mallocFailed ){
70433 assert(pDup);
70434 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
70436 sqlite3ExprDelete(db, pDup);
70439 if( iCol>0 ){
70440 CollSeq *pColl = pE->pColl;
70441 int flags = pE->flags & EP_ExpCollate;
70442 sqlite3ExprDelete(db, pE);
70443 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
70444 if( pE==0 ) return 1;
70445 pE->pColl = pColl;
70446 pE->flags |= EP_IntValue | flags;
70447 pE->u.iValue = iCol;
70448 pItem->iCol = (u16)iCol;
70449 pItem->done = 1;
70450 }else{
70451 moreToDo = 1;
70454 pSelect = pSelect->pNext;
70456 for(i=0; i<pOrderBy->nExpr; i++){
70457 if( pOrderBy->a[i].done==0 ){
70458 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
70459 "column in the result set", i+1);
70460 return 1;
70463 return 0;
70467 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
70468 ** the SELECT statement pSelect. If any term is reference to a
70469 ** result set expression (as determined by the ExprList.a.iCol field)
70470 ** then convert that term into a copy of the corresponding result set
70471 ** column.
70473 ** If any errors are detected, add an error message to pParse and
70474 ** return non-zero. Return zero if no errors are seen.
70476 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
70477 Parse *pParse, /* Parsing context. Leave error messages here */
70478 Select *pSelect, /* The SELECT statement containing the clause */
70479 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
70480 const char *zType /* "ORDER" or "GROUP" */
70482 int i;
70483 sqlite3 *db = pParse->db;
70484 ExprList *pEList;
70485 struct ExprList_item *pItem;
70487 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
70488 #if SQLITE_MAX_COLUMN
70489 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70490 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
70491 return 1;
70493 #endif
70494 pEList = pSelect->pEList;
70495 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
70496 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70497 if( pItem->iCol ){
70498 if( pItem->iCol>pEList->nExpr ){
70499 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
70500 return 1;
70502 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
70505 return 0;
70509 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
70510 ** The Name context of the SELECT statement is pNC. zType is either
70511 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
70513 ** This routine resolves each term of the clause into an expression.
70514 ** If the order-by term is an integer I between 1 and N (where N is the
70515 ** number of columns in the result set of the SELECT) then the expression
70516 ** in the resolution is a copy of the I-th result-set expression. If
70517 ** the order-by term is an identify that corresponds to the AS-name of
70518 ** a result-set expression, then the term resolves to a copy of the
70519 ** result-set expression. Otherwise, the expression is resolved in
70520 ** the usual way - using sqlite3ResolveExprNames().
70522 ** This routine returns the number of errors. If errors occur, then
70523 ** an appropriate error message might be left in pParse. (OOM errors
70524 ** excepted.)
70526 static int resolveOrderGroupBy(
70527 NameContext *pNC, /* The name context of the SELECT statement */
70528 Select *pSelect, /* The SELECT statement holding pOrderBy */
70529 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
70530 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
70532 int i; /* Loop counter */
70533 int iCol; /* Column number */
70534 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
70535 Parse *pParse; /* Parsing context */
70536 int nResult; /* Number of terms in the result set */
70538 if( pOrderBy==0 ) return 0;
70539 nResult = pSelect->pEList->nExpr;
70540 pParse = pNC->pParse;
70541 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70542 Expr *pE = pItem->pExpr;
70543 iCol = resolveAsName(pParse, pSelect->pEList, pE);
70544 if( iCol>0 ){
70545 /* If an AS-name match is found, mark this ORDER BY column as being
70546 ** a copy of the iCol-th result-set column. The subsequent call to
70547 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
70548 ** copy of the iCol-th result-set expression. */
70549 pItem->iCol = (u16)iCol;
70550 continue;
70552 if( sqlite3ExprIsInteger(pE, &iCol) ){
70553 /* The ORDER BY term is an integer constant. Again, set the column
70554 ** number so that sqlite3ResolveOrderGroupBy() will convert the
70555 ** order-by term to a copy of the result-set expression */
70556 if( iCol<1 ){
70557 resolveOutOfRangeError(pParse, zType, i+1, nResult);
70558 return 1;
70560 pItem->iCol = (u16)iCol;
70561 continue;
70564 /* Otherwise, treat the ORDER BY term as an ordinary expression */
70565 pItem->iCol = 0;
70566 if( sqlite3ResolveExprNames(pNC, pE) ){
70567 return 1;
70570 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
70574 ** Resolve names in the SELECT statement p and all of its descendents.
70576 static int resolveSelectStep(Walker *pWalker, Select *p){
70577 NameContext *pOuterNC; /* Context that contains this SELECT */
70578 NameContext sNC; /* Name context of this SELECT */
70579 int isCompound; /* True if p is a compound select */
70580 int nCompound; /* Number of compound terms processed so far */
70581 Parse *pParse; /* Parsing context */
70582 ExprList *pEList; /* Result set expression list */
70583 int i; /* Loop counter */
70584 ExprList *pGroupBy; /* The GROUP BY clause */
70585 Select *pLeftmost; /* Left-most of SELECT of a compound */
70586 sqlite3 *db; /* Database connection */
70589 assert( p!=0 );
70590 if( p->selFlags & SF_Resolved ){
70591 return WRC_Prune;
70593 pOuterNC = pWalker->u.pNC;
70594 pParse = pWalker->pParse;
70595 db = pParse->db;
70597 /* Normally sqlite3SelectExpand() will be called first and will have
70598 ** already expanded this SELECT. However, if this is a subquery within
70599 ** an expression, sqlite3ResolveExprNames() will be called without a
70600 ** prior call to sqlite3SelectExpand(). When that happens, let
70601 ** sqlite3SelectPrep() do all of the processing for this SELECT.
70602 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
70603 ** this routine in the correct order.
70605 if( (p->selFlags & SF_Expanded)==0 ){
70606 sqlite3SelectPrep(pParse, p, pOuterNC);
70607 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
70610 isCompound = p->pPrior!=0;
70611 nCompound = 0;
70612 pLeftmost = p;
70613 while( p ){
70614 assert( (p->selFlags & SF_Expanded)!=0 );
70615 assert( (p->selFlags & SF_Resolved)==0 );
70616 p->selFlags |= SF_Resolved;
70618 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
70619 ** are not allowed to refer to any names, so pass an empty NameContext.
70621 memset(&sNC, 0, sizeof(sNC));
70622 sNC.pParse = pParse;
70623 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
70624 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
70625 return WRC_Abort;
70628 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
70629 ** resolve the result-set expression list.
70631 sNC.allowAgg = 1;
70632 sNC.pSrcList = p->pSrc;
70633 sNC.pNext = pOuterNC;
70635 /* Resolve names in the result set. */
70636 pEList = p->pEList;
70637 assert( pEList!=0 );
70638 for(i=0; i<pEList->nExpr; i++){
70639 Expr *pX = pEList->a[i].pExpr;
70640 if( sqlite3ResolveExprNames(&sNC, pX) ){
70641 return WRC_Abort;
70645 /* Recursively resolve names in all subqueries
70647 for(i=0; i<p->pSrc->nSrc; i++){
70648 struct SrcList_item *pItem = &p->pSrc->a[i];
70649 if( pItem->pSelect ){
70650 const char *zSavedContext = pParse->zAuthContext;
70651 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
70652 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
70653 pParse->zAuthContext = zSavedContext;
70654 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
70658 /* If there are no aggregate functions in the result-set, and no GROUP BY
70659 ** expression, do not allow aggregates in any of the other expressions.
70661 assert( (p->selFlags & SF_Aggregate)==0 );
70662 pGroupBy = p->pGroupBy;
70663 if( pGroupBy || sNC.hasAgg ){
70664 p->selFlags |= SF_Aggregate;
70665 }else{
70666 sNC.allowAgg = 0;
70669 /* If a HAVING clause is present, then there must be a GROUP BY clause.
70671 if( p->pHaving && !pGroupBy ){
70672 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
70673 return WRC_Abort;
70676 /* Add the expression list to the name-context before parsing the
70677 ** other expressions in the SELECT statement. This is so that
70678 ** expressions in the WHERE clause (etc.) can refer to expressions by
70679 ** aliases in the result set.
70681 ** Minor point: If this is the case, then the expression will be
70682 ** re-evaluated for each reference to it.
70684 sNC.pEList = p->pEList;
70685 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
70686 sqlite3ResolveExprNames(&sNC, p->pHaving)
70688 return WRC_Abort;
70691 /* The ORDER BY and GROUP BY clauses may not refer to terms in
70692 ** outer queries
70694 sNC.pNext = 0;
70695 sNC.allowAgg = 1;
70697 /* Process the ORDER BY clause for singleton SELECT statements.
70698 ** The ORDER BY clause for compounds SELECT statements is handled
70699 ** below, after all of the result-sets for all of the elements of
70700 ** the compound have been resolved.
70702 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
70703 return WRC_Abort;
70705 if( db->mallocFailed ){
70706 return WRC_Abort;
70709 /* Resolve the GROUP BY clause. At the same time, make sure
70710 ** the GROUP BY clause does not contain aggregate functions.
70712 if( pGroupBy ){
70713 struct ExprList_item *pItem;
70715 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
70716 return WRC_Abort;
70718 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
70719 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
70720 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
70721 "the GROUP BY clause");
70722 return WRC_Abort;
70727 /* Advance to the next term of the compound
70729 p = p->pPrior;
70730 nCompound++;
70733 /* Resolve the ORDER BY on a compound SELECT after all terms of
70734 ** the compound have been resolved.
70736 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
70737 return WRC_Abort;
70740 return WRC_Prune;
70744 ** This routine walks an expression tree and resolves references to
70745 ** table columns and result-set columns. At the same time, do error
70746 ** checking on function usage and set a flag if any aggregate functions
70747 ** are seen.
70749 ** To resolve table columns references we look for nodes (or subtrees) of the
70750 ** form X.Y.Z or Y.Z or just Z where
70752 ** X: The name of a database. Ex: "main" or "temp" or
70753 ** the symbolic name assigned to an ATTACH-ed database.
70755 ** Y: The name of a table in a FROM clause. Or in a trigger
70756 ** one of the special names "old" or "new".
70758 ** Z: The name of a column in table Y.
70760 ** The node at the root of the subtree is modified as follows:
70762 ** Expr.op Changed to TK_COLUMN
70763 ** Expr.pTab Points to the Table object for X.Y
70764 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
70765 ** Expr.iTable The VDBE cursor number for X.Y
70768 ** To resolve result-set references, look for expression nodes of the
70769 ** form Z (with no X and Y prefix) where the Z matches the right-hand
70770 ** size of an AS clause in the result-set of a SELECT. The Z expression
70771 ** is replaced by a copy of the left-hand side of the result-set expression.
70772 ** Table-name and function resolution occurs on the substituted expression
70773 ** tree. For example, in:
70775 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
70777 ** The "x" term of the order by is replaced by "a+b" to render:
70779 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
70781 ** Function calls are checked to make sure that the function is
70782 ** defined and that the correct number of arguments are specified.
70783 ** If the function is an aggregate function, then the pNC->hasAgg is
70784 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
70785 ** If an expression contains aggregate functions then the EP_Agg
70786 ** property on the expression is set.
70788 ** An error message is left in pParse if anything is amiss. The number
70789 ** if errors is returned.
70791 SQLITE_PRIVATE int sqlite3ResolveExprNames(
70792 NameContext *pNC, /* Namespace to resolve expressions in. */
70793 Expr *pExpr /* The expression to be analyzed. */
70795 int savedHasAgg;
70796 Walker w;
70798 if( pExpr==0 ) return 0;
70799 #if SQLITE_MAX_EXPR_DEPTH>0
70801 Parse *pParse = pNC->pParse;
70802 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
70803 return 1;
70805 pParse->nHeight += pExpr->nHeight;
70807 #endif
70808 savedHasAgg = pNC->hasAgg;
70809 pNC->hasAgg = 0;
70810 w.xExprCallback = resolveExprStep;
70811 w.xSelectCallback = resolveSelectStep;
70812 w.pParse = pNC->pParse;
70813 w.u.pNC = pNC;
70814 sqlite3WalkExpr(&w, pExpr);
70815 #if SQLITE_MAX_EXPR_DEPTH>0
70816 pNC->pParse->nHeight -= pExpr->nHeight;
70817 #endif
70818 if( pNC->nErr>0 || w.pParse->nErr>0 ){
70819 ExprSetProperty(pExpr, EP_Error);
70821 if( pNC->hasAgg ){
70822 ExprSetProperty(pExpr, EP_Agg);
70823 }else if( savedHasAgg ){
70824 pNC->hasAgg = 1;
70826 return ExprHasProperty(pExpr, EP_Error);
70831 ** Resolve all names in all expressions of a SELECT and in all
70832 ** decendents of the SELECT, including compounds off of p->pPrior,
70833 ** subqueries in expressions, and subqueries used as FROM clause
70834 ** terms.
70836 ** See sqlite3ResolveExprNames() for a description of the kinds of
70837 ** transformations that occur.
70839 ** All SELECT statements should have been expanded using
70840 ** sqlite3SelectExpand() prior to invoking this routine.
70842 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
70843 Parse *pParse, /* The parser context */
70844 Select *p, /* The SELECT statement being coded. */
70845 NameContext *pOuterNC /* Name context for parent SELECT statement */
70847 Walker w;
70849 assert( p!=0 );
70850 w.xExprCallback = resolveExprStep;
70851 w.xSelectCallback = resolveSelectStep;
70852 w.pParse = pParse;
70853 w.u.pNC = pOuterNC;
70854 sqlite3WalkSelect(&w, p);
70857 /************** End of resolve.c *********************************************/
70858 /************** Begin file expr.c ********************************************/
70860 ** 2001 September 15
70862 ** The author disclaims copyright to this source code. In place of
70863 ** a legal notice, here is a blessing:
70865 ** May you do good and not evil.
70866 ** May you find forgiveness for yourself and forgive others.
70867 ** May you share freely, never taking more than you give.
70869 *************************************************************************
70870 ** This file contains routines used for analyzing expressions and
70871 ** for generating VDBE code that evaluates expressions in SQLite.
70875 ** Return the 'affinity' of the expression pExpr if any.
70877 ** If pExpr is a column, a reference to a column via an 'AS' alias,
70878 ** or a sub-select with a column as the return value, then the
70879 ** affinity of that column is returned. Otherwise, 0x00 is returned,
70880 ** indicating no affinity for the expression.
70882 ** i.e. the WHERE clause expresssions in the following statements all
70883 ** have an affinity:
70885 ** CREATE TABLE t1(a);
70886 ** SELECT * FROM t1 WHERE a;
70887 ** SELECT a AS b FROM t1 WHERE b;
70888 ** SELECT * FROM t1 WHERE (select a from t1);
70890 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
70891 int op = pExpr->op;
70892 if( op==TK_SELECT ){
70893 assert( pExpr->flags&EP_xIsSelect );
70894 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
70896 #ifndef SQLITE_OMIT_CAST
70897 if( op==TK_CAST ){
70898 assert( !ExprHasProperty(pExpr, EP_IntValue) );
70899 return sqlite3AffinityType(pExpr->u.zToken);
70901 #endif
70902 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
70903 && pExpr->pTab!=0
70905 /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
70906 ** a TK_COLUMN but was previously evaluated and cached in a register */
70907 int j = pExpr->iColumn;
70908 if( j<0 ) return SQLITE_AFF_INTEGER;
70909 assert( pExpr->pTab && j<pExpr->pTab->nCol );
70910 return pExpr->pTab->aCol[j].affinity;
70912 return pExpr->affinity;
70916 ** Set the explicit collating sequence for an expression to the
70917 ** collating sequence supplied in the second argument.
70919 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
70920 if( pExpr && pColl ){
70921 pExpr->pColl = pColl;
70922 pExpr->flags |= EP_ExpCollate;
70924 return pExpr;
70928 ** Set the collating sequence for expression pExpr to be the collating
70929 ** sequence named by pToken. Return a pointer to the revised expression.
70930 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
70931 ** flag. An explicit collating sequence will override implicit
70932 ** collating sequences.
70934 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
70935 char *zColl = 0; /* Dequoted name of collation sequence */
70936 CollSeq *pColl;
70937 sqlite3 *db = pParse->db;
70938 zColl = sqlite3NameFromToken(db, pCollName);
70939 pColl = sqlite3LocateCollSeq(pParse, zColl);
70940 sqlite3ExprSetColl(pExpr, pColl);
70941 sqlite3DbFree(db, zColl);
70942 return pExpr;
70946 ** Return the default collation sequence for the expression pExpr. If
70947 ** there is no default collation type, return 0.
70949 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
70950 CollSeq *pColl = 0;
70951 Expr *p = pExpr;
70952 while( p ){
70953 int op;
70954 pColl = p->pColl;
70955 if( pColl ) break;
70956 op = p->op;
70957 if( p->pTab!=0 && (
70958 op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
70960 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
70961 ** a TK_COLUMN but was previously evaluated and cached in a register */
70962 const char *zColl;
70963 int j = p->iColumn;
70964 if( j>=0 ){
70965 sqlite3 *db = pParse->db;
70966 zColl = p->pTab->aCol[j].zColl;
70967 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
70968 pExpr->pColl = pColl;
70970 break;
70972 if( op!=TK_CAST && op!=TK_UPLUS ){
70973 break;
70975 p = p->pLeft;
70977 if( sqlite3CheckCollSeq(pParse, pColl) ){
70978 pColl = 0;
70980 return pColl;
70984 ** pExpr is an operand of a comparison operator. aff2 is the
70985 ** type affinity of the other operand. This routine returns the
70986 ** type affinity that should be used for the comparison operator.
70988 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
70989 char aff1 = sqlite3ExprAffinity(pExpr);
70990 if( aff1 && aff2 ){
70991 /* Both sides of the comparison are columns. If one has numeric
70992 ** affinity, use that. Otherwise use no affinity.
70994 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
70995 return SQLITE_AFF_NUMERIC;
70996 }else{
70997 return SQLITE_AFF_NONE;
70999 }else if( !aff1 && !aff2 ){
71000 /* Neither side of the comparison is a column. Compare the
71001 ** results directly.
71003 return SQLITE_AFF_NONE;
71004 }else{
71005 /* One side is a column, the other is not. Use the columns affinity. */
71006 assert( aff1==0 || aff2==0 );
71007 return (aff1 + aff2);
71012 ** pExpr is a comparison operator. Return the type affinity that should
71013 ** be applied to both operands prior to doing the comparison.
71015 static char comparisonAffinity(Expr *pExpr){
71016 char aff;
71017 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
71018 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
71019 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
71020 assert( pExpr->pLeft );
71021 aff = sqlite3ExprAffinity(pExpr->pLeft);
71022 if( pExpr->pRight ){
71023 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
71024 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
71025 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
71026 }else if( !aff ){
71027 aff = SQLITE_AFF_NONE;
71029 return aff;
71033 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
71034 ** idx_affinity is the affinity of an indexed column. Return true
71035 ** if the index with affinity idx_affinity may be used to implement
71036 ** the comparison in pExpr.
71038 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
71039 char aff = comparisonAffinity(pExpr);
71040 switch( aff ){
71041 case SQLITE_AFF_NONE:
71042 return 1;
71043 case SQLITE_AFF_TEXT:
71044 return idx_affinity==SQLITE_AFF_TEXT;
71045 default:
71046 return sqlite3IsNumericAffinity(idx_affinity);
71051 ** Return the P5 value that should be used for a binary comparison
71052 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
71054 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
71055 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
71056 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
71057 return aff;
71061 ** Return a pointer to the collation sequence that should be used by
71062 ** a binary comparison operator comparing pLeft and pRight.
71064 ** If the left hand expression has a collating sequence type, then it is
71065 ** used. Otherwise the collation sequence for the right hand expression
71066 ** is used, or the default (BINARY) if neither expression has a collating
71067 ** type.
71069 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
71070 ** it is not considered.
71072 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
71073 Parse *pParse,
71074 Expr *pLeft,
71075 Expr *pRight
71077 CollSeq *pColl;
71078 assert( pLeft );
71079 if( pLeft->flags & EP_ExpCollate ){
71080 assert( pLeft->pColl );
71081 pColl = pLeft->pColl;
71082 }else if( pRight && pRight->flags & EP_ExpCollate ){
71083 assert( pRight->pColl );
71084 pColl = pRight->pColl;
71085 }else{
71086 pColl = sqlite3ExprCollSeq(pParse, pLeft);
71087 if( !pColl ){
71088 pColl = sqlite3ExprCollSeq(pParse, pRight);
71091 return pColl;
71095 ** Generate code for a comparison operator.
71097 static int codeCompare(
71098 Parse *pParse, /* The parsing (and code generating) context */
71099 Expr *pLeft, /* The left operand */
71100 Expr *pRight, /* The right operand */
71101 int opcode, /* The comparison opcode */
71102 int in1, int in2, /* Register holding operands */
71103 int dest, /* Jump here if true. */
71104 int jumpIfNull /* If true, jump if either operand is NULL */
71106 int p5;
71107 int addr;
71108 CollSeq *p4;
71110 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
71111 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
71112 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
71113 (void*)p4, P4_COLLSEQ);
71114 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
71115 return addr;
71118 #if SQLITE_MAX_EXPR_DEPTH>0
71120 ** Check that argument nHeight is less than or equal to the maximum
71121 ** expression depth allowed. If it is not, leave an error message in
71122 ** pParse.
71124 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
71125 int rc = SQLITE_OK;
71126 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
71127 if( nHeight>mxHeight ){
71128 sqlite3ErrorMsg(pParse,
71129 "Expression tree is too large (maximum depth %d)", mxHeight
71131 rc = SQLITE_ERROR;
71133 return rc;
71136 /* The following three functions, heightOfExpr(), heightOfExprList()
71137 ** and heightOfSelect(), are used to determine the maximum height
71138 ** of any expression tree referenced by the structure passed as the
71139 ** first argument.
71141 ** If this maximum height is greater than the current value pointed
71142 ** to by pnHeight, the second parameter, then set *pnHeight to that
71143 ** value.
71145 static void heightOfExpr(Expr *p, int *pnHeight){
71146 if( p ){
71147 if( p->nHeight>*pnHeight ){
71148 *pnHeight = p->nHeight;
71152 static void heightOfExprList(ExprList *p, int *pnHeight){
71153 if( p ){
71154 int i;
71155 for(i=0; i<p->nExpr; i++){
71156 heightOfExpr(p->a[i].pExpr, pnHeight);
71160 static void heightOfSelect(Select *p, int *pnHeight){
71161 if( p ){
71162 heightOfExpr(p->pWhere, pnHeight);
71163 heightOfExpr(p->pHaving, pnHeight);
71164 heightOfExpr(p->pLimit, pnHeight);
71165 heightOfExpr(p->pOffset, pnHeight);
71166 heightOfExprList(p->pEList, pnHeight);
71167 heightOfExprList(p->pGroupBy, pnHeight);
71168 heightOfExprList(p->pOrderBy, pnHeight);
71169 heightOfSelect(p->pPrior, pnHeight);
71174 ** Set the Expr.nHeight variable in the structure passed as an
71175 ** argument. An expression with no children, Expr.pList or
71176 ** Expr.pSelect member has a height of 1. Any other expression
71177 ** has a height equal to the maximum height of any other
71178 ** referenced Expr plus one.
71180 static void exprSetHeight(Expr *p){
71181 int nHeight = 0;
71182 heightOfExpr(p->pLeft, &nHeight);
71183 heightOfExpr(p->pRight, &nHeight);
71184 if( ExprHasProperty(p, EP_xIsSelect) ){
71185 heightOfSelect(p->x.pSelect, &nHeight);
71186 }else{
71187 heightOfExprList(p->x.pList, &nHeight);
71189 p->nHeight = nHeight + 1;
71193 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
71194 ** the height is greater than the maximum allowed expression depth,
71195 ** leave an error in pParse.
71197 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
71198 exprSetHeight(p);
71199 sqlite3ExprCheckHeight(pParse, p->nHeight);
71203 ** Return the maximum height of any expression tree referenced
71204 ** by the select statement passed as an argument.
71206 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
71207 int nHeight = 0;
71208 heightOfSelect(p, &nHeight);
71209 return nHeight;
71211 #else
71212 #define exprSetHeight(y)
71213 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
71216 ** This routine is the core allocator for Expr nodes.
71218 ** Construct a new expression node and return a pointer to it. Memory
71219 ** for this node and for the pToken argument is a single allocation
71220 ** obtained from sqlite3DbMalloc(). The calling function
71221 ** is responsible for making sure the node eventually gets freed.
71223 ** If dequote is true, then the token (if it exists) is dequoted.
71224 ** If dequote is false, no dequoting is performance. The deQuote
71225 ** parameter is ignored if pToken is NULL or if the token does not
71226 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
71227 ** then the EP_DblQuoted flag is set on the expression node.
71229 ** Special case: If op==TK_INTEGER and pToken points to a string that
71230 ** can be translated into a 32-bit integer, then the token is not
71231 ** stored in u.zToken. Instead, the integer values is written
71232 ** into u.iValue and the EP_IntValue flag is set. No extra storage
71233 ** is allocated to hold the integer text and the dequote flag is ignored.
71235 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
71236 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
71237 int op, /* Expression opcode */
71238 const Token *pToken, /* Token argument. Might be NULL */
71239 int dequote /* True to dequote */
71241 Expr *pNew;
71242 int nExtra = 0;
71243 int iValue = 0;
71245 if( pToken ){
71246 if( op!=TK_INTEGER || pToken->z==0
71247 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
71248 nExtra = pToken->n+1;
71249 assert( iValue>=0 );
71252 pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
71253 if( pNew ){
71254 pNew->op = (u8)op;
71255 pNew->iAgg = -1;
71256 if( pToken ){
71257 if( nExtra==0 ){
71258 pNew->flags |= EP_IntValue;
71259 pNew->u.iValue = iValue;
71260 }else{
71261 int c;
71262 pNew->u.zToken = (char*)&pNew[1];
71263 memcpy(pNew->u.zToken, pToken->z, pToken->n);
71264 pNew->u.zToken[pToken->n] = 0;
71265 if( dequote && nExtra>=3
71266 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
71267 sqlite3Dequote(pNew->u.zToken);
71268 if( c=='"' ) pNew->flags |= EP_DblQuoted;
71272 #if SQLITE_MAX_EXPR_DEPTH>0
71273 pNew->nHeight = 1;
71274 #endif
71276 return pNew;
71280 ** Allocate a new expression node from a zero-terminated token that has
71281 ** already been dequoted.
71283 SQLITE_PRIVATE Expr *sqlite3Expr(
71284 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
71285 int op, /* Expression opcode */
71286 const char *zToken /* Token argument. Might be NULL */
71288 Token x;
71289 x.z = zToken;
71290 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
71291 return sqlite3ExprAlloc(db, op, &x, 0);
71295 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
71297 ** If pRoot==NULL that means that a memory allocation error has occurred.
71298 ** In that case, delete the subtrees pLeft and pRight.
71300 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
71301 sqlite3 *db,
71302 Expr *pRoot,
71303 Expr *pLeft,
71304 Expr *pRight
71306 if( pRoot==0 ){
71307 assert( db->mallocFailed );
71308 sqlite3ExprDelete(db, pLeft);
71309 sqlite3ExprDelete(db, pRight);
71310 }else{
71311 if( pRight ){
71312 pRoot->pRight = pRight;
71313 if( pRight->flags & EP_ExpCollate ){
71314 pRoot->flags |= EP_ExpCollate;
71315 pRoot->pColl = pRight->pColl;
71318 if( pLeft ){
71319 pRoot->pLeft = pLeft;
71320 if( pLeft->flags & EP_ExpCollate ){
71321 pRoot->flags |= EP_ExpCollate;
71322 pRoot->pColl = pLeft->pColl;
71325 exprSetHeight(pRoot);
71330 ** Allocate a Expr node which joins as many as two subtrees.
71332 ** One or both of the subtrees can be NULL. Return a pointer to the new
71333 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
71334 ** free the subtrees and return NULL.
71336 SQLITE_PRIVATE Expr *sqlite3PExpr(
71337 Parse *pParse, /* Parsing context */
71338 int op, /* Expression opcode */
71339 Expr *pLeft, /* Left operand */
71340 Expr *pRight, /* Right operand */
71341 const Token *pToken /* Argument token */
71343 Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
71344 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
71345 if( p ) {
71346 sqlite3ExprCheckHeight(pParse, p->nHeight);
71348 return p;
71352 ** Join two expressions using an AND operator. If either expression is
71353 ** NULL, then just return the other expression.
71355 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
71356 if( pLeft==0 ){
71357 return pRight;
71358 }else if( pRight==0 ){
71359 return pLeft;
71360 }else{
71361 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
71362 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
71363 return pNew;
71368 ** Construct a new expression node for a function with multiple
71369 ** arguments.
71371 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
71372 Expr *pNew;
71373 sqlite3 *db = pParse->db;
71374 assert( pToken );
71375 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
71376 if( pNew==0 ){
71377 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
71378 return 0;
71380 pNew->x.pList = pList;
71381 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
71382 sqlite3ExprSetHeight(pParse, pNew);
71383 return pNew;
71387 ** Assign a variable number to an expression that encodes a wildcard
71388 ** in the original SQL statement.
71390 ** Wildcards consisting of a single "?" are assigned the next sequential
71391 ** variable number.
71393 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
71394 ** sure "nnn" is not too be to avoid a denial of service attack when
71395 ** the SQL statement comes from an external source.
71397 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
71398 ** as the previous instance of the same wildcard. Or if this is the first
71399 ** instance of the wildcard, the next sequenial variable number is
71400 ** assigned.
71402 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
71403 sqlite3 *db = pParse->db;
71404 const char *z;
71406 if( pExpr==0 ) return;
71407 assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
71408 z = pExpr->u.zToken;
71409 assert( z!=0 );
71410 assert( z[0]!=0 );
71411 if( z[1]==0 ){
71412 /* Wildcard of the form "?". Assign the next variable number */
71413 assert( z[0]=='?' );
71414 pExpr->iColumn = (ynVar)(++pParse->nVar);
71415 }else if( z[0]=='?' ){
71416 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
71417 ** use it as the variable number */
71418 i64 i;
71419 int bOk = 0==sqlite3Atoi64(&z[1], &i, sqlite3Strlen30(&z[1]), SQLITE_UTF8);
71420 pExpr->iColumn = (ynVar)i;
71421 testcase( i==0 );
71422 testcase( i==1 );
71423 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
71424 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
71425 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71426 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
71427 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
71429 if( i>pParse->nVar ){
71430 pParse->nVar = (int)i;
71432 }else{
71433 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
71434 ** number as the prior appearance of the same name, or if the name
71435 ** has never appeared before, reuse the same variable number
71437 int i;
71438 u32 n;
71439 n = sqlite3Strlen30(z);
71440 for(i=0; i<pParse->nVarExpr; i++){
71441 Expr *pE = pParse->apVarExpr[i];
71442 assert( pE!=0 );
71443 if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
71444 pExpr->iColumn = pE->iColumn;
71445 break;
71448 if( i>=pParse->nVarExpr ){
71449 pExpr->iColumn = (ynVar)(++pParse->nVar);
71450 if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
71451 pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
71452 pParse->apVarExpr =
71453 sqlite3DbReallocOrFree(
71455 pParse->apVarExpr,
71456 pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
71459 if( !db->mallocFailed ){
71460 assert( pParse->apVarExpr!=0 );
71461 pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
71465 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71466 sqlite3ErrorMsg(pParse, "too many SQL variables");
71471 ** Recursively delete an expression tree.
71473 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
71474 if( p==0 ) return;
71475 /* Sanity check: Assert that the IntValue is non-negative if it exists */
71476 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
71477 if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
71478 sqlite3ExprDelete(db, p->pLeft);
71479 sqlite3ExprDelete(db, p->pRight);
71480 if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
71481 sqlite3DbFree(db, p->u.zToken);
71483 if( ExprHasProperty(p, EP_xIsSelect) ){
71484 sqlite3SelectDelete(db, p->x.pSelect);
71485 }else{
71486 sqlite3ExprListDelete(db, p->x.pList);
71489 if( !ExprHasProperty(p, EP_Static) ){
71490 sqlite3DbFree(db, p);
71495 ** Return the number of bytes allocated for the expression structure
71496 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
71497 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
71499 static int exprStructSize(Expr *p){
71500 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
71501 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
71502 return EXPR_FULLSIZE;
71506 ** The dupedExpr*Size() routines each return the number of bytes required
71507 ** to store a copy of an expression or expression tree. They differ in
71508 ** how much of the tree is measured.
71510 ** dupedExprStructSize() Size of only the Expr structure
71511 ** dupedExprNodeSize() Size of Expr + space for token
71512 ** dupedExprSize() Expr + token + subtree components
71514 ***************************************************************************
71516 ** The dupedExprStructSize() function returns two values OR-ed together:
71517 ** (1) the space required for a copy of the Expr structure only and
71518 ** (2) the EP_xxx flags that indicate what the structure size should be.
71519 ** The return values is always one of:
71521 ** EXPR_FULLSIZE
71522 ** EXPR_REDUCEDSIZE | EP_Reduced
71523 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
71525 ** The size of the structure can be found by masking the return value
71526 ** of this routine with 0xfff. The flags can be found by masking the
71527 ** return value with EP_Reduced|EP_TokenOnly.
71529 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
71530 ** (unreduced) Expr objects as they or originally constructed by the parser.
71531 ** During expression analysis, extra information is computed and moved into
71532 ** later parts of teh Expr object and that extra information might get chopped
71533 ** off if the expression is reduced. Note also that it does not work to
71534 ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
71535 ** to reduce a pristine expression tree from the parser. The implementation
71536 ** of dupedExprStructSize() contain multiple assert() statements that attempt
71537 ** to enforce this constraint.
71539 static int dupedExprStructSize(Expr *p, int flags){
71540 int nSize;
71541 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
71542 if( 0==(flags&EXPRDUP_REDUCE) ){
71543 nSize = EXPR_FULLSIZE;
71544 }else{
71545 assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
71546 assert( !ExprHasProperty(p, EP_FromJoin) );
71547 assert( (p->flags2 & EP2_MallocedToken)==0 );
71548 assert( (p->flags2 & EP2_Irreducible)==0 );
71549 if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
71550 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
71551 }else{
71552 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
71555 return nSize;
71559 ** This function returns the space in bytes required to store the copy
71560 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
71561 ** string is defined.)
71563 static int dupedExprNodeSize(Expr *p, int flags){
71564 int nByte = dupedExprStructSize(p, flags) & 0xfff;
71565 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71566 nByte += sqlite3Strlen30(p->u.zToken)+1;
71568 return ROUND8(nByte);
71572 ** Return the number of bytes required to create a duplicate of the
71573 ** expression passed as the first argument. The second argument is a
71574 ** mask containing EXPRDUP_XXX flags.
71576 ** The value returned includes space to create a copy of the Expr struct
71577 ** itself and the buffer referred to by Expr.u.zToken, if any.
71579 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
71580 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
71581 ** and Expr.pRight variables (but not for any structures pointed to or
71582 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
71584 static int dupedExprSize(Expr *p, int flags){
71585 int nByte = 0;
71586 if( p ){
71587 nByte = dupedExprNodeSize(p, flags);
71588 if( flags&EXPRDUP_REDUCE ){
71589 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
71592 return nByte;
71596 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
71597 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
71598 ** to store the copy of expression p, the copies of p->u.zToken
71599 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
71600 ** if any. Before returning, *pzBuffer is set to the first byte passed the
71601 ** portion of the buffer copied into by this function.
71603 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
71604 Expr *pNew = 0; /* Value to return */
71605 if( p ){
71606 const int isReduced = (flags&EXPRDUP_REDUCE);
71607 u8 *zAlloc;
71608 u32 staticFlag = 0;
71610 assert( pzBuffer==0 || isReduced );
71612 /* Figure out where to write the new Expr structure. */
71613 if( pzBuffer ){
71614 zAlloc = *pzBuffer;
71615 staticFlag = EP_Static;
71616 }else{
71617 zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
71619 pNew = (Expr *)zAlloc;
71621 if( pNew ){
71622 /* Set nNewSize to the size allocated for the structure pointed to
71623 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
71624 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
71625 ** by the copy of the p->u.zToken string (if any).
71627 const unsigned nStructSize = dupedExprStructSize(p, flags);
71628 const int nNewSize = nStructSize & 0xfff;
71629 int nToken;
71630 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71631 nToken = sqlite3Strlen30(p->u.zToken) + 1;
71632 }else{
71633 nToken = 0;
71635 if( isReduced ){
71636 assert( ExprHasProperty(p, EP_Reduced)==0 );
71637 memcpy(zAlloc, p, nNewSize);
71638 }else{
71639 int nSize = exprStructSize(p);
71640 memcpy(zAlloc, p, nSize);
71641 if( EXPR_FULLSIZE>nSize ){
71642 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
71646 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
71647 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
71648 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
71649 pNew->flags |= staticFlag;
71651 /* Copy the p->u.zToken string, if any. */
71652 if( nToken ){
71653 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
71654 memcpy(zToken, p->u.zToken, nToken);
71657 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
71658 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
71659 if( ExprHasProperty(p, EP_xIsSelect) ){
71660 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
71661 }else{
71662 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
71666 /* Fill in pNew->pLeft and pNew->pRight. */
71667 if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
71668 zAlloc += dupedExprNodeSize(p, flags);
71669 if( ExprHasProperty(pNew, EP_Reduced) ){
71670 pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
71671 pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
71673 if( pzBuffer ){
71674 *pzBuffer = zAlloc;
71676 }else{
71677 pNew->flags2 = 0;
71678 if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
71679 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
71680 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
71686 return pNew;
71690 ** The following group of routines make deep copies of expressions,
71691 ** expression lists, ID lists, and select statements. The copies can
71692 ** be deleted (by being passed to their respective ...Delete() routines)
71693 ** without effecting the originals.
71695 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
71696 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
71697 ** by subsequent calls to sqlite*ListAppend() routines.
71699 ** Any tables that the SrcList might point to are not duplicated.
71701 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
71702 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
71703 ** truncated version of the usual Expr structure that will be stored as
71704 ** part of the in-memory representation of the database schema.
71706 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
71707 return exprDup(db, p, flags, 0);
71709 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
71710 ExprList *pNew;
71711 struct ExprList_item *pItem, *pOldItem;
71712 int i;
71713 if( p==0 ) return 0;
71714 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
71715 if( pNew==0 ) return 0;
71716 pNew->iECursor = 0;
71717 pNew->nExpr = pNew->nAlloc = p->nExpr;
71718 pNew->a = pItem = sqlite3DbMallocRaw(db, p->nExpr*sizeof(p->a[0]) );
71719 if( pItem==0 ){
71720 sqlite3DbFree(db, pNew);
71721 return 0;
71723 pOldItem = p->a;
71724 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
71725 Expr *pOldExpr = pOldItem->pExpr;
71726 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
71727 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71728 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
71729 pItem->sortOrder = pOldItem->sortOrder;
71730 pItem->done = 0;
71731 pItem->iCol = pOldItem->iCol;
71732 pItem->iAlias = pOldItem->iAlias;
71734 return pNew;
71738 ** If cursors, triggers, views and subqueries are all omitted from
71739 ** the build, then none of the following routines, except for
71740 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
71741 ** called with a NULL argument.
71743 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
71744 || !defined(SQLITE_OMIT_SUBQUERY)
71745 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
71746 SrcList *pNew;
71747 int i;
71748 int nByte;
71749 if( p==0 ) return 0;
71750 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
71751 pNew = sqlite3DbMallocRaw(db, nByte );
71752 if( pNew==0 ) return 0;
71753 pNew->nSrc = pNew->nAlloc = p->nSrc;
71754 for(i=0; i<p->nSrc; i++){
71755 struct SrcList_item *pNewItem = &pNew->a[i];
71756 struct SrcList_item *pOldItem = &p->a[i];
71757 Table *pTab;
71758 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
71759 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71760 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
71761 pNewItem->jointype = pOldItem->jointype;
71762 pNewItem->iCursor = pOldItem->iCursor;
71763 pNewItem->isPopulated = pOldItem->isPopulated;
71764 pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
71765 pNewItem->notIndexed = pOldItem->notIndexed;
71766 pNewItem->pIndex = pOldItem->pIndex;
71767 pTab = pNewItem->pTab = pOldItem->pTab;
71768 if( pTab ){
71769 pTab->nRef++;
71771 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
71772 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
71773 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
71774 pNewItem->colUsed = pOldItem->colUsed;
71776 return pNew;
71778 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
71779 IdList *pNew;
71780 int i;
71781 if( p==0 ) return 0;
71782 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
71783 if( pNew==0 ) return 0;
71784 pNew->nId = pNew->nAlloc = p->nId;
71785 pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
71786 if( pNew->a==0 ){
71787 sqlite3DbFree(db, pNew);
71788 return 0;
71790 for(i=0; i<p->nId; i++){
71791 struct IdList_item *pNewItem = &pNew->a[i];
71792 struct IdList_item *pOldItem = &p->a[i];
71793 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71794 pNewItem->idx = pOldItem->idx;
71796 return pNew;
71798 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
71799 Select *pNew;
71800 if( p==0 ) return 0;
71801 pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
71802 if( pNew==0 ) return 0;
71803 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
71804 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
71805 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
71806 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
71807 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
71808 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
71809 pNew->op = p->op;
71810 pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
71811 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
71812 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
71813 pNew->iLimit = 0;
71814 pNew->iOffset = 0;
71815 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
71816 pNew->pRightmost = 0;
71817 pNew->addrOpenEphm[0] = -1;
71818 pNew->addrOpenEphm[1] = -1;
71819 pNew->addrOpenEphm[2] = -1;
71820 return pNew;
71822 #else
71823 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
71824 assert( p==0 );
71825 return 0;
71827 #endif
71831 ** Add a new element to the end of an expression list. If pList is
71832 ** initially NULL, then create a new expression list.
71834 ** If a memory allocation error occurs, the entire list is freed and
71835 ** NULL is returned. If non-NULL is returned, then it is guaranteed
71836 ** that the new entry was successfully appended.
71838 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
71839 Parse *pParse, /* Parsing context */
71840 ExprList *pList, /* List to which to append. Might be NULL */
71841 Expr *pExpr /* Expression to be appended. Might be NULL */
71843 sqlite3 *db = pParse->db;
71844 if( pList==0 ){
71845 pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
71846 if( pList==0 ){
71847 goto no_mem;
71849 assert( pList->nAlloc==0 );
71851 if( pList->nAlloc<=pList->nExpr ){
71852 struct ExprList_item *a;
71853 int n = pList->nAlloc*2 + 4;
71854 a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
71855 if( a==0 ){
71856 goto no_mem;
71858 pList->a = a;
71859 pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
71861 assert( pList->a!=0 );
71862 if( 1 ){
71863 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
71864 memset(pItem, 0, sizeof(*pItem));
71865 pItem->pExpr = pExpr;
71867 return pList;
71869 no_mem:
71870 /* Avoid leaking memory if malloc has failed. */
71871 sqlite3ExprDelete(db, pExpr);
71872 sqlite3ExprListDelete(db, pList);
71873 return 0;
71877 ** Set the ExprList.a[].zName element of the most recently added item
71878 ** on the expression list.
71880 ** pList might be NULL following an OOM error. But pName should never be
71881 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
71882 ** is set.
71884 SQLITE_PRIVATE void sqlite3ExprListSetName(
71885 Parse *pParse, /* Parsing context */
71886 ExprList *pList, /* List to which to add the span. */
71887 Token *pName, /* Name to be added */
71888 int dequote /* True to cause the name to be dequoted */
71890 assert( pList!=0 || pParse->db->mallocFailed!=0 );
71891 if( pList ){
71892 struct ExprList_item *pItem;
71893 assert( pList->nExpr>0 );
71894 pItem = &pList->a[pList->nExpr-1];
71895 assert( pItem->zName==0 );
71896 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
71897 if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
71902 ** Set the ExprList.a[].zSpan element of the most recently added item
71903 ** on the expression list.
71905 ** pList might be NULL following an OOM error. But pSpan should never be
71906 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
71907 ** is set.
71909 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
71910 Parse *pParse, /* Parsing context */
71911 ExprList *pList, /* List to which to add the span. */
71912 ExprSpan *pSpan /* The span to be added */
71914 sqlite3 *db = pParse->db;
71915 assert( pList!=0 || db->mallocFailed!=0 );
71916 if( pList ){
71917 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
71918 assert( pList->nExpr>0 );
71919 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
71920 sqlite3DbFree(db, pItem->zSpan);
71921 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
71922 (int)(pSpan->zEnd - pSpan->zStart));
71927 ** If the expression list pEList contains more than iLimit elements,
71928 ** leave an error message in pParse.
71930 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
71931 Parse *pParse,
71932 ExprList *pEList,
71933 const char *zObject
71935 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
71936 testcase( pEList && pEList->nExpr==mx );
71937 testcase( pEList && pEList->nExpr==mx+1 );
71938 if( pEList && pEList->nExpr>mx ){
71939 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
71944 ** Delete an entire expression list.
71946 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
71947 int i;
71948 struct ExprList_item *pItem;
71949 if( pList==0 ) return;
71950 assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
71951 assert( pList->nExpr<=pList->nAlloc );
71952 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
71953 sqlite3ExprDelete(db, pItem->pExpr);
71954 sqlite3DbFree(db, pItem->zName);
71955 sqlite3DbFree(db, pItem->zSpan);
71957 sqlite3DbFree(db, pList->a);
71958 sqlite3DbFree(db, pList);
71962 ** These routines are Walker callbacks. Walker.u.pi is a pointer
71963 ** to an integer. These routines are checking an expression to see
71964 ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
71965 ** not constant.
71967 ** These callback routines are used to implement the following:
71969 ** sqlite3ExprIsConstant()
71970 ** sqlite3ExprIsConstantNotJoin()
71971 ** sqlite3ExprIsConstantOrFunction()
71974 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
71976 /* If pWalker->u.i is 3 then any term of the expression that comes from
71977 ** the ON or USING clauses of a join disqualifies the expression
71978 ** from being considered constant. */
71979 if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
71980 pWalker->u.i = 0;
71981 return WRC_Abort;
71984 switch( pExpr->op ){
71985 /* Consider functions to be constant if all their arguments are constant
71986 ** and pWalker->u.i==2 */
71987 case TK_FUNCTION:
71988 if( pWalker->u.i==2 ) return 0;
71989 /* Fall through */
71990 case TK_ID:
71991 case TK_COLUMN:
71992 case TK_AGG_FUNCTION:
71993 case TK_AGG_COLUMN:
71994 testcase( pExpr->op==TK_ID );
71995 testcase( pExpr->op==TK_COLUMN );
71996 testcase( pExpr->op==TK_AGG_FUNCTION );
71997 testcase( pExpr->op==TK_AGG_COLUMN );
71998 pWalker->u.i = 0;
71999 return WRC_Abort;
72000 default:
72001 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
72002 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
72003 return WRC_Continue;
72006 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
72007 UNUSED_PARAMETER(NotUsed);
72008 pWalker->u.i = 0;
72009 return WRC_Abort;
72011 static int exprIsConst(Expr *p, int initFlag){
72012 Walker w;
72013 w.u.i = initFlag;
72014 w.xExprCallback = exprNodeIsConstant;
72015 w.xSelectCallback = selectNodeIsConstant;
72016 sqlite3WalkExpr(&w, p);
72017 return w.u.i;
72021 ** Walk an expression tree. Return 1 if the expression is constant
72022 ** and 0 if it involves variables or function calls.
72024 ** For the purposes of this function, a double-quoted string (ex: "abc")
72025 ** is considered a variable but a single-quoted string (ex: 'abc') is
72026 ** a constant.
72028 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
72029 return exprIsConst(p, 1);
72033 ** Walk an expression tree. Return 1 if the expression is constant
72034 ** that does no originate from the ON or USING clauses of a join.
72035 ** Return 0 if it involves variables or function calls or terms from
72036 ** an ON or USING clause.
72038 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
72039 return exprIsConst(p, 3);
72043 ** Walk an expression tree. Return 1 if the expression is constant
72044 ** or a function call with constant arguments. Return and 0 if there
72045 ** are any variables.
72047 ** For the purposes of this function, a double-quoted string (ex: "abc")
72048 ** is considered a variable but a single-quoted string (ex: 'abc') is
72049 ** a constant.
72051 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
72052 return exprIsConst(p, 2);
72056 ** If the expression p codes a constant integer that is small enough
72057 ** to fit in a 32-bit integer, return 1 and put the value of the integer
72058 ** in *pValue. If the expression is not an integer or if it is too big
72059 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
72061 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
72062 int rc = 0;
72064 /* If an expression is an integer literal that fits in a signed 32-bit
72065 ** integer, then the EP_IntValue flag will have already been set */
72066 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
72067 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
72069 if( p->flags & EP_IntValue ){
72070 *pValue = p->u.iValue;
72071 return 1;
72073 switch( p->op ){
72074 case TK_UPLUS: {
72075 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
72076 break;
72078 case TK_UMINUS: {
72079 int v;
72080 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
72081 *pValue = -v;
72082 rc = 1;
72084 break;
72086 default: break;
72088 return rc;
72092 ** Return FALSE if there is no chance that the expression can be NULL.
72094 ** If the expression might be NULL or if the expression is too complex
72095 ** to tell return TRUE.
72097 ** This routine is used as an optimization, to skip OP_IsNull opcodes
72098 ** when we know that a value cannot be NULL. Hence, a false positive
72099 ** (returning TRUE when in fact the expression can never be NULL) might
72100 ** be a small performance hit but is otherwise harmless. On the other
72101 ** hand, a false negative (returning FALSE when the result could be NULL)
72102 ** will likely result in an incorrect answer. So when in doubt, return
72103 ** TRUE.
72105 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
72106 u8 op;
72107 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
72108 op = p->op;
72109 if( op==TK_REGISTER ) op = p->op2;
72110 switch( op ){
72111 case TK_INTEGER:
72112 case TK_STRING:
72113 case TK_FLOAT:
72114 case TK_BLOB:
72115 return 0;
72116 default:
72117 return 1;
72122 ** Generate an OP_IsNull instruction that tests register iReg and jumps
72123 ** to location iDest if the value in iReg is NULL. The value in iReg
72124 ** was computed by pExpr. If we can look at pExpr at compile-time and
72125 ** determine that it can never generate a NULL, then the OP_IsNull operation
72126 ** can be omitted.
72128 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
72129 Vdbe *v, /* The VDBE under construction */
72130 const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
72131 int iReg, /* Test the value in this register for NULL */
72132 int iDest /* Jump here if the value is null */
72134 if( sqlite3ExprCanBeNull(pExpr) ){
72135 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
72140 ** Return TRUE if the given expression is a constant which would be
72141 ** unchanged by OP_Affinity with the affinity given in the second
72142 ** argument.
72144 ** This routine is used to determine if the OP_Affinity operation
72145 ** can be omitted. When in doubt return FALSE. A false negative
72146 ** is harmless. A false positive, however, can result in the wrong
72147 ** answer.
72149 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
72150 u8 op;
72151 if( aff==SQLITE_AFF_NONE ) return 1;
72152 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
72153 op = p->op;
72154 if( op==TK_REGISTER ) op = p->op2;
72155 switch( op ){
72156 case TK_INTEGER: {
72157 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
72159 case TK_FLOAT: {
72160 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
72162 case TK_STRING: {
72163 return aff==SQLITE_AFF_TEXT;
72165 case TK_BLOB: {
72166 return 1;
72168 case TK_COLUMN: {
72169 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
72170 return p->iColumn<0
72171 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
72173 default: {
72174 return 0;
72180 ** Return TRUE if the given string is a row-id column name.
72182 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
72183 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
72184 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
72185 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
72186 return 0;
72190 ** Return true if we are able to the IN operator optimization on a
72191 ** query of the form
72193 ** x IN (SELECT ...)
72195 ** Where the SELECT... clause is as specified by the parameter to this
72196 ** routine.
72198 ** The Select object passed in has already been preprocessed and no
72199 ** errors have been found.
72201 #ifndef SQLITE_OMIT_SUBQUERY
72202 static int isCandidateForInOpt(Select *p){
72203 SrcList *pSrc;
72204 ExprList *pEList;
72205 Table *pTab;
72206 if( p==0 ) return 0; /* right-hand side of IN is SELECT */
72207 if( p->pPrior ) return 0; /* Not a compound SELECT */
72208 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
72209 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
72210 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
72211 return 0; /* No DISTINCT keyword and no aggregate functions */
72213 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
72214 if( p->pLimit ) return 0; /* Has no LIMIT clause */
72215 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
72216 if( p->pWhere ) return 0; /* Has no WHERE clause */
72217 pSrc = p->pSrc;
72218 assert( pSrc!=0 );
72219 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
72220 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
72221 pTab = pSrc->a[0].pTab;
72222 if( NEVER(pTab==0) ) return 0;
72223 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
72224 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
72225 pEList = p->pEList;
72226 if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
72227 if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
72228 return 1;
72230 #endif /* SQLITE_OMIT_SUBQUERY */
72233 ** This function is used by the implementation of the IN (...) operator.
72234 ** It's job is to find or create a b-tree structure that may be used
72235 ** either to test for membership of the (...) set or to iterate through
72236 ** its members, skipping duplicates.
72238 ** The index of the cursor opened on the b-tree (database table, database index
72239 ** or ephermal table) is stored in pX->iTable before this function returns.
72240 ** The returned value of this function indicates the b-tree type, as follows:
72242 ** IN_INDEX_ROWID - The cursor was opened on a database table.
72243 ** IN_INDEX_INDEX - The cursor was opened on a database index.
72244 ** IN_INDEX_EPH - The cursor was opened on a specially created and
72245 ** populated epheremal table.
72247 ** An existing b-tree may only be used if the SELECT is of the simple
72248 ** form:
72250 ** SELECT <column> FROM <table>
72252 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
72253 ** through the set members, skipping any duplicates. In this case an
72254 ** epheremal table must be used unless the selected <column> is guaranteed
72255 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
72256 ** has a UNIQUE constraint or UNIQUE index.
72258 ** If the prNotFound parameter is not 0, then the b-tree will be used
72259 ** for fast set membership tests. In this case an epheremal table must
72260 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
72261 ** be found with <column> as its left-most column.
72263 ** When the b-tree is being used for membership tests, the calling function
72264 ** needs to know whether or not the structure contains an SQL NULL
72265 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
72266 ** If there is any chance that the (...) might contain a NULL value at
72267 ** runtime, then a register is allocated and the register number written
72268 ** to *prNotFound. If there is no chance that the (...) contains a
72269 ** NULL value, then *prNotFound is left unchanged.
72271 ** If a register is allocated and its location stored in *prNotFound, then
72272 ** its initial value is NULL. If the (...) does not remain constant
72273 ** for the duration of the query (i.e. the SELECT within the (...)
72274 ** is a correlated subquery) then the value of the allocated register is
72275 ** reset to NULL each time the subquery is rerun. This allows the
72276 ** caller to use vdbe code equivalent to the following:
72278 ** if( register==NULL ){
72279 ** has_null = <test if data structure contains null>
72280 ** register = 1
72281 ** }
72283 ** in order to avoid running the <test if data structure contains null>
72284 ** test more often than is necessary.
72286 #ifndef SQLITE_OMIT_SUBQUERY
72287 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
72288 Select *p; /* SELECT to the right of IN operator */
72289 int eType = 0; /* Type of RHS table. IN_INDEX_* */
72290 int iTab = pParse->nTab++; /* Cursor of the RHS table */
72291 int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
72293 assert( pX->op==TK_IN );
72295 /* Check to see if an existing table or index can be used to
72296 ** satisfy the query. This is preferable to generating a new
72297 ** ephemeral table.
72299 p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
72300 if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
72301 sqlite3 *db = pParse->db; /* Database connection */
72302 Expr *pExpr = p->pEList->a[0].pExpr; /* Expression <column> */
72303 int iCol = pExpr->iColumn; /* Index of column <column> */
72304 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
72305 Table *pTab = p->pSrc->a[0].pTab; /* Table <table>. */
72306 int iDb; /* Database idx for pTab */
72308 /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
72309 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72310 sqlite3CodeVerifySchema(pParse, iDb);
72311 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
72313 /* This function is only called from two places. In both cases the vdbe
72314 ** has already been allocated. So assume sqlite3GetVdbe() is always
72315 ** successful here.
72317 assert(v);
72318 if( iCol<0 ){
72319 int iMem = ++pParse->nMem;
72320 int iAddr;
72322 iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72323 sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72325 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
72326 eType = IN_INDEX_ROWID;
72328 sqlite3VdbeJumpHere(v, iAddr);
72329 }else{
72330 Index *pIdx; /* Iterator variable */
72332 /* The collation sequence used by the comparison. If an index is to
72333 ** be used in place of a temp-table, it must be ordered according
72334 ** to this collation sequence. */
72335 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
72337 /* Check that the affinity that will be used to perform the
72338 ** comparison is the same as the affinity of the column. If
72339 ** it is not, it is not possible to use any index.
72341 char aff = comparisonAffinity(pX);
72342 int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
72344 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
72345 if( (pIdx->aiColumn[0]==iCol)
72346 && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
72347 && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
72349 int iMem = ++pParse->nMem;
72350 int iAddr;
72351 char *pKey;
72353 pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
72354 iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72355 sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72357 sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
72358 pKey,P4_KEYINFO_HANDOFF);
72359 VdbeComment((v, "%s", pIdx->zName));
72360 eType = IN_INDEX_INDEX;
72362 sqlite3VdbeJumpHere(v, iAddr);
72363 if( prNotFound && !pTab->aCol[iCol].notNull ){
72364 *prNotFound = ++pParse->nMem;
72371 if( eType==0 ){
72372 /* Could not found an existing table or index to use as the RHS b-tree.
72373 ** We will have to generate an ephemeral table to do the job.
72375 double savedNQueryLoop = pParse->nQueryLoop;
72376 int rMayHaveNull = 0;
72377 eType = IN_INDEX_EPH;
72378 if( prNotFound ){
72379 *prNotFound = rMayHaveNull = ++pParse->nMem;
72380 }else{
72381 testcase( pParse->nQueryLoop>(double)1 );
72382 pParse->nQueryLoop = (double)1;
72383 if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
72384 eType = IN_INDEX_ROWID;
72387 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
72388 pParse->nQueryLoop = savedNQueryLoop;
72389 }else{
72390 pX->iTable = iTab;
72392 return eType;
72394 #endif
72397 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
72398 ** or IN operators. Examples:
72400 ** (SELECT a FROM b) -- subquery
72401 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
72402 ** x IN (4,5,11) -- IN operator with list on right-hand side
72403 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
72405 ** The pExpr parameter describes the expression that contains the IN
72406 ** operator or subquery.
72408 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
72409 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
72410 ** to some integer key column of a table B-Tree. In this case, use an
72411 ** intkey B-Tree to store the set of IN(...) values instead of the usual
72412 ** (slower) variable length keys B-Tree.
72414 ** If rMayHaveNull is non-zero, that means that the operation is an IN
72415 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
72416 ** Furthermore, the IN is in a WHERE clause and that we really want
72417 ** to iterate over the RHS of the IN operator in order to quickly locate
72418 ** all corresponding LHS elements. All this routine does is initialize
72419 ** the register given by rMayHaveNull to NULL. Calling routines will take
72420 ** care of changing this register value to non-NULL if the RHS is NULL-free.
72422 ** If rMayHaveNull is zero, that means that the subquery is being used
72423 ** for membership testing only. There is no need to initialize any
72424 ** registers to indicate the presense or absence of NULLs on the RHS.
72426 ** For a SELECT or EXISTS operator, return the register that holds the
72427 ** result. For IN operators or if an error occurs, the return value is 0.
72429 #ifndef SQLITE_OMIT_SUBQUERY
72430 SQLITE_PRIVATE int sqlite3CodeSubselect(
72431 Parse *pParse, /* Parsing context */
72432 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
72433 int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
72434 int isRowid /* If true, LHS of IN operator is a rowid */
72436 int testAddr = 0; /* One-time test address */
72437 int rReg = 0; /* Register storing resulting */
72438 Vdbe *v = sqlite3GetVdbe(pParse);
72439 if( NEVER(v==0) ) return 0;
72440 sqlite3ExprCachePush(pParse);
72442 /* This code must be run in its entirety every time it is encountered
72443 ** if any of the following is true:
72445 ** * The right-hand side is a correlated subquery
72446 ** * The right-hand side is an expression list containing variables
72447 ** * We are inside a trigger
72449 ** If all of the above are false, then we can run this code just once
72450 ** save the results, and reuse the same result on subsequent invocations.
72452 if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
72453 int mem = ++pParse->nMem;
72454 sqlite3VdbeAddOp1(v, OP_If, mem);
72455 testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
72456 assert( testAddr>0 || pParse->db->mallocFailed );
72459 #ifndef SQLITE_OMIT_EXPLAIN
72460 if( pParse->explain==2 ){
72461 char *zMsg = sqlite3MPrintf(
72462 pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr?"":"CORRELATED ",
72463 pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
72465 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
72467 #endif
72469 switch( pExpr->op ){
72470 case TK_IN: {
72471 char affinity; /* Affinity of the LHS of the IN */
72472 KeyInfo keyInfo; /* Keyinfo for the generated table */
72473 int addr; /* Address of OP_OpenEphemeral instruction */
72474 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
72476 if( rMayHaveNull ){
72477 sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
72480 affinity = sqlite3ExprAffinity(pLeft);
72482 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
72483 ** expression it is handled the same way. An ephemeral table is
72484 ** filled with single-field index keys representing the results
72485 ** from the SELECT or the <exprlist>.
72487 ** If the 'x' expression is a column value, or the SELECT...
72488 ** statement returns a column value, then the affinity of that
72489 ** column is used to build the index keys. If both 'x' and the
72490 ** SELECT... statement are columns, then numeric affinity is used
72491 ** if either column has NUMERIC or INTEGER affinity. If neither
72492 ** 'x' nor the SELECT... statement are columns, then numeric affinity
72493 ** is used.
72495 pExpr->iTable = pParse->nTab++;
72496 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
72497 if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
72498 memset(&keyInfo, 0, sizeof(keyInfo));
72499 keyInfo.nField = 1;
72501 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72502 /* Case 1: expr IN (SELECT ...)
72504 ** Generate code to write the results of the select into the temporary
72505 ** table allocated and opened above.
72507 SelectDest dest;
72508 ExprList *pEList;
72510 assert( !isRowid );
72511 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
72512 dest.affinity = (u8)affinity;
72513 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
72514 pExpr->x.pSelect->iLimit = 0;
72515 if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
72516 return 0;
72518 pEList = pExpr->x.pSelect->pEList;
72519 if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
72520 keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
72521 pEList->a[0].pExpr);
72523 }else if( ALWAYS(pExpr->x.pList!=0) ){
72524 /* Case 2: expr IN (exprlist)
72526 ** For each expression, build an index key from the evaluation and
72527 ** store it in the temporary table. If <expr> is a column, then use
72528 ** that columns affinity when building index keys. If <expr> is not
72529 ** a column, use numeric affinity.
72531 int i;
72532 ExprList *pList = pExpr->x.pList;
72533 struct ExprList_item *pItem;
72534 int r1, r2, r3;
72536 if( !affinity ){
72537 affinity = SQLITE_AFF_NONE;
72539 keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
72541 /* Loop through each expression in <exprlist>. */
72542 r1 = sqlite3GetTempReg(pParse);
72543 r2 = sqlite3GetTempReg(pParse);
72544 sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
72545 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
72546 Expr *pE2 = pItem->pExpr;
72547 int iValToIns;
72549 /* If the expression is not constant then we will need to
72550 ** disable the test that was generated above that makes sure
72551 ** this code only executes once. Because for a non-constant
72552 ** expression we need to rerun this code each time.
72554 if( testAddr && !sqlite3ExprIsConstant(pE2) ){
72555 sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
72556 testAddr = 0;
72559 /* Evaluate the expression and insert it into the temp table */
72560 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
72561 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
72562 }else{
72563 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
72564 if( isRowid ){
72565 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
72566 sqlite3VdbeCurrentAddr(v)+2);
72567 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
72568 }else{
72569 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
72570 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
72571 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
72575 sqlite3ReleaseTempReg(pParse, r1);
72576 sqlite3ReleaseTempReg(pParse, r2);
72578 if( !isRowid ){
72579 sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
72581 break;
72584 case TK_EXISTS:
72585 case TK_SELECT:
72586 default: {
72587 /* If this has to be a scalar SELECT. Generate code to put the
72588 ** value of this select in a memory cell and record the number
72589 ** of the memory cell in iColumn. If this is an EXISTS, write
72590 ** an integer 0 (not exists) or 1 (exists) into a memory cell
72591 ** and record that memory cell in iColumn.
72593 Select *pSel; /* SELECT statement to encode */
72594 SelectDest dest; /* How to deal with SELECt result */
72596 testcase( pExpr->op==TK_EXISTS );
72597 testcase( pExpr->op==TK_SELECT );
72598 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
72600 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
72601 pSel = pExpr->x.pSelect;
72602 sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
72603 if( pExpr->op==TK_SELECT ){
72604 dest.eDest = SRT_Mem;
72605 sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
72606 VdbeComment((v, "Init subquery result"));
72607 }else{
72608 dest.eDest = SRT_Exists;
72609 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
72610 VdbeComment((v, "Init EXISTS result"));
72612 sqlite3ExprDelete(pParse->db, pSel->pLimit);
72613 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
72614 &sqlite3IntTokens[1]);
72615 pSel->iLimit = 0;
72616 if( sqlite3Select(pParse, pSel, &dest) ){
72617 return 0;
72619 rReg = dest.iParm;
72620 ExprSetIrreducible(pExpr);
72621 break;
72625 if( testAddr ){
72626 sqlite3VdbeJumpHere(v, testAddr-1);
72628 sqlite3ExprCachePop(pParse, 1);
72630 return rReg;
72632 #endif /* SQLITE_OMIT_SUBQUERY */
72634 #ifndef SQLITE_OMIT_SUBQUERY
72636 ** Generate code for an IN expression.
72638 ** x IN (SELECT ...)
72639 ** x IN (value, value, ...)
72641 ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
72642 ** is an array of zero or more values. The expression is true if the LHS is
72643 ** contained within the RHS. The value of the expression is unknown (NULL)
72644 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
72645 ** RHS contains one or more NULL values.
72647 ** This routine generates code will jump to destIfFalse if the LHS is not
72648 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
72649 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
72650 ** within the RHS then fall through.
72652 static void sqlite3ExprCodeIN(
72653 Parse *pParse, /* Parsing and code generating context */
72654 Expr *pExpr, /* The IN expression */
72655 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
72656 int destIfNull /* Jump here if the results are unknown due to NULLs */
72658 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
72659 char affinity; /* Comparison affinity to use */
72660 int eType; /* Type of the RHS */
72661 int r1; /* Temporary use register */
72662 Vdbe *v; /* Statement under construction */
72664 /* Compute the RHS. After this step, the table with cursor
72665 ** pExpr->iTable will contains the values that make up the RHS.
72667 v = pParse->pVdbe;
72668 assert( v!=0 ); /* OOM detected prior to this routine */
72669 VdbeNoopComment((v, "begin IN expr"));
72670 eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
72672 /* Figure out the affinity to use to create a key from the results
72673 ** of the expression. affinityStr stores a static string suitable for
72674 ** P4 of OP_MakeRecord.
72676 affinity = comparisonAffinity(pExpr);
72678 /* Code the LHS, the <expr> from "<expr> IN (...)".
72680 sqlite3ExprCachePush(pParse);
72681 r1 = sqlite3GetTempReg(pParse);
72682 sqlite3ExprCode(pParse, pExpr->pLeft, r1);
72684 /* If the LHS is NULL, then the result is either false or NULL depending
72685 ** on whether the RHS is empty or not, respectively.
72687 if( destIfNull==destIfFalse ){
72688 /* Shortcut for the common case where the false and NULL outcomes are
72689 ** the same. */
72690 sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
72691 }else{
72692 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
72693 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
72694 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
72695 sqlite3VdbeJumpHere(v, addr1);
72698 if( eType==IN_INDEX_ROWID ){
72699 /* In this case, the RHS is the ROWID of table b-tree
72701 sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
72702 sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
72703 }else{
72704 /* In this case, the RHS is an index b-tree.
72706 sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
72708 /* If the set membership test fails, then the result of the
72709 ** "x IN (...)" expression must be either 0 or NULL. If the set
72710 ** contains no NULL values, then the result is 0. If the set
72711 ** contains one or more NULL values, then the result of the
72712 ** expression is also NULL.
72714 if( rRhsHasNull==0 || destIfFalse==destIfNull ){
72715 /* This branch runs if it is known at compile time that the RHS
72716 ** cannot contain NULL values. This happens as the result
72717 ** of a "NOT NULL" constraint in the database schema.
72719 ** Also run this branch if NULL is equivalent to FALSE
72720 ** for this particular IN operator.
72722 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
72724 }else{
72725 /* In this branch, the RHS of the IN might contain a NULL and
72726 ** the presence of a NULL on the RHS makes a difference in the
72727 ** outcome.
72729 int j1, j2, j3;
72731 /* First check to see if the LHS is contained in the RHS. If so,
72732 ** then the presence of NULLs in the RHS does not matter, so jump
72733 ** over all of the code that follows.
72735 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
72737 /* Here we begin generating code that runs if the LHS is not
72738 ** contained within the RHS. Generate additional code that
72739 ** tests the RHS for NULLs. If the RHS contains a NULL then
72740 ** jump to destIfNull. If there are no NULLs in the RHS then
72741 ** jump to destIfFalse.
72743 j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
72744 j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
72745 sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
72746 sqlite3VdbeJumpHere(v, j3);
72747 sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
72748 sqlite3VdbeJumpHere(v, j2);
72750 /* Jump to the appropriate target depending on whether or not
72751 ** the RHS contains a NULL
72753 sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
72754 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
72756 /* The OP_Found at the top of this branch jumps here when true,
72757 ** causing the overall IN expression evaluation to fall through.
72759 sqlite3VdbeJumpHere(v, j1);
72762 sqlite3ReleaseTempReg(pParse, r1);
72763 sqlite3ExprCachePop(pParse, 1);
72764 VdbeComment((v, "end IN expr"));
72766 #endif /* SQLITE_OMIT_SUBQUERY */
72769 ** Duplicate an 8-byte value
72771 static char *dup8bytes(Vdbe *v, const char *in){
72772 char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
72773 if( out ){
72774 memcpy(out, in, 8);
72776 return out;
72779 #ifndef SQLITE_OMIT_FLOATING_POINT
72781 ** Generate an instruction that will put the floating point
72782 ** value described by z[0..n-1] into register iMem.
72784 ** The z[] string will probably not be zero-terminated. But the
72785 ** z[n] character is guaranteed to be something that does not look
72786 ** like the continuation of the number.
72788 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
72789 if( ALWAYS(z!=0) ){
72790 double value;
72791 char *zV;
72792 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
72793 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
72794 if( negateFlag ) value = -value;
72795 zV = dup8bytes(v, (char*)&value);
72796 sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
72799 #endif
72803 ** Generate an instruction that will put the integer describe by
72804 ** text z[0..n-1] into register iMem.
72806 ** Expr.u.zToken is always UTF8 and zero-terminated.
72808 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
72809 Vdbe *v = pParse->pVdbe;
72810 if( pExpr->flags & EP_IntValue ){
72811 int i = pExpr->u.iValue;
72812 assert( i>=0 );
72813 if( negFlag ) i = -i;
72814 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
72815 }else{
72816 int c;
72817 i64 value;
72818 const char *z = pExpr->u.zToken;
72819 assert( z!=0 );
72820 c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
72821 if( c==0 || (c==2 && negFlag) ){
72822 char *zV;
72823 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
72824 zV = dup8bytes(v, (char*)&value);
72825 sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
72826 }else{
72827 #ifdef SQLITE_OMIT_FLOATING_POINT
72828 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
72829 #else
72830 codeReal(v, z, negFlag, iMem);
72831 #endif
72837 ** Clear a cache entry.
72839 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
72840 if( p->tempReg ){
72841 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
72842 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
72844 p->tempReg = 0;
72850 ** Record in the column cache that a particular column from a
72851 ** particular table is stored in a particular register.
72853 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
72854 int i;
72855 int minLru;
72856 int idxLru;
72857 struct yColCache *p;
72859 assert( iReg>0 ); /* Register numbers are always positive */
72860 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
72862 /* The SQLITE_ColumnCache flag disables the column cache. This is used
72863 ** for testing only - to verify that SQLite always gets the same answer
72864 ** with and without the column cache.
72866 if( pParse->db->flags & SQLITE_ColumnCache ) return;
72868 /* First replace any existing entry.
72870 ** Actually, the way the column cache is currently used, we are guaranteed
72871 ** that the object will never already be in cache. Verify this guarantee.
72873 #ifndef NDEBUG
72874 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72875 #if 0 /* This code wold remove the entry from the cache if it existed */
72876 if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
72877 cacheEntryClear(pParse, p);
72878 p->iLevel = pParse->iCacheLevel;
72879 p->iReg = iReg;
72880 p->lru = pParse->iCacheCnt++;
72881 return;
72883 #endif
72884 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
72886 #endif
72888 /* Find an empty slot and replace it */
72889 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72890 if( p->iReg==0 ){
72891 p->iLevel = pParse->iCacheLevel;
72892 p->iTable = iTab;
72893 p->iColumn = iCol;
72894 p->iReg = iReg;
72895 p->tempReg = 0;
72896 p->lru = pParse->iCacheCnt++;
72897 return;
72901 /* Replace the last recently used */
72902 minLru = 0x7fffffff;
72903 idxLru = -1;
72904 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72905 if( p->lru<minLru ){
72906 idxLru = i;
72907 minLru = p->lru;
72910 if( ALWAYS(idxLru>=0) ){
72911 p = &pParse->aColCache[idxLru];
72912 p->iLevel = pParse->iCacheLevel;
72913 p->iTable = iTab;
72914 p->iColumn = iCol;
72915 p->iReg = iReg;
72916 p->tempReg = 0;
72917 p->lru = pParse->iCacheCnt++;
72918 return;
72923 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
72924 ** Purge the range of registers from the column cache.
72926 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
72927 int i;
72928 int iLast = iReg + nReg - 1;
72929 struct yColCache *p;
72930 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72931 int r = p->iReg;
72932 if( r>=iReg && r<=iLast ){
72933 cacheEntryClear(pParse, p);
72934 p->iReg = 0;
72940 ** Remember the current column cache context. Any new entries added
72941 ** added to the column cache after this call are removed when the
72942 ** corresponding pop occurs.
72944 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
72945 pParse->iCacheLevel++;
72949 ** Remove from the column cache any entries that were added since the
72950 ** the previous N Push operations. In other words, restore the cache
72951 ** to the state it was in N Pushes ago.
72953 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
72954 int i;
72955 struct yColCache *p;
72956 assert( N>0 );
72957 assert( pParse->iCacheLevel>=N );
72958 pParse->iCacheLevel -= N;
72959 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72960 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
72961 cacheEntryClear(pParse, p);
72962 p->iReg = 0;
72968 ** When a cached column is reused, make sure that its register is
72969 ** no longer available as a temp register. ticket #3879: that same
72970 ** register might be in the cache in multiple places, so be sure to
72971 ** get them all.
72973 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
72974 int i;
72975 struct yColCache *p;
72976 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72977 if( p->iReg==iReg ){
72978 p->tempReg = 0;
72984 ** Generate code to extract the value of the iCol-th column of a table.
72986 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
72987 Vdbe *v, /* The VDBE under construction */
72988 Table *pTab, /* The table containing the value */
72989 int iTabCur, /* The cursor for this table */
72990 int iCol, /* Index of the column to extract */
72991 int regOut /* Extract the valud into this register */
72993 if( iCol<0 || iCol==pTab->iPKey ){
72994 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
72995 }else{
72996 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
72997 sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
72999 if( iCol>=0 ){
73000 sqlite3ColumnDefault(v, pTab, iCol, regOut);
73005 ** Generate code that will extract the iColumn-th column from
73006 ** table pTab and store the column value in a register. An effort
73007 ** is made to store the column value in register iReg, but this is
73008 ** not guaranteed. The location of the column value is returned.
73010 ** There must be an open cursor to pTab in iTable when this routine
73011 ** is called. If iColumn<0 then code is generated that extracts the rowid.
73013 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
73014 Parse *pParse, /* Parsing and code generating context */
73015 Table *pTab, /* Description of the table we are reading from */
73016 int iColumn, /* Index of the table column */
73017 int iTable, /* The cursor pointing to the table */
73018 int iReg /* Store results here */
73020 Vdbe *v = pParse->pVdbe;
73021 int i;
73022 struct yColCache *p;
73024 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73025 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
73026 p->lru = pParse->iCacheCnt++;
73027 sqlite3ExprCachePinRegister(pParse, p->iReg);
73028 return p->iReg;
73031 assert( v!=0 );
73032 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
73033 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
73034 return iReg;
73038 ** Clear all column cache entries.
73040 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
73041 int i;
73042 struct yColCache *p;
73044 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73045 if( p->iReg ){
73046 cacheEntryClear(pParse, p);
73047 p->iReg = 0;
73053 ** Record the fact that an affinity change has occurred on iCount
73054 ** registers starting with iStart.
73056 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
73057 sqlite3ExprCacheRemove(pParse, iStart, iCount);
73061 ** Generate code to move content from registers iFrom...iFrom+nReg-1
73062 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
73064 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
73065 int i;
73066 struct yColCache *p;
73067 if( NEVER(iFrom==iTo) ) return;
73068 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
73069 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73070 int x = p->iReg;
73071 if( x>=iFrom && x<iFrom+nReg ){
73072 p->iReg += iTo-iFrom;
73078 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
73079 ** over to iTo..iTo+nReg-1.
73081 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
73082 int i;
73083 if( NEVER(iFrom==iTo) ) return;
73084 for(i=0; i<nReg; i++){
73085 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
73089 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
73091 ** Return true if any register in the range iFrom..iTo (inclusive)
73092 ** is used as part of the column cache.
73094 ** This routine is used within assert() and testcase() macros only
73095 ** and does not appear in a normal build.
73097 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
73098 int i;
73099 struct yColCache *p;
73100 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73101 int r = p->iReg;
73102 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
73104 return 0;
73106 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
73109 ** Generate code into the current Vdbe to evaluate the given
73110 ** expression. Attempt to store the results in register "target".
73111 ** Return the register where results are stored.
73113 ** With this routine, there is no guarantee that results will
73114 ** be stored in target. The result might be stored in some other
73115 ** register if it is convenient to do so. The calling function
73116 ** must check the return code and move the results to the desired
73117 ** register.
73119 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
73120 Vdbe *v = pParse->pVdbe; /* The VM under construction */
73121 int op; /* The opcode being coded */
73122 int inReg = target; /* Results stored in register inReg */
73123 int regFree1 = 0; /* If non-zero free this temporary register */
73124 int regFree2 = 0; /* If non-zero free this temporary register */
73125 int r1, r2, r3, r4; /* Various register numbers */
73126 sqlite3 *db = pParse->db; /* The database connection */
73128 assert( target>0 && target<=pParse->nMem );
73129 if( v==0 ){
73130 assert( pParse->db->mallocFailed );
73131 return 0;
73134 if( pExpr==0 ){
73135 op = TK_NULL;
73136 }else{
73137 op = pExpr->op;
73139 switch( op ){
73140 case TK_AGG_COLUMN: {
73141 AggInfo *pAggInfo = pExpr->pAggInfo;
73142 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
73143 if( !pAggInfo->directMode ){
73144 assert( pCol->iMem>0 );
73145 inReg = pCol->iMem;
73146 break;
73147 }else if( pAggInfo->useSortingIdx ){
73148 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
73149 pCol->iSorterColumn, target);
73150 break;
73152 /* Otherwise, fall thru into the TK_COLUMN case */
73154 case TK_COLUMN: {
73155 if( pExpr->iTable<0 ){
73156 /* This only happens when coding check constraints */
73157 assert( pParse->ckBase>0 );
73158 inReg = pExpr->iColumn + pParse->ckBase;
73159 }else{
73160 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
73161 pExpr->iColumn, pExpr->iTable, target);
73163 break;
73165 case TK_INTEGER: {
73166 codeInteger(pParse, pExpr, 0, target);
73167 break;
73169 #ifndef SQLITE_OMIT_FLOATING_POINT
73170 case TK_FLOAT: {
73171 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73172 codeReal(v, pExpr->u.zToken, 0, target);
73173 break;
73175 #endif
73176 case TK_STRING: {
73177 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73178 sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
73179 break;
73181 case TK_NULL: {
73182 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73183 break;
73185 #ifndef SQLITE_OMIT_BLOB_LITERAL
73186 case TK_BLOB: {
73187 int n;
73188 const char *z;
73189 char *zBlob;
73190 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73191 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
73192 assert( pExpr->u.zToken[1]=='\'' );
73193 z = &pExpr->u.zToken[2];
73194 n = sqlite3Strlen30(z) - 1;
73195 assert( z[n]=='\'' );
73196 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
73197 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
73198 break;
73200 #endif
73201 case TK_VARIABLE: {
73202 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73203 assert( pExpr->u.zToken!=0 );
73204 assert( pExpr->u.zToken[0]!=0 );
73205 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
73206 if( pExpr->u.zToken[1]!=0 ){
73207 sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, P4_TRANSIENT);
73209 break;
73211 case TK_REGISTER: {
73212 inReg = pExpr->iTable;
73213 break;
73215 case TK_AS: {
73216 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73217 break;
73219 #ifndef SQLITE_OMIT_CAST
73220 case TK_CAST: {
73221 /* Expressions of the form: CAST(pLeft AS token) */
73222 int aff, to_op;
73223 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73224 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73225 aff = sqlite3AffinityType(pExpr->u.zToken);
73226 to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
73227 assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
73228 assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
73229 assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
73230 assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
73231 assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
73232 testcase( to_op==OP_ToText );
73233 testcase( to_op==OP_ToBlob );
73234 testcase( to_op==OP_ToNumeric );
73235 testcase( to_op==OP_ToInt );
73236 testcase( to_op==OP_ToReal );
73237 if( inReg!=target ){
73238 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
73239 inReg = target;
73241 sqlite3VdbeAddOp1(v, to_op, inReg);
73242 testcase( usedAsColumnCache(pParse, inReg, inReg) );
73243 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
73244 break;
73246 #endif /* SQLITE_OMIT_CAST */
73247 case TK_LT:
73248 case TK_LE:
73249 case TK_GT:
73250 case TK_GE:
73251 case TK_NE:
73252 case TK_EQ: {
73253 assert( TK_LT==OP_Lt );
73254 assert( TK_LE==OP_Le );
73255 assert( TK_GT==OP_Gt );
73256 assert( TK_GE==OP_Ge );
73257 assert( TK_EQ==OP_Eq );
73258 assert( TK_NE==OP_Ne );
73259 testcase( op==TK_LT );
73260 testcase( op==TK_LE );
73261 testcase( op==TK_GT );
73262 testcase( op==TK_GE );
73263 testcase( op==TK_EQ );
73264 testcase( op==TK_NE );
73265 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73266 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73267 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73268 r1, r2, inReg, SQLITE_STOREP2);
73269 testcase( regFree1==0 );
73270 testcase( regFree2==0 );
73271 break;
73273 case TK_IS:
73274 case TK_ISNOT: {
73275 testcase( op==TK_IS );
73276 testcase( op==TK_ISNOT );
73277 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73278 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73279 op = (op==TK_IS) ? TK_EQ : TK_NE;
73280 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73281 r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
73282 testcase( regFree1==0 );
73283 testcase( regFree2==0 );
73284 break;
73286 case TK_AND:
73287 case TK_OR:
73288 case TK_PLUS:
73289 case TK_STAR:
73290 case TK_MINUS:
73291 case TK_REM:
73292 case TK_BITAND:
73293 case TK_BITOR:
73294 case TK_SLASH:
73295 case TK_LSHIFT:
73296 case TK_RSHIFT:
73297 case TK_CONCAT: {
73298 assert( TK_AND==OP_And );
73299 assert( TK_OR==OP_Or );
73300 assert( TK_PLUS==OP_Add );
73301 assert( TK_MINUS==OP_Subtract );
73302 assert( TK_REM==OP_Remainder );
73303 assert( TK_BITAND==OP_BitAnd );
73304 assert( TK_BITOR==OP_BitOr );
73305 assert( TK_SLASH==OP_Divide );
73306 assert( TK_LSHIFT==OP_ShiftLeft );
73307 assert( TK_RSHIFT==OP_ShiftRight );
73308 assert( TK_CONCAT==OP_Concat );
73309 testcase( op==TK_AND );
73310 testcase( op==TK_OR );
73311 testcase( op==TK_PLUS );
73312 testcase( op==TK_MINUS );
73313 testcase( op==TK_REM );
73314 testcase( op==TK_BITAND );
73315 testcase( op==TK_BITOR );
73316 testcase( op==TK_SLASH );
73317 testcase( op==TK_LSHIFT );
73318 testcase( op==TK_RSHIFT );
73319 testcase( op==TK_CONCAT );
73320 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73321 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73322 sqlite3VdbeAddOp3(v, op, r2, r1, target);
73323 testcase( regFree1==0 );
73324 testcase( regFree2==0 );
73325 break;
73327 case TK_UMINUS: {
73328 Expr *pLeft = pExpr->pLeft;
73329 assert( pLeft );
73330 if( pLeft->op==TK_INTEGER ){
73331 codeInteger(pParse, pLeft, 1, target);
73332 #ifndef SQLITE_OMIT_FLOATING_POINT
73333 }else if( pLeft->op==TK_FLOAT ){
73334 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73335 codeReal(v, pLeft->u.zToken, 1, target);
73336 #endif
73337 }else{
73338 regFree1 = r1 = sqlite3GetTempReg(pParse);
73339 sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
73340 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
73341 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
73342 testcase( regFree2==0 );
73344 inReg = target;
73345 break;
73347 case TK_BITNOT:
73348 case TK_NOT: {
73349 assert( TK_BITNOT==OP_BitNot );
73350 assert( TK_NOT==OP_Not );
73351 testcase( op==TK_BITNOT );
73352 testcase( op==TK_NOT );
73353 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73354 testcase( regFree1==0 );
73355 inReg = target;
73356 sqlite3VdbeAddOp2(v, op, r1, inReg);
73357 break;
73359 case TK_ISNULL:
73360 case TK_NOTNULL: {
73361 int addr;
73362 assert( TK_ISNULL==OP_IsNull );
73363 assert( TK_NOTNULL==OP_NotNull );
73364 testcase( op==TK_ISNULL );
73365 testcase( op==TK_NOTNULL );
73366 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73367 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73368 testcase( regFree1==0 );
73369 addr = sqlite3VdbeAddOp1(v, op, r1);
73370 sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
73371 sqlite3VdbeJumpHere(v, addr);
73372 break;
73374 case TK_AGG_FUNCTION: {
73375 AggInfo *pInfo = pExpr->pAggInfo;
73376 if( pInfo==0 ){
73377 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73378 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
73379 }else{
73380 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
73382 break;
73384 case TK_CONST_FUNC:
73385 case TK_FUNCTION: {
73386 ExprList *pFarg; /* List of function arguments */
73387 int nFarg; /* Number of function arguments */
73388 FuncDef *pDef; /* The function definition object */
73389 int nId; /* Length of the function name in bytes */
73390 const char *zId; /* The function name */
73391 int constMask = 0; /* Mask of function arguments that are constant */
73392 int i; /* Loop counter */
73393 u8 enc = ENC(db); /* The text encoding used by this database */
73394 CollSeq *pColl = 0; /* A collating sequence */
73396 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73397 testcase( op==TK_CONST_FUNC );
73398 testcase( op==TK_FUNCTION );
73399 if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
73400 pFarg = 0;
73401 }else{
73402 pFarg = pExpr->x.pList;
73404 nFarg = pFarg ? pFarg->nExpr : 0;
73405 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73406 zId = pExpr->u.zToken;
73407 nId = sqlite3Strlen30(zId);
73408 pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
73409 if( pDef==0 ){
73410 sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
73411 break;
73414 /* Attempt a direct implementation of the built-in COALESCE() and
73415 ** IFNULL() functions. This avoids unnecessary evalation of
73416 ** arguments past the first non-NULL argument.
73418 if( pDef->flags & SQLITE_FUNC_COALESCE ){
73419 int endCoalesce = sqlite3VdbeMakeLabel(v);
73420 assert( nFarg>=2 );
73421 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
73422 for(i=1; i<nFarg; i++){
73423 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
73424 sqlite3ExprCacheRemove(pParse, target, 1);
73425 sqlite3ExprCachePush(pParse);
73426 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
73427 sqlite3ExprCachePop(pParse, 1);
73429 sqlite3VdbeResolveLabel(v, endCoalesce);
73430 break;
73434 if( pFarg ){
73435 r1 = sqlite3GetTempRange(pParse, nFarg);
73436 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
73437 sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
73438 sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
73439 }else{
73440 r1 = 0;
73442 #ifndef SQLITE_OMIT_VIRTUALTABLE
73443 /* Possibly overload the function if the first argument is
73444 ** a virtual table column.
73446 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
73447 ** second argument, not the first, as the argument to test to
73448 ** see if it is a column in a virtual table. This is done because
73449 ** the left operand of infix functions (the operand we want to
73450 ** control overloading) ends up as the second argument to the
73451 ** function. The expression "A glob B" is equivalent to
73452 ** "glob(B,A). We want to use the A in "A glob B" to test
73453 ** for function overloading. But we use the B term in "glob(B,A)".
73455 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
73456 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
73457 }else if( nFarg>0 ){
73458 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
73460 #endif
73461 for(i=0; i<nFarg; i++){
73462 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
73463 constMask |= (1<<i);
73465 if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
73466 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
73469 if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
73470 if( !pColl ) pColl = db->pDfltColl;
73471 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
73473 sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
73474 (char*)pDef, P4_FUNCDEF);
73475 sqlite3VdbeChangeP5(v, (u8)nFarg);
73476 if( nFarg ){
73477 sqlite3ReleaseTempRange(pParse, r1, nFarg);
73479 break;
73481 #ifndef SQLITE_OMIT_SUBQUERY
73482 case TK_EXISTS:
73483 case TK_SELECT: {
73484 testcase( op==TK_EXISTS );
73485 testcase( op==TK_SELECT );
73486 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
73487 break;
73489 case TK_IN: {
73490 int destIfFalse = sqlite3VdbeMakeLabel(v);
73491 int destIfNull = sqlite3VdbeMakeLabel(v);
73492 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73493 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
73494 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73495 sqlite3VdbeResolveLabel(v, destIfFalse);
73496 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
73497 sqlite3VdbeResolveLabel(v, destIfNull);
73498 break;
73500 #endif /* SQLITE_OMIT_SUBQUERY */
73504 ** x BETWEEN y AND z
73506 ** This is equivalent to
73508 ** x>=y AND x<=z
73510 ** X is stored in pExpr->pLeft.
73511 ** Y is stored in pExpr->pList->a[0].pExpr.
73512 ** Z is stored in pExpr->pList->a[1].pExpr.
73514 case TK_BETWEEN: {
73515 Expr *pLeft = pExpr->pLeft;
73516 struct ExprList_item *pLItem = pExpr->x.pList->a;
73517 Expr *pRight = pLItem->pExpr;
73519 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
73520 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73521 testcase( regFree1==0 );
73522 testcase( regFree2==0 );
73523 r3 = sqlite3GetTempReg(pParse);
73524 r4 = sqlite3GetTempReg(pParse);
73525 codeCompare(pParse, pLeft, pRight, OP_Ge,
73526 r1, r2, r3, SQLITE_STOREP2);
73527 pLItem++;
73528 pRight = pLItem->pExpr;
73529 sqlite3ReleaseTempReg(pParse, regFree2);
73530 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73531 testcase( regFree2==0 );
73532 codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
73533 sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
73534 sqlite3ReleaseTempReg(pParse, r3);
73535 sqlite3ReleaseTempReg(pParse, r4);
73536 break;
73538 case TK_UPLUS: {
73539 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73540 break;
73543 case TK_TRIGGER: {
73544 /* If the opcode is TK_TRIGGER, then the expression is a reference
73545 ** to a column in the new.* or old.* pseudo-tables available to
73546 ** trigger programs. In this case Expr.iTable is set to 1 for the
73547 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
73548 ** is set to the column of the pseudo-table to read, or to -1 to
73549 ** read the rowid field.
73551 ** The expression is implemented using an OP_Param opcode. The p1
73552 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
73553 ** to reference another column of the old.* pseudo-table, where
73554 ** i is the index of the column. For a new.rowid reference, p1 is
73555 ** set to (n+1), where n is the number of columns in each pseudo-table.
73556 ** For a reference to any other column in the new.* pseudo-table, p1
73557 ** is set to (n+2+i), where n and i are as defined previously. For
73558 ** example, if the table on which triggers are being fired is
73559 ** declared as:
73561 ** CREATE TABLE t1(a, b);
73563 ** Then p1 is interpreted as follows:
73565 ** p1==0 -> old.rowid p1==3 -> new.rowid
73566 ** p1==1 -> old.a p1==4 -> new.a
73567 ** p1==2 -> old.b p1==5 -> new.b
73569 Table *pTab = pExpr->pTab;
73570 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
73572 assert( pExpr->iTable==0 || pExpr->iTable==1 );
73573 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
73574 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
73575 assert( p1>=0 && p1<(pTab->nCol*2+2) );
73577 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
73578 VdbeComment((v, "%s.%s -> $%d",
73579 (pExpr->iTable ? "new" : "old"),
73580 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
73581 target
73584 #ifndef SQLITE_OMIT_FLOATING_POINT
73585 /* If the column has REAL affinity, it may currently be stored as an
73586 ** integer. Use OP_RealAffinity to make sure it is really real. */
73587 if( pExpr->iColumn>=0
73588 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
73590 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
73592 #endif
73593 break;
73598 ** Form A:
73599 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73601 ** Form B:
73602 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73604 ** Form A is can be transformed into the equivalent form B as follows:
73605 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
73606 ** WHEN x=eN THEN rN ELSE y END
73608 ** X (if it exists) is in pExpr->pLeft.
73609 ** Y is in pExpr->pRight. The Y is also optional. If there is no
73610 ** ELSE clause and no other term matches, then the result of the
73611 ** exprssion is NULL.
73612 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
73614 ** The result of the expression is the Ri for the first matching Ei,
73615 ** or if there is no matching Ei, the ELSE term Y, or if there is
73616 ** no ELSE term, NULL.
73618 default: assert( op==TK_CASE ); {
73619 int endLabel; /* GOTO label for end of CASE stmt */
73620 int nextCase; /* GOTO label for next WHEN clause */
73621 int nExpr; /* 2x number of WHEN terms */
73622 int i; /* Loop counter */
73623 ExprList *pEList; /* List of WHEN terms */
73624 struct ExprList_item *aListelem; /* Array of WHEN terms */
73625 Expr opCompare; /* The X==Ei expression */
73626 Expr cacheX; /* Cached expression X */
73627 Expr *pX; /* The X expression */
73628 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
73629 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
73631 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
73632 assert((pExpr->x.pList->nExpr % 2) == 0);
73633 assert(pExpr->x.pList->nExpr > 0);
73634 pEList = pExpr->x.pList;
73635 aListelem = pEList->a;
73636 nExpr = pEList->nExpr;
73637 endLabel = sqlite3VdbeMakeLabel(v);
73638 if( (pX = pExpr->pLeft)!=0 ){
73639 cacheX = *pX;
73640 testcase( pX->op==TK_COLUMN );
73641 testcase( pX->op==TK_REGISTER );
73642 cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
73643 testcase( regFree1==0 );
73644 cacheX.op = TK_REGISTER;
73645 opCompare.op = TK_EQ;
73646 opCompare.pLeft = &cacheX;
73647 pTest = &opCompare;
73648 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
73649 ** The value in regFree1 might get SCopy-ed into the file result.
73650 ** So make sure that the regFree1 register is not reused for other
73651 ** purposes and possibly overwritten. */
73652 regFree1 = 0;
73654 for(i=0; i<nExpr; i=i+2){
73655 sqlite3ExprCachePush(pParse);
73656 if( pX ){
73657 assert( pTest!=0 );
73658 opCompare.pRight = aListelem[i].pExpr;
73659 }else{
73660 pTest = aListelem[i].pExpr;
73662 nextCase = sqlite3VdbeMakeLabel(v);
73663 testcase( pTest->op==TK_COLUMN );
73664 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
73665 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
73666 testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
73667 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
73668 sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
73669 sqlite3ExprCachePop(pParse, 1);
73670 sqlite3VdbeResolveLabel(v, nextCase);
73672 if( pExpr->pRight ){
73673 sqlite3ExprCachePush(pParse);
73674 sqlite3ExprCode(pParse, pExpr->pRight, target);
73675 sqlite3ExprCachePop(pParse, 1);
73676 }else{
73677 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73679 assert( db->mallocFailed || pParse->nErr>0
73680 || pParse->iCacheLevel==iCacheLevel );
73681 sqlite3VdbeResolveLabel(v, endLabel);
73682 break;
73684 #ifndef SQLITE_OMIT_TRIGGER
73685 case TK_RAISE: {
73686 assert( pExpr->affinity==OE_Rollback
73687 || pExpr->affinity==OE_Abort
73688 || pExpr->affinity==OE_Fail
73689 || pExpr->affinity==OE_Ignore
73691 if( !pParse->pTriggerTab ){
73692 sqlite3ErrorMsg(pParse,
73693 "RAISE() may only be used within a trigger-program");
73694 return 0;
73696 if( pExpr->affinity==OE_Abort ){
73697 sqlite3MayAbort(pParse);
73699 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73700 if( pExpr->affinity==OE_Ignore ){
73701 sqlite3VdbeAddOp4(
73702 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
73703 }else{
73704 sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
73707 break;
73709 #endif
73711 sqlite3ReleaseTempReg(pParse, regFree1);
73712 sqlite3ReleaseTempReg(pParse, regFree2);
73713 return inReg;
73717 ** Generate code to evaluate an expression and store the results
73718 ** into a register. Return the register number where the results
73719 ** are stored.
73721 ** If the register is a temporary register that can be deallocated,
73722 ** then write its number into *pReg. If the result register is not
73723 ** a temporary, then set *pReg to zero.
73725 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
73726 int r1 = sqlite3GetTempReg(pParse);
73727 int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
73728 if( r2==r1 ){
73729 *pReg = r1;
73730 }else{
73731 sqlite3ReleaseTempReg(pParse, r1);
73732 *pReg = 0;
73734 return r2;
73738 ** Generate code that will evaluate expression pExpr and store the
73739 ** results in register target. The results are guaranteed to appear
73740 ** in register target.
73742 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
73743 int inReg;
73745 assert( target>0 && target<=pParse->nMem );
73746 if( pExpr && pExpr->op==TK_REGISTER ){
73747 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
73748 }else{
73749 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
73750 assert( pParse->pVdbe || pParse->db->mallocFailed );
73751 if( inReg!=target && pParse->pVdbe ){
73752 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
73755 return target;
73759 ** Generate code that evalutes the given expression and puts the result
73760 ** in register target.
73762 ** Also make a copy of the expression results into another "cache" register
73763 ** and modify the expression so that the next time it is evaluated,
73764 ** the result is a copy of the cache register.
73766 ** This routine is used for expressions that are used multiple
73767 ** times. They are evaluated once and the results of the expression
73768 ** are reused.
73770 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
73771 Vdbe *v = pParse->pVdbe;
73772 int inReg;
73773 inReg = sqlite3ExprCode(pParse, pExpr, target);
73774 assert( target>0 );
73775 /* This routine is called for terms to INSERT or UPDATE. And the only
73776 ** other place where expressions can be converted into TK_REGISTER is
73777 ** in WHERE clause processing. So as currently implemented, there is
73778 ** no way for a TK_REGISTER to exist here. But it seems prudent to
73779 ** keep the ALWAYS() in case the conditions above change with future
73780 ** modifications or enhancements. */
73781 if( ALWAYS(pExpr->op!=TK_REGISTER) ){
73782 int iMem;
73783 iMem = ++pParse->nMem;
73784 sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
73785 pExpr->iTable = iMem;
73786 pExpr->op2 = pExpr->op;
73787 pExpr->op = TK_REGISTER;
73789 return inReg;
73793 ** Return TRUE if pExpr is an constant expression that is appropriate
73794 ** for factoring out of a loop. Appropriate expressions are:
73796 ** * Any expression that evaluates to two or more opcodes.
73798 ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
73799 ** or OP_Variable that does not need to be placed in a
73800 ** specific register.
73802 ** There is no point in factoring out single-instruction constant
73803 ** expressions that need to be placed in a particular register.
73804 ** We could factor them out, but then we would end up adding an
73805 ** OP_SCopy instruction to move the value into the correct register
73806 ** later. We might as well just use the original instruction and
73807 ** avoid the OP_SCopy.
73809 static int isAppropriateForFactoring(Expr *p){
73810 if( !sqlite3ExprIsConstantNotJoin(p) ){
73811 return 0; /* Only constant expressions are appropriate for factoring */
73813 if( (p->flags & EP_FixedDest)==0 ){
73814 return 1; /* Any constant without a fixed destination is appropriate */
73816 while( p->op==TK_UPLUS ) p = p->pLeft;
73817 switch( p->op ){
73818 #ifndef SQLITE_OMIT_BLOB_LITERAL
73819 case TK_BLOB:
73820 #endif
73821 case TK_VARIABLE:
73822 case TK_INTEGER:
73823 case TK_FLOAT:
73824 case TK_NULL:
73825 case TK_STRING: {
73826 testcase( p->op==TK_BLOB );
73827 testcase( p->op==TK_VARIABLE );
73828 testcase( p->op==TK_INTEGER );
73829 testcase( p->op==TK_FLOAT );
73830 testcase( p->op==TK_NULL );
73831 testcase( p->op==TK_STRING );
73832 /* Single-instruction constants with a fixed destination are
73833 ** better done in-line. If we factor them, they will just end
73834 ** up generating an OP_SCopy to move the value to the destination
73835 ** register. */
73836 return 0;
73838 case TK_UMINUS: {
73839 if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
73840 return 0;
73842 break;
73844 default: {
73845 break;
73848 return 1;
73852 ** If pExpr is a constant expression that is appropriate for
73853 ** factoring out of a loop, then evaluate the expression
73854 ** into a register and convert the expression into a TK_REGISTER
73855 ** expression.
73857 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
73858 Parse *pParse = pWalker->pParse;
73859 switch( pExpr->op ){
73860 case TK_IN:
73861 case TK_REGISTER: {
73862 return WRC_Prune;
73864 case TK_FUNCTION:
73865 case TK_AGG_FUNCTION:
73866 case TK_CONST_FUNC: {
73867 /* The arguments to a function have a fixed destination.
73868 ** Mark them this way to avoid generated unneeded OP_SCopy
73869 ** instructions.
73871 ExprList *pList = pExpr->x.pList;
73872 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73873 if( pList ){
73874 int i = pList->nExpr;
73875 struct ExprList_item *pItem = pList->a;
73876 for(; i>0; i--, pItem++){
73877 if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
73880 break;
73883 if( isAppropriateForFactoring(pExpr) ){
73884 int r1 = ++pParse->nMem;
73885 int r2;
73886 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
73887 if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
73888 pExpr->op2 = pExpr->op;
73889 pExpr->op = TK_REGISTER;
73890 pExpr->iTable = r2;
73891 return WRC_Prune;
73893 return WRC_Continue;
73897 ** Preevaluate constant subexpressions within pExpr and store the
73898 ** results in registers. Modify pExpr so that the constant subexpresions
73899 ** are TK_REGISTER opcodes that refer to the precomputed values.
73901 ** This routine is a no-op if the jump to the cookie-check code has
73902 ** already occur. Since the cookie-check jump is generated prior to
73903 ** any other serious processing, this check ensures that there is no
73904 ** way to accidently bypass the constant initializations.
73906 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
73907 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
73908 ** interface. This allows test logic to verify that the same answer is
73909 ** obtained for queries regardless of whether or not constants are
73910 ** precomputed into registers or if they are inserted in-line.
73912 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
73913 Walker w;
73914 if( pParse->cookieGoto ) return;
73915 if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
73916 w.xExprCallback = evalConstExpr;
73917 w.xSelectCallback = 0;
73918 w.pParse = pParse;
73919 sqlite3WalkExpr(&w, pExpr);
73924 ** Generate code that pushes the value of every element of the given
73925 ** expression list into a sequence of registers beginning at target.
73927 ** Return the number of elements evaluated.
73929 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
73930 Parse *pParse, /* Parsing context */
73931 ExprList *pList, /* The expression list to be coded */
73932 int target, /* Where to write results */
73933 int doHardCopy /* Make a hard copy of every element */
73935 struct ExprList_item *pItem;
73936 int i, n;
73937 assert( pList!=0 );
73938 assert( target>0 );
73939 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
73940 n = pList->nExpr;
73941 for(pItem=pList->a, i=0; i<n; i++, pItem++){
73942 Expr *pExpr = pItem->pExpr;
73943 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
73944 if( inReg!=target+i ){
73945 sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
73946 inReg, target+i);
73949 return n;
73953 ** Generate code for a BETWEEN operator.
73955 ** x BETWEEN y AND z
73957 ** The above is equivalent to
73959 ** x>=y AND x<=z
73961 ** Code it as such, taking care to do the common subexpression
73962 ** elementation of x.
73964 static void exprCodeBetween(
73965 Parse *pParse, /* Parsing and code generating context */
73966 Expr *pExpr, /* The BETWEEN expression */
73967 int dest, /* Jump here if the jump is taken */
73968 int jumpIfTrue, /* Take the jump if the BETWEEN is true */
73969 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
73971 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
73972 Expr compLeft; /* The x>=y term */
73973 Expr compRight; /* The x<=z term */
73974 Expr exprX; /* The x subexpression */
73975 int regFree1 = 0; /* Temporary use register */
73977 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73978 exprX = *pExpr->pLeft;
73979 exprAnd.op = TK_AND;
73980 exprAnd.pLeft = &compLeft;
73981 exprAnd.pRight = &compRight;
73982 compLeft.op = TK_GE;
73983 compLeft.pLeft = &exprX;
73984 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
73985 compRight.op = TK_LE;
73986 compRight.pLeft = &exprX;
73987 compRight.pRight = pExpr->x.pList->a[1].pExpr;
73988 exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
73989 exprX.op = TK_REGISTER;
73990 if( jumpIfTrue ){
73991 sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
73992 }else{
73993 sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
73995 sqlite3ReleaseTempReg(pParse, regFree1);
73997 /* Ensure adequate test coverage */
73998 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
73999 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
74000 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
74001 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
74002 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
74003 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
74004 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
74005 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
74009 ** Generate code for a boolean expression such that a jump is made
74010 ** to the label "dest" if the expression is true but execution
74011 ** continues straight thru if the expression is false.
74013 ** If the expression evaluates to NULL (neither true nor false), then
74014 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
74016 ** This code depends on the fact that certain token values (ex: TK_EQ)
74017 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
74018 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
74019 ** the make process cause these values to align. Assert()s in the code
74020 ** below verify that the numbers are aligned correctly.
74022 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
74023 Vdbe *v = pParse->pVdbe;
74024 int op = 0;
74025 int regFree1 = 0;
74026 int regFree2 = 0;
74027 int r1, r2;
74029 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
74030 if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
74031 if( NEVER(pExpr==0) ) return; /* No way this can happen */
74032 op = pExpr->op;
74033 switch( op ){
74034 case TK_AND: {
74035 int d2 = sqlite3VdbeMakeLabel(v);
74036 testcase( jumpIfNull==0 );
74037 sqlite3ExprCachePush(pParse);
74038 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
74039 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
74040 sqlite3VdbeResolveLabel(v, d2);
74041 sqlite3ExprCachePop(pParse, 1);
74042 break;
74044 case TK_OR: {
74045 testcase( jumpIfNull==0 );
74046 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
74047 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
74048 break;
74050 case TK_NOT: {
74051 testcase( jumpIfNull==0 );
74052 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
74053 break;
74055 case TK_LT:
74056 case TK_LE:
74057 case TK_GT:
74058 case TK_GE:
74059 case TK_NE:
74060 case TK_EQ: {
74061 assert( TK_LT==OP_Lt );
74062 assert( TK_LE==OP_Le );
74063 assert( TK_GT==OP_Gt );
74064 assert( TK_GE==OP_Ge );
74065 assert( TK_EQ==OP_Eq );
74066 assert( TK_NE==OP_Ne );
74067 testcase( op==TK_LT );
74068 testcase( op==TK_LE );
74069 testcase( op==TK_GT );
74070 testcase( op==TK_GE );
74071 testcase( op==TK_EQ );
74072 testcase( op==TK_NE );
74073 testcase( jumpIfNull==0 );
74074 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74075 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74076 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74077 r1, r2, dest, jumpIfNull);
74078 testcase( regFree1==0 );
74079 testcase( regFree2==0 );
74080 break;
74082 case TK_IS:
74083 case TK_ISNOT: {
74084 testcase( op==TK_IS );
74085 testcase( op==TK_ISNOT );
74086 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74087 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74088 op = (op==TK_IS) ? TK_EQ : TK_NE;
74089 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74090 r1, r2, dest, SQLITE_NULLEQ);
74091 testcase( regFree1==0 );
74092 testcase( regFree2==0 );
74093 break;
74095 case TK_ISNULL:
74096 case TK_NOTNULL: {
74097 assert( TK_ISNULL==OP_IsNull );
74098 assert( TK_NOTNULL==OP_NotNull );
74099 testcase( op==TK_ISNULL );
74100 testcase( op==TK_NOTNULL );
74101 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74102 sqlite3VdbeAddOp2(v, op, r1, dest);
74103 testcase( regFree1==0 );
74104 break;
74106 case TK_BETWEEN: {
74107 testcase( jumpIfNull==0 );
74108 exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
74109 break;
74111 #ifndef SQLITE_OMIT_SUBQUERY
74112 case TK_IN: {
74113 int destIfFalse = sqlite3VdbeMakeLabel(v);
74114 int destIfNull = jumpIfNull ? dest : destIfFalse;
74115 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
74116 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
74117 sqlite3VdbeResolveLabel(v, destIfFalse);
74118 break;
74120 #endif
74121 default: {
74122 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
74123 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
74124 testcase( regFree1==0 );
74125 testcase( jumpIfNull==0 );
74126 break;
74129 sqlite3ReleaseTempReg(pParse, regFree1);
74130 sqlite3ReleaseTempReg(pParse, regFree2);
74134 ** Generate code for a boolean expression such that a jump is made
74135 ** to the label "dest" if the expression is false but execution
74136 ** continues straight thru if the expression is true.
74138 ** If the expression evaluates to NULL (neither true nor false) then
74139 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
74140 ** is 0.
74142 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
74143 Vdbe *v = pParse->pVdbe;
74144 int op = 0;
74145 int regFree1 = 0;
74146 int regFree2 = 0;
74147 int r1, r2;
74149 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
74150 if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
74151 if( pExpr==0 ) return;
74153 /* The value of pExpr->op and op are related as follows:
74155 ** pExpr->op op
74156 ** --------- ----------
74157 ** TK_ISNULL OP_NotNull
74158 ** TK_NOTNULL OP_IsNull
74159 ** TK_NE OP_Eq
74160 ** TK_EQ OP_Ne
74161 ** TK_GT OP_Le
74162 ** TK_LE OP_Gt
74163 ** TK_GE OP_Lt
74164 ** TK_LT OP_Ge
74166 ** For other values of pExpr->op, op is undefined and unused.
74167 ** The value of TK_ and OP_ constants are arranged such that we
74168 ** can compute the mapping above using the following expression.
74169 ** Assert()s verify that the computation is correct.
74171 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
74173 /* Verify correct alignment of TK_ and OP_ constants
74175 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
74176 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
74177 assert( pExpr->op!=TK_NE || op==OP_Eq );
74178 assert( pExpr->op!=TK_EQ || op==OP_Ne );
74179 assert( pExpr->op!=TK_LT || op==OP_Ge );
74180 assert( pExpr->op!=TK_LE || op==OP_Gt );
74181 assert( pExpr->op!=TK_GT || op==OP_Le );
74182 assert( pExpr->op!=TK_GE || op==OP_Lt );
74184 switch( pExpr->op ){
74185 case TK_AND: {
74186 testcase( jumpIfNull==0 );
74187 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
74188 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
74189 break;
74191 case TK_OR: {
74192 int d2 = sqlite3VdbeMakeLabel(v);
74193 testcase( jumpIfNull==0 );
74194 sqlite3ExprCachePush(pParse);
74195 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
74196 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
74197 sqlite3VdbeResolveLabel(v, d2);
74198 sqlite3ExprCachePop(pParse, 1);
74199 break;
74201 case TK_NOT: {
74202 testcase( jumpIfNull==0 );
74203 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
74204 break;
74206 case TK_LT:
74207 case TK_LE:
74208 case TK_GT:
74209 case TK_GE:
74210 case TK_NE:
74211 case TK_EQ: {
74212 testcase( op==TK_LT );
74213 testcase( op==TK_LE );
74214 testcase( op==TK_GT );
74215 testcase( op==TK_GE );
74216 testcase( op==TK_EQ );
74217 testcase( op==TK_NE );
74218 testcase( jumpIfNull==0 );
74219 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74220 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74221 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74222 r1, r2, dest, jumpIfNull);
74223 testcase( regFree1==0 );
74224 testcase( regFree2==0 );
74225 break;
74227 case TK_IS:
74228 case TK_ISNOT: {
74229 testcase( pExpr->op==TK_IS );
74230 testcase( pExpr->op==TK_ISNOT );
74231 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74232 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74233 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
74234 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74235 r1, r2, dest, SQLITE_NULLEQ);
74236 testcase( regFree1==0 );
74237 testcase( regFree2==0 );
74238 break;
74240 case TK_ISNULL:
74241 case TK_NOTNULL: {
74242 testcase( op==TK_ISNULL );
74243 testcase( op==TK_NOTNULL );
74244 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74245 sqlite3VdbeAddOp2(v, op, r1, dest);
74246 testcase( regFree1==0 );
74247 break;
74249 case TK_BETWEEN: {
74250 testcase( jumpIfNull==0 );
74251 exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
74252 break;
74254 #ifndef SQLITE_OMIT_SUBQUERY
74255 case TK_IN: {
74256 if( jumpIfNull ){
74257 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
74258 }else{
74259 int destIfNull = sqlite3VdbeMakeLabel(v);
74260 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
74261 sqlite3VdbeResolveLabel(v, destIfNull);
74263 break;
74265 #endif
74266 default: {
74267 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
74268 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
74269 testcase( regFree1==0 );
74270 testcase( jumpIfNull==0 );
74271 break;
74274 sqlite3ReleaseTempReg(pParse, regFree1);
74275 sqlite3ReleaseTempReg(pParse, regFree2);
74279 ** Do a deep comparison of two expression trees. Return 0 if the two
74280 ** expressions are completely identical. Return 1 if they differ only
74281 ** by a COLLATE operator at the top level. Return 2 if there are differences
74282 ** other than the top-level COLLATE operator.
74284 ** Sometimes this routine will return 2 even if the two expressions
74285 ** really are equivalent. If we cannot prove that the expressions are
74286 ** identical, we return 2 just to be safe. So if this routine
74287 ** returns 2, then you do not really know for certain if the two
74288 ** expressions are the same. But if you get a 0 or 1 return, then you
74289 ** can be sure the expressions are the same. In the places where
74290 ** this routine is used, it does not hurt to get an extra 2 - that
74291 ** just might result in some slightly slower code. But returning
74292 ** an incorrect 0 or 1 could lead to a malfunction.
74294 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
74295 if( pA==0||pB==0 ){
74296 return pB==pA ? 0 : 2;
74298 assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
74299 assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
74300 if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
74301 return 2;
74303 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
74304 if( pA->op!=pB->op ) return 2;
74305 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
74306 if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
74307 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
74308 if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
74309 if( ExprHasProperty(pA, EP_IntValue) ){
74310 if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
74311 return 2;
74313 }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
74314 if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
74315 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
74316 return 2;
74319 if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
74320 if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
74321 return 0;
74325 ** Compare two ExprList objects. Return 0 if they are identical and
74326 ** non-zero if they differ in any way.
74328 ** This routine might return non-zero for equivalent ExprLists. The
74329 ** only consequence will be disabled optimizations. But this routine
74330 ** must never return 0 if the two ExprList objects are different, or
74331 ** a malfunction will result.
74333 ** Two NULL pointers are considered to be the same. But a NULL pointer
74334 ** always differs from a non-NULL pointer.
74336 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
74337 int i;
74338 if( pA==0 && pB==0 ) return 0;
74339 if( pA==0 || pB==0 ) return 1;
74340 if( pA->nExpr!=pB->nExpr ) return 1;
74341 for(i=0; i<pA->nExpr; i++){
74342 Expr *pExprA = pA->a[i].pExpr;
74343 Expr *pExprB = pB->a[i].pExpr;
74344 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
74345 if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
74347 return 0;
74351 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
74352 ** the new element. Return a negative number if malloc fails.
74354 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
74355 int i;
74356 pInfo->aCol = sqlite3ArrayAllocate(
74358 pInfo->aCol,
74359 sizeof(pInfo->aCol[0]),
74361 &pInfo->nColumn,
74362 &pInfo->nColumnAlloc,
74365 return i;
74369 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
74370 ** the new element. Return a negative number if malloc fails.
74372 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
74373 int i;
74374 pInfo->aFunc = sqlite3ArrayAllocate(
74375 db,
74376 pInfo->aFunc,
74377 sizeof(pInfo->aFunc[0]),
74379 &pInfo->nFunc,
74380 &pInfo->nFuncAlloc,
74383 return i;
74387 ** This is the xExprCallback for a tree walker. It is used to
74388 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
74389 ** for additional information.
74391 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
74392 int i;
74393 NameContext *pNC = pWalker->u.pNC;
74394 Parse *pParse = pNC->pParse;
74395 SrcList *pSrcList = pNC->pSrcList;
74396 AggInfo *pAggInfo = pNC->pAggInfo;
74398 switch( pExpr->op ){
74399 case TK_AGG_COLUMN:
74400 case TK_COLUMN: {
74401 testcase( pExpr->op==TK_AGG_COLUMN );
74402 testcase( pExpr->op==TK_COLUMN );
74403 /* Check to see if the column is in one of the tables in the FROM
74404 ** clause of the aggregate query */
74405 if( ALWAYS(pSrcList!=0) ){
74406 struct SrcList_item *pItem = pSrcList->a;
74407 for(i=0; i<pSrcList->nSrc; i++, pItem++){
74408 struct AggInfo_col *pCol;
74409 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74410 if( pExpr->iTable==pItem->iCursor ){
74411 /* If we reach this point, it means that pExpr refers to a table
74412 ** that is in the FROM clause of the aggregate query.
74414 ** Make an entry for the column in pAggInfo->aCol[] if there
74415 ** is not an entry there already.
74417 int k;
74418 pCol = pAggInfo->aCol;
74419 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
74420 if( pCol->iTable==pExpr->iTable &&
74421 pCol->iColumn==pExpr->iColumn ){
74422 break;
74425 if( (k>=pAggInfo->nColumn)
74426 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
74428 pCol = &pAggInfo->aCol[k];
74429 pCol->pTab = pExpr->pTab;
74430 pCol->iTable = pExpr->iTable;
74431 pCol->iColumn = pExpr->iColumn;
74432 pCol->iMem = ++pParse->nMem;
74433 pCol->iSorterColumn = -1;
74434 pCol->pExpr = pExpr;
74435 if( pAggInfo->pGroupBy ){
74436 int j, n;
74437 ExprList *pGB = pAggInfo->pGroupBy;
74438 struct ExprList_item *pTerm = pGB->a;
74439 n = pGB->nExpr;
74440 for(j=0; j<n; j++, pTerm++){
74441 Expr *pE = pTerm->pExpr;
74442 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
74443 pE->iColumn==pExpr->iColumn ){
74444 pCol->iSorterColumn = j;
74445 break;
74449 if( pCol->iSorterColumn<0 ){
74450 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
74453 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
74454 ** because it was there before or because we just created it).
74455 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
74456 ** pAggInfo->aCol[] entry.
74458 ExprSetIrreducible(pExpr);
74459 pExpr->pAggInfo = pAggInfo;
74460 pExpr->op = TK_AGG_COLUMN;
74461 pExpr->iAgg = (i16)k;
74462 break;
74463 } /* endif pExpr->iTable==pItem->iCursor */
74464 } /* end loop over pSrcList */
74466 return WRC_Prune;
74468 case TK_AGG_FUNCTION: {
74469 /* The pNC->nDepth==0 test causes aggregate functions in subqueries
74470 ** to be ignored */
74471 if( pNC->nDepth==0 ){
74472 /* Check to see if pExpr is a duplicate of another aggregate
74473 ** function that is already in the pAggInfo structure
74475 struct AggInfo_func *pItem = pAggInfo->aFunc;
74476 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
74477 if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
74478 break;
74481 if( i>=pAggInfo->nFunc ){
74482 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
74484 u8 enc = ENC(pParse->db);
74485 i = addAggInfoFunc(pParse->db, pAggInfo);
74486 if( i>=0 ){
74487 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74488 pItem = &pAggInfo->aFunc[i];
74489 pItem->pExpr = pExpr;
74490 pItem->iMem = ++pParse->nMem;
74491 assert( !ExprHasProperty(pExpr, EP_IntValue) );
74492 pItem->pFunc = sqlite3FindFunction(pParse->db,
74493 pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
74494 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
74495 if( pExpr->flags & EP_Distinct ){
74496 pItem->iDistinct = pParse->nTab++;
74497 }else{
74498 pItem->iDistinct = -1;
74502 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
74504 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74505 ExprSetIrreducible(pExpr);
74506 pExpr->iAgg = (i16)i;
74507 pExpr->pAggInfo = pAggInfo;
74508 return WRC_Prune;
74512 return WRC_Continue;
74514 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
74515 NameContext *pNC = pWalker->u.pNC;
74516 if( pNC->nDepth==0 ){
74517 pNC->nDepth++;
74518 sqlite3WalkSelect(pWalker, pSelect);
74519 pNC->nDepth--;
74520 return WRC_Prune;
74521 }else{
74522 return WRC_Continue;
74527 ** Analyze the given expression looking for aggregate functions and
74528 ** for variables that need to be added to the pParse->aAgg[] array.
74529 ** Make additional entries to the pParse->aAgg[] array as necessary.
74531 ** This routine should only be called after the expression has been
74532 ** analyzed by sqlite3ResolveExprNames().
74534 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
74535 Walker w;
74536 w.xExprCallback = analyzeAggregate;
74537 w.xSelectCallback = analyzeAggregatesInSelect;
74538 w.u.pNC = pNC;
74539 assert( pNC->pSrcList!=0 );
74540 sqlite3WalkExpr(&w, pExpr);
74544 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
74545 ** expression list. Return the number of errors.
74547 ** If an error is found, the analysis is cut short.
74549 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
74550 struct ExprList_item *pItem;
74551 int i;
74552 if( pList ){
74553 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
74554 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
74560 ** Allocate a single new register for use to hold some intermediate result.
74562 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
74563 if( pParse->nTempReg==0 ){
74564 return ++pParse->nMem;
74566 return pParse->aTempReg[--pParse->nTempReg];
74570 ** Deallocate a register, making available for reuse for some other
74571 ** purpose.
74573 ** If a register is currently being used by the column cache, then
74574 ** the dallocation is deferred until the column cache line that uses
74575 ** the register becomes stale.
74577 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
74578 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
74579 int i;
74580 struct yColCache *p;
74581 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
74582 if( p->iReg==iReg ){
74583 p->tempReg = 1;
74584 return;
74587 pParse->aTempReg[pParse->nTempReg++] = iReg;
74592 ** Allocate or deallocate a block of nReg consecutive registers
74594 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
74595 int i, n;
74596 i = pParse->iRangeReg;
74597 n = pParse->nRangeReg;
74598 if( nReg<=n ){
74599 assert( !usedAsColumnCache(pParse, i, i+n-1) );
74600 pParse->iRangeReg += nReg;
74601 pParse->nRangeReg -= nReg;
74602 }else{
74603 i = pParse->nMem+1;
74604 pParse->nMem += nReg;
74606 return i;
74608 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
74609 sqlite3ExprCacheRemove(pParse, iReg, nReg);
74610 if( nReg>pParse->nRangeReg ){
74611 pParse->nRangeReg = nReg;
74612 pParse->iRangeReg = iReg;
74616 /************** End of expr.c ************************************************/
74617 /************** Begin file alter.c *******************************************/
74619 ** 2005 February 15
74621 ** The author disclaims copyright to this source code. In place of
74622 ** a legal notice, here is a blessing:
74624 ** May you do good and not evil.
74625 ** May you find forgiveness for yourself and forgive others.
74626 ** May you share freely, never taking more than you give.
74628 *************************************************************************
74629 ** This file contains C code routines that used to generate VDBE code
74630 ** that implements the ALTER TABLE command.
74634 ** The code in this file only exists if we are not omitting the
74635 ** ALTER TABLE logic from the build.
74637 #ifndef SQLITE_OMIT_ALTERTABLE
74641 ** This function is used by SQL generated to implement the
74642 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
74643 ** CREATE INDEX command. The second is a table name. The table name in
74644 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
74645 ** argument and the result returned. Examples:
74647 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
74648 ** -> 'CREATE TABLE def(a, b, c)'
74650 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
74651 ** -> 'CREATE INDEX i ON def(a, b, c)'
74653 static void renameTableFunc(
74654 sqlite3_context *context,
74655 int NotUsed,
74656 sqlite3_value **argv
74658 unsigned char const *zSql = sqlite3_value_text(argv[0]);
74659 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
74661 int token;
74662 Token tname;
74663 unsigned char const *zCsr = zSql;
74664 int len = 0;
74665 char *zRet;
74667 sqlite3 *db = sqlite3_context_db_handle(context);
74669 UNUSED_PARAMETER(NotUsed);
74671 /* The principle used to locate the table name in the CREATE TABLE
74672 ** statement is that the table name is the first non-space token that
74673 ** is immediately followed by a TK_LP or TK_USING token.
74675 if( zSql ){
74676 do {
74677 if( !*zCsr ){
74678 /* Ran out of input before finding an opening bracket. Return NULL. */
74679 return;
74682 /* Store the token that zCsr points to in tname. */
74683 tname.z = (char*)zCsr;
74684 tname.n = len;
74686 /* Advance zCsr to the next token. Store that token type in 'token',
74687 ** and its length in 'len' (to be used next iteration of this loop).
74689 do {
74690 zCsr += len;
74691 len = sqlite3GetToken(zCsr, &token);
74692 } while( token==TK_SPACE );
74693 assert( len>0 );
74694 } while( token!=TK_LP && token!=TK_USING );
74696 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
74697 zTableName, tname.z+tname.n);
74698 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
74703 ** This C function implements an SQL user function that is used by SQL code
74704 ** generated by the ALTER TABLE ... RENAME command to modify the definition
74705 ** of any foreign key constraints that use the table being renamed as the
74706 ** parent table. It is passed three arguments:
74708 ** 1) The complete text of the CREATE TABLE statement being modified,
74709 ** 2) The old name of the table being renamed, and
74710 ** 3) The new name of the table being renamed.
74712 ** It returns the new CREATE TABLE statement. For example:
74714 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
74715 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
74717 #ifndef SQLITE_OMIT_FOREIGN_KEY
74718 static void renameParentFunc(
74719 sqlite3_context *context,
74720 int NotUsed,
74721 sqlite3_value **argv
74723 sqlite3 *db = sqlite3_context_db_handle(context);
74724 char *zOutput = 0;
74725 char *zResult;
74726 unsigned char const *zInput = sqlite3_value_text(argv[0]);
74727 unsigned char const *zOld = sqlite3_value_text(argv[1]);
74728 unsigned char const *zNew = sqlite3_value_text(argv[2]);
74730 unsigned const char *z; /* Pointer to token */
74731 int n; /* Length of token z */
74732 int token; /* Type of token */
74734 UNUSED_PARAMETER(NotUsed);
74735 for(z=zInput; *z; z=z+n){
74736 n = sqlite3GetToken(z, &token);
74737 if( token==TK_REFERENCES ){
74738 char *zParent;
74739 do {
74740 z += n;
74741 n = sqlite3GetToken(z, &token);
74742 }while( token==TK_SPACE );
74744 zParent = sqlite3DbStrNDup(db, (const char *)z, n);
74745 if( zParent==0 ) break;
74746 sqlite3Dequote(zParent);
74747 if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
74748 char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
74749 (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
74751 sqlite3DbFree(db, zOutput);
74752 zOutput = zOut;
74753 zInput = &z[n];
74755 sqlite3DbFree(db, zParent);
74759 zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
74760 sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
74761 sqlite3DbFree(db, zOutput);
74763 #endif
74765 #ifndef SQLITE_OMIT_TRIGGER
74766 /* This function is used by SQL generated to implement the
74767 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
74768 ** statement. The second is a table name. The table name in the CREATE
74769 ** TRIGGER statement is replaced with the third argument and the result
74770 ** returned. This is analagous to renameTableFunc() above, except for CREATE
74771 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
74773 static void renameTriggerFunc(
74774 sqlite3_context *context,
74775 int NotUsed,
74776 sqlite3_value **argv
74778 unsigned char const *zSql = sqlite3_value_text(argv[0]);
74779 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
74781 int token;
74782 Token tname;
74783 int dist = 3;
74784 unsigned char const *zCsr = zSql;
74785 int len = 0;
74786 char *zRet;
74787 sqlite3 *db = sqlite3_context_db_handle(context);
74789 UNUSED_PARAMETER(NotUsed);
74791 /* The principle used to locate the table name in the CREATE TRIGGER
74792 ** statement is that the table name is the first token that is immediatedly
74793 ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
74794 ** of TK_WHEN, TK_BEGIN or TK_FOR.
74796 if( zSql ){
74797 do {
74799 if( !*zCsr ){
74800 /* Ran out of input before finding the table name. Return NULL. */
74801 return;
74804 /* Store the token that zCsr points to in tname. */
74805 tname.z = (char*)zCsr;
74806 tname.n = len;
74808 /* Advance zCsr to the next token. Store that token type in 'token',
74809 ** and its length in 'len' (to be used next iteration of this loop).
74811 do {
74812 zCsr += len;
74813 len = sqlite3GetToken(zCsr, &token);
74814 }while( token==TK_SPACE );
74815 assert( len>0 );
74817 /* Variable 'dist' stores the number of tokens read since the most
74818 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
74819 ** token is read and 'dist' equals 2, the condition stated above
74820 ** to be met.
74822 ** Note that ON cannot be a database, table or column name, so
74823 ** there is no need to worry about syntax like
74824 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
74826 dist++;
74827 if( token==TK_DOT || token==TK_ON ){
74828 dist = 0;
74830 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
74832 /* Variable tname now contains the token that is the old table-name
74833 ** in the CREATE TRIGGER statement.
74835 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
74836 zTableName, tname.z+tname.n);
74837 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
74840 #endif /* !SQLITE_OMIT_TRIGGER */
74843 ** Register built-in functions used to help implement ALTER TABLE
74845 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
74846 static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
74847 FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
74848 #ifndef SQLITE_OMIT_TRIGGER
74849 FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
74850 #endif
74851 #ifndef SQLITE_OMIT_FOREIGN_KEY
74852 FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
74853 #endif
74855 int i;
74856 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
74857 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
74859 for(i=0; i<ArraySize(aAlterTableFuncs); i++){
74860 sqlite3FuncDefInsert(pHash, &aFunc[i]);
74865 ** This function is used to create the text of expressions of the form:
74867 ** name=<constant1> OR name=<constant2> OR ...
74869 ** If argument zWhere is NULL, then a pointer string containing the text
74870 ** "name=<constant>" is returned, where <constant> is the quoted version
74871 ** of the string passed as argument zConstant. The returned buffer is
74872 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
74873 ** caller to ensure that it is eventually freed.
74875 ** If argument zWhere is not NULL, then the string returned is
74876 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
74877 ** In this case zWhere is passed to sqlite3DbFree() before returning.
74880 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
74881 char *zNew;
74882 if( !zWhere ){
74883 zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
74884 }else{
74885 zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
74886 sqlite3DbFree(db, zWhere);
74888 return zNew;
74891 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
74893 ** Generate the text of a WHERE expression which can be used to select all
74894 ** tables that have foreign key constraints that refer to table pTab (i.e.
74895 ** constraints for which pTab is the parent table) from the sqlite_master
74896 ** table.
74898 static char *whereForeignKeys(Parse *pParse, Table *pTab){
74899 FKey *p;
74900 char *zWhere = 0;
74901 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
74902 zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
74904 return zWhere;
74906 #endif
74909 ** Generate the text of a WHERE expression which can be used to select all
74910 ** temporary triggers on table pTab from the sqlite_temp_master table. If
74911 ** table pTab has no temporary triggers, or is itself stored in the
74912 ** temporary database, NULL is returned.
74914 static char *whereTempTriggers(Parse *pParse, Table *pTab){
74915 Trigger *pTrig;
74916 char *zWhere = 0;
74917 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
74919 /* If the table is not located in the temp-db (in which case NULL is
74920 ** returned, loop through the tables list of triggers. For each trigger
74921 ** that is not part of the temp-db schema, add a clause to the WHERE
74922 ** expression being built up in zWhere.
74924 if( pTab->pSchema!=pTempSchema ){
74925 sqlite3 *db = pParse->db;
74926 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
74927 if( pTrig->pSchema==pTempSchema ){
74928 zWhere = whereOrName(db, zWhere, pTrig->zName);
74932 if( zWhere ){
74933 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
74934 sqlite3DbFree(pParse->db, zWhere);
74935 zWhere = zNew;
74937 return zWhere;
74941 ** Generate code to drop and reload the internal representation of table
74942 ** pTab from the database, including triggers and temporary triggers.
74943 ** Argument zName is the name of the table in the database schema at
74944 ** the time the generated code is executed. This can be different from
74945 ** pTab->zName if this function is being called to code part of an
74946 ** "ALTER TABLE RENAME TO" statement.
74948 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
74949 Vdbe *v;
74950 char *zWhere;
74951 int iDb; /* Index of database containing pTab */
74952 #ifndef SQLITE_OMIT_TRIGGER
74953 Trigger *pTrig;
74954 #endif
74956 v = sqlite3GetVdbe(pParse);
74957 if( NEVER(v==0) ) return;
74958 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
74959 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74960 assert( iDb>=0 );
74962 #ifndef SQLITE_OMIT_TRIGGER
74963 /* Drop any table triggers from the internal schema. */
74964 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
74965 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
74966 assert( iTrigDb==iDb || iTrigDb==1 );
74967 sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
74969 #endif
74971 /* Drop the table and index from the internal schema. */
74972 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
74974 /* Reload the table, index and permanent trigger schemas. */
74975 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
74976 if( !zWhere ) return;
74977 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
74979 #ifndef SQLITE_OMIT_TRIGGER
74980 /* Now, if the table is not stored in the temp database, reload any temp
74981 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
74983 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
74984 sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
74986 #endif
74990 ** Parameter zName is the name of a table that is about to be altered
74991 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
74992 ** If the table is a system table, this function leaves an error message
74993 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
74995 ** Or, if zName is not a system table, zero is returned.
74997 static int isSystemTable(Parse *pParse, const char *zName){
74998 if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
74999 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
75000 return 1;
75002 return 0;
75006 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
75007 ** command.
75009 SQLITE_PRIVATE void sqlite3AlterRenameTable(
75010 Parse *pParse, /* Parser context. */
75011 SrcList *pSrc, /* The table to rename. */
75012 Token *pName /* The new table name. */
75014 int iDb; /* Database that contains the table */
75015 char *zDb; /* Name of database iDb */
75016 Table *pTab; /* Table being renamed */
75017 char *zName = 0; /* NULL-terminated version of pName */
75018 sqlite3 *db = pParse->db; /* Database connection */
75019 int nTabName; /* Number of UTF-8 characters in zTabName */
75020 const char *zTabName; /* Original name of the table */
75021 Vdbe *v;
75022 #ifndef SQLITE_OMIT_TRIGGER
75023 char *zWhere = 0; /* Where clause to locate temp triggers */
75024 #endif
75025 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
75026 int savedDbFlags; /* Saved value of db->flags */
75028 savedDbFlags = db->flags;
75029 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
75030 assert( pSrc->nSrc==1 );
75031 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75033 pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
75034 if( !pTab ) goto exit_rename_table;
75035 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75036 zDb = db->aDb[iDb].zName;
75037 db->flags |= SQLITE_PreferBuiltin;
75039 /* Get a NULL terminated version of the new table name. */
75040 zName = sqlite3NameFromToken(db, pName);
75041 if( !zName ) goto exit_rename_table;
75043 /* Check that a table or index named 'zName' does not already exist
75044 ** in database iDb. If so, this is an error.
75046 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
75047 sqlite3ErrorMsg(pParse,
75048 "there is already another table or index with this name: %s", zName);
75049 goto exit_rename_table;
75052 /* Make sure it is not a system table being altered, or a reserved name
75053 ** that the table is being renamed to.
75055 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
75056 goto exit_rename_table;
75058 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
75059 exit_rename_table;
75062 #ifndef SQLITE_OMIT_VIEW
75063 if( pTab->pSelect ){
75064 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
75065 goto exit_rename_table;
75067 #endif
75069 #ifndef SQLITE_OMIT_AUTHORIZATION
75070 /* Invoke the authorization callback. */
75071 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
75072 goto exit_rename_table;
75074 #endif
75076 #ifndef SQLITE_OMIT_VIRTUALTABLE
75077 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
75078 goto exit_rename_table;
75080 if( IsVirtual(pTab) ){
75081 pVTab = sqlite3GetVTable(db, pTab);
75082 if( pVTab->pVtab->pModule->xRename==0 ){
75083 pVTab = 0;
75086 #endif
75088 /* Begin a transaction and code the VerifyCookie for database iDb.
75089 ** Then modify the schema cookie (since the ALTER TABLE modifies the
75090 ** schema). Open a statement transaction if the table is a virtual
75091 ** table.
75093 v = sqlite3GetVdbe(pParse);
75094 if( v==0 ){
75095 goto exit_rename_table;
75097 sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
75098 sqlite3ChangeCookie(pParse, iDb);
75100 /* If this is a virtual table, invoke the xRename() function if
75101 ** one is defined. The xRename() callback will modify the names
75102 ** of any resources used by the v-table implementation (including other
75103 ** SQLite tables) that are identified by the name of the virtual table.
75105 #ifndef SQLITE_OMIT_VIRTUALTABLE
75106 if( pVTab ){
75107 int i = ++pParse->nMem;
75108 sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
75109 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
75110 sqlite3MayAbort(pParse);
75112 #endif
75114 /* figure out how many UTF-8 characters are in zName */
75115 zTabName = pTab->zName;
75116 nTabName = sqlite3Utf8CharLen(zTabName, -1);
75118 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
75119 if( db->flags&SQLITE_ForeignKeys ){
75120 /* If foreign-key support is enabled, rewrite the CREATE TABLE
75121 ** statements corresponding to all child tables of foreign key constraints
75122 ** for which the renamed table is the parent table. */
75123 if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
75124 sqlite3NestedParse(pParse,
75125 "UPDATE \"%w\".%s SET "
75126 "sql = sqlite_rename_parent(sql, %Q, %Q) "
75127 "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
75128 sqlite3DbFree(db, zWhere);
75131 #endif
75133 /* Modify the sqlite_master table to use the new table name. */
75134 sqlite3NestedParse(pParse,
75135 "UPDATE %Q.%s SET "
75136 #ifdef SQLITE_OMIT_TRIGGER
75137 "sql = sqlite_rename_table(sql, %Q), "
75138 #else
75139 "sql = CASE "
75140 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
75141 "ELSE sqlite_rename_table(sql, %Q) END, "
75142 #endif
75143 "tbl_name = %Q, "
75144 "name = CASE "
75145 "WHEN type='table' THEN %Q "
75146 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
75147 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
75148 "ELSE name END "
75149 "WHERE tbl_name=%Q AND "
75150 "(type='table' OR type='index' OR type='trigger');",
75151 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
75152 #ifndef SQLITE_OMIT_TRIGGER
75153 zName,
75154 #endif
75155 zName, nTabName, zTabName
75158 #ifndef SQLITE_OMIT_AUTOINCREMENT
75159 /* If the sqlite_sequence table exists in this database, then update
75160 ** it with the new table name.
75162 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
75163 sqlite3NestedParse(pParse,
75164 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
75165 zDb, zName, pTab->zName);
75167 #endif
75169 #ifndef SQLITE_OMIT_TRIGGER
75170 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
75171 ** table. Don't do this if the table being ALTERed is itself located in
75172 ** the temp database.
75174 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
75175 sqlite3NestedParse(pParse,
75176 "UPDATE sqlite_temp_master SET "
75177 "sql = sqlite_rename_trigger(sql, %Q), "
75178 "tbl_name = %Q "
75179 "WHERE %s;", zName, zName, zWhere);
75180 sqlite3DbFree(db, zWhere);
75182 #endif
75184 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
75185 if( db->flags&SQLITE_ForeignKeys ){
75186 FKey *p;
75187 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
75188 Table *pFrom = p->pFrom;
75189 if( pFrom!=pTab ){
75190 reloadTableSchema(pParse, p->pFrom, pFrom->zName);
75194 #endif
75196 /* Drop and reload the internal table schema. */
75197 reloadTableSchema(pParse, pTab, zName);
75199 exit_rename_table:
75200 sqlite3SrcListDelete(db, pSrc);
75201 sqlite3DbFree(db, zName);
75202 db->flags = savedDbFlags;
75207 ** Generate code to make sure the file format number is at least minFormat.
75208 ** The generated code will increase the file format number if necessary.
75210 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
75211 Vdbe *v;
75212 v = sqlite3GetVdbe(pParse);
75213 /* The VDBE should have been allocated before this routine is called.
75214 ** If that allocation failed, we would have quit before reaching this
75215 ** point */
75216 if( ALWAYS(v) ){
75217 int r1 = sqlite3GetTempReg(pParse);
75218 int r2 = sqlite3GetTempReg(pParse);
75219 int j1;
75220 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
75221 sqlite3VdbeUsesBtree(v, iDb);
75222 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
75223 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
75224 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
75225 sqlite3VdbeJumpHere(v, j1);
75226 sqlite3ReleaseTempReg(pParse, r1);
75227 sqlite3ReleaseTempReg(pParse, r2);
75232 ** This function is called after an "ALTER TABLE ... ADD" statement
75233 ** has been parsed. Argument pColDef contains the text of the new
75234 ** column definition.
75236 ** The Table structure pParse->pNewTable was extended to include
75237 ** the new column during parsing.
75239 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
75240 Table *pNew; /* Copy of pParse->pNewTable */
75241 Table *pTab; /* Table being altered */
75242 int iDb; /* Database number */
75243 const char *zDb; /* Database name */
75244 const char *zTab; /* Table name */
75245 char *zCol; /* Null-terminated column definition */
75246 Column *pCol; /* The new column */
75247 Expr *pDflt; /* Default value for the new column */
75248 sqlite3 *db; /* The database connection; */
75250 db = pParse->db;
75251 if( pParse->nErr || db->mallocFailed ) return;
75252 pNew = pParse->pNewTable;
75253 assert( pNew );
75255 assert( sqlite3BtreeHoldsAllMutexes(db) );
75256 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
75257 zDb = db->aDb[iDb].zName;
75258 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
75259 pCol = &pNew->aCol[pNew->nCol-1];
75260 pDflt = pCol->pDflt;
75261 pTab = sqlite3FindTable(db, zTab, zDb);
75262 assert( pTab );
75264 #ifndef SQLITE_OMIT_AUTHORIZATION
75265 /* Invoke the authorization callback. */
75266 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
75267 return;
75269 #endif
75271 /* If the default value for the new column was specified with a
75272 ** literal NULL, then set pDflt to 0. This simplifies checking
75273 ** for an SQL NULL default below.
75275 if( pDflt && pDflt->op==TK_NULL ){
75276 pDflt = 0;
75279 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
75280 ** If there is a NOT NULL constraint, then the default value for the
75281 ** column must not be NULL.
75283 if( pCol->isPrimKey ){
75284 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
75285 return;
75287 if( pNew->pIndex ){
75288 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
75289 return;
75291 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
75292 sqlite3ErrorMsg(pParse,
75293 "Cannot add a REFERENCES column with non-NULL default value");
75294 return;
75296 if( pCol->notNull && !pDflt ){
75297 sqlite3ErrorMsg(pParse,
75298 "Cannot add a NOT NULL column with default value NULL");
75299 return;
75302 /* Ensure the default expression is something that sqlite3ValueFromExpr()
75303 ** can handle (i.e. not CURRENT_TIME etc.)
75305 if( pDflt ){
75306 sqlite3_value *pVal;
75307 if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
75308 db->mallocFailed = 1;
75309 return;
75311 if( !pVal ){
75312 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
75313 return;
75315 sqlite3ValueFree(pVal);
75318 /* Modify the CREATE TABLE statement. */
75319 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
75320 if( zCol ){
75321 char *zEnd = &zCol[pColDef->n-1];
75322 int savedDbFlags = db->flags;
75323 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
75324 *zEnd-- = '\0';
75326 db->flags |= SQLITE_PreferBuiltin;
75327 sqlite3NestedParse(pParse,
75328 "UPDATE \"%w\".%s SET "
75329 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
75330 "WHERE type = 'table' AND name = %Q",
75331 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
75332 zTab
75334 sqlite3DbFree(db, zCol);
75335 db->flags = savedDbFlags;
75338 /* If the default value of the new column is NULL, then set the file
75339 ** format to 2. If the default value of the new column is not NULL,
75340 ** the file format becomes 3.
75342 sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
75344 /* Reload the schema of the modified table. */
75345 reloadTableSchema(pParse, pTab, pTab->zName);
75349 ** This function is called by the parser after the table-name in
75350 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
75351 ** pSrc is the full-name of the table being altered.
75353 ** This routine makes a (partial) copy of the Table structure
75354 ** for the table being altered and sets Parse.pNewTable to point
75355 ** to it. Routines called by the parser as the column definition
75356 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
75357 ** the copy. The copy of the Table structure is deleted by tokenize.c
75358 ** after parsing is finished.
75360 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
75361 ** coding the "ALTER TABLE ... ADD" statement.
75363 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
75364 Table *pNew;
75365 Table *pTab;
75366 Vdbe *v;
75367 int iDb;
75368 int i;
75369 int nAlloc;
75370 sqlite3 *db = pParse->db;
75372 /* Look up the table being altered. */
75373 assert( pParse->pNewTable==0 );
75374 assert( sqlite3BtreeHoldsAllMutexes(db) );
75375 if( db->mallocFailed ) goto exit_begin_add_column;
75376 pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
75377 if( !pTab ) goto exit_begin_add_column;
75379 #ifndef SQLITE_OMIT_VIRTUALTABLE
75380 if( IsVirtual(pTab) ){
75381 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
75382 goto exit_begin_add_column;
75384 #endif
75386 /* Make sure this is not an attempt to ALTER a view. */
75387 if( pTab->pSelect ){
75388 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
75389 goto exit_begin_add_column;
75391 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
75392 goto exit_begin_add_column;
75395 assert( pTab->addColOffset>0 );
75396 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75398 /* Put a copy of the Table struct in Parse.pNewTable for the
75399 ** sqlite3AddColumn() function and friends to modify. But modify
75400 ** the name by adding an "sqlite_altertab_" prefix. By adding this
75401 ** prefix, we insure that the name will not collide with an existing
75402 ** table because user table are not allowed to have the "sqlite_"
75403 ** prefix on their name.
75405 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
75406 if( !pNew ) goto exit_begin_add_column;
75407 pParse->pNewTable = pNew;
75408 pNew->nRef = 1;
75409 pNew->nCol = pTab->nCol;
75410 assert( pNew->nCol>0 );
75411 nAlloc = (((pNew->nCol-1)/8)*8)+8;
75412 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
75413 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
75414 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
75415 if( !pNew->aCol || !pNew->zName ){
75416 db->mallocFailed = 1;
75417 goto exit_begin_add_column;
75419 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
75420 for(i=0; i<pNew->nCol; i++){
75421 Column *pCol = &pNew->aCol[i];
75422 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
75423 pCol->zColl = 0;
75424 pCol->zType = 0;
75425 pCol->pDflt = 0;
75426 pCol->zDflt = 0;
75428 pNew->pSchema = db->aDb[iDb].pSchema;
75429 pNew->addColOffset = pTab->addColOffset;
75430 pNew->nRef = 1;
75432 /* Begin a transaction and increment the schema cookie. */
75433 sqlite3BeginWriteOperation(pParse, 0, iDb);
75434 v = sqlite3GetVdbe(pParse);
75435 if( !v ) goto exit_begin_add_column;
75436 sqlite3ChangeCookie(pParse, iDb);
75438 exit_begin_add_column:
75439 sqlite3SrcListDelete(db, pSrc);
75440 return;
75442 #endif /* SQLITE_ALTER_TABLE */
75444 /************** End of alter.c ***********************************************/
75445 /************** Begin file analyze.c *****************************************/
75447 ** 2005 July 8
75449 ** The author disclaims copyright to this source code. In place of
75450 ** a legal notice, here is a blessing:
75452 ** May you do good and not evil.
75453 ** May you find forgiveness for yourself and forgive others.
75454 ** May you share freely, never taking more than you give.
75456 *************************************************************************
75457 ** This file contains code associated with the ANALYZE command.
75459 #ifndef SQLITE_OMIT_ANALYZE
75462 ** This routine generates code that opens the sqlite_stat1 table for
75463 ** writing with cursor iStatCur. If the library was built with the
75464 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
75465 ** opened for writing using cursor (iStatCur+1)
75467 ** If the sqlite_stat1 tables does not previously exist, it is created.
75468 ** Similarly, if the sqlite_stat2 table does not exist and the library
75469 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
75471 ** Argument zWhere may be a pointer to a buffer containing a table name,
75472 ** or it may be a NULL pointer. If it is not NULL, then all entries in
75473 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
75474 ** with the named table are deleted. If zWhere==0, then code is generated
75475 ** to delete all stat table entries.
75477 static void openStatTable(
75478 Parse *pParse, /* Parsing context */
75479 int iDb, /* The database we are looking in */
75480 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
75481 const char *zWhere, /* Delete entries for this table or index */
75482 const char *zWhereType /* Either "tbl" or "idx" */
75484 static const struct {
75485 const char *zName;
75486 const char *zCols;
75487 } aTable[] = {
75488 { "sqlite_stat1", "tbl,idx,stat" },
75489 #ifdef SQLITE_ENABLE_STAT2
75490 { "sqlite_stat2", "tbl,idx,sampleno,sample" },
75491 #endif
75494 int aRoot[] = {0, 0};
75495 u8 aCreateTbl[] = {0, 0};
75497 int i;
75498 sqlite3 *db = pParse->db;
75499 Db *pDb;
75500 Vdbe *v = sqlite3GetVdbe(pParse);
75501 if( v==0 ) return;
75502 assert( sqlite3BtreeHoldsAllMutexes(db) );
75503 assert( sqlite3VdbeDb(v)==db );
75504 pDb = &db->aDb[iDb];
75506 for(i=0; i<ArraySize(aTable); i++){
75507 const char *zTab = aTable[i].zName;
75508 Table *pStat;
75509 if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
75510 /* The sqlite_stat[12] table does not exist. Create it. Note that a
75511 ** side-effect of the CREATE TABLE statement is to leave the rootpage
75512 ** of the new table in register pParse->regRoot. This is important
75513 ** because the OpenWrite opcode below will be needing it. */
75514 sqlite3NestedParse(pParse,
75515 "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
75517 aRoot[i] = pParse->regRoot;
75518 aCreateTbl[i] = 1;
75519 }else{
75520 /* The table already exists. If zWhere is not NULL, delete all entries
75521 ** associated with the table zWhere. If zWhere is NULL, delete the
75522 ** entire contents of the table. */
75523 aRoot[i] = pStat->tnum;
75524 sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
75525 if( zWhere ){
75526 sqlite3NestedParse(pParse,
75527 "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
75529 }else{
75530 /* The sqlite_stat[12] table already exists. Delete all rows. */
75531 sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
75536 /* Open the sqlite_stat[12] tables for writing. */
75537 for(i=0; i<ArraySize(aTable); i++){
75538 sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
75539 sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
75540 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
75545 ** Generate code to do an analysis of all indices associated with
75546 ** a single table.
75548 static void analyzeOneTable(
75549 Parse *pParse, /* Parser context */
75550 Table *pTab, /* Table whose indices are to be analyzed */
75551 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
75552 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
75553 int iMem /* Available memory locations begin here */
75555 sqlite3 *db = pParse->db; /* Database handle */
75556 Index *pIdx; /* An index to being analyzed */
75557 int iIdxCur; /* Cursor open on index being analyzed */
75558 Vdbe *v; /* The virtual machine being built up */
75559 int i; /* Loop counter */
75560 int topOfLoop; /* The top of the loop */
75561 int endOfLoop; /* The end of the loop */
75562 int jZeroRows = -1; /* Jump from here if number of rows is zero */
75563 int iDb; /* Index of database containing pTab */
75564 int regTabname = iMem++; /* Register containing table name */
75565 int regIdxname = iMem++; /* Register containing index name */
75566 int regSampleno = iMem++; /* Register containing next sample number */
75567 int regCol = iMem++; /* Content of a column analyzed table */
75568 int regRec = iMem++; /* Register holding completed record */
75569 int regTemp = iMem++; /* Temporary use register */
75570 int regRowid = iMem++; /* Rowid for the inserted record */
75572 #ifdef SQLITE_ENABLE_STAT2
75573 int addr = 0; /* Instruction address */
75574 int regTemp2 = iMem++; /* Temporary use register */
75575 int regSamplerecno = iMem++; /* Index of next sample to record */
75576 int regRecno = iMem++; /* Current sample index */
75577 int regLast = iMem++; /* Index of last sample to record */
75578 int regFirst = iMem++; /* Index of first sample to record */
75579 #endif
75581 v = sqlite3GetVdbe(pParse);
75582 if( v==0 || NEVER(pTab==0) ){
75583 return;
75585 if( pTab->tnum==0 ){
75586 /* Do not gather statistics on views or virtual tables */
75587 return;
75589 if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
75590 /* Do not gather statistics on system tables */
75591 return;
75593 assert( sqlite3BtreeHoldsAllMutexes(db) );
75594 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75595 assert( iDb>=0 );
75596 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75597 #ifndef SQLITE_OMIT_AUTHORIZATION
75598 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
75599 db->aDb[iDb].zName ) ){
75600 return;
75602 #endif
75604 /* Establish a read-lock on the table at the shared-cache level. */
75605 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75607 iIdxCur = pParse->nTab++;
75608 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
75609 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75610 int nCol;
75611 KeyInfo *pKey;
75613 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
75614 nCol = pIdx->nColumn;
75615 pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75616 if( iMem+1+(nCol*2)>pParse->nMem ){
75617 pParse->nMem = iMem+1+(nCol*2);
75620 /* Open a cursor to the index to be analyzed. */
75621 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
75622 sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
75623 (char *)pKey, P4_KEYINFO_HANDOFF);
75624 VdbeComment((v, "%s", pIdx->zName));
75626 /* Populate the register containing the index name. */
75627 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
75629 #ifdef SQLITE_ENABLE_STAT2
75631 /* If this iteration of the loop is generating code to analyze the
75632 ** first index in the pTab->pIndex list, then register regLast has
75633 ** not been populated. In this case populate it now. */
75634 if( pTab->pIndex==pIdx ){
75635 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
75636 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
75637 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
75639 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
75640 sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
75641 addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
75642 sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
75643 sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
75644 sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
75645 sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regLast);
75646 sqlite3VdbeJumpHere(v, addr);
75649 /* Zero the regSampleno and regRecno registers. */
75650 sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
75651 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
75652 sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
75653 #endif
75655 /* The block of memory cells initialized here is used as follows.
75657 ** iMem:
75658 ** The total number of rows in the table.
75660 ** iMem+1 .. iMem+nCol:
75661 ** Number of distinct entries in index considering the
75662 ** left-most N columns only, where N is between 1 and nCol,
75663 ** inclusive.
75665 ** iMem+nCol+1 .. Mem+2*nCol:
75666 ** Previous value of indexed columns, from left to right.
75668 ** Cells iMem through iMem+nCol are initialized to 0. The others are
75669 ** initialized to contain an SQL NULL.
75671 for(i=0; i<=nCol; i++){
75672 sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
75674 for(i=0; i<nCol; i++){
75675 sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
75678 /* Start the analysis loop. This loop runs through all the entries in
75679 ** the index b-tree. */
75680 endOfLoop = sqlite3VdbeMakeLabel(v);
75681 sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
75682 topOfLoop = sqlite3VdbeCurrentAddr(v);
75683 sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
75685 for(i=0; i<nCol; i++){
75686 CollSeq *pColl;
75687 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
75688 if( i==0 ){
75689 #ifdef SQLITE_ENABLE_STAT2
75690 /* Check if the record that cursor iIdxCur points to contains a
75691 ** value that should be stored in the sqlite_stat2 table. If so,
75692 ** store it. */
75693 int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
75694 assert( regTabname+1==regIdxname
75695 && regTabname+2==regSampleno
75696 && regTabname+3==regCol
75698 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
75699 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
75700 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
75701 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
75703 /* Calculate new values for regSamplerecno and regSampleno.
75705 ** sampleno = sampleno + 1
75706 ** samplerecno = samplerecno+(remaining records)/(remaining samples)
75708 sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
75709 sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
75710 sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
75711 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
75712 sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
75713 sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
75714 sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
75716 sqlite3VdbeJumpHere(v, ne);
75717 sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
75718 #endif
75720 /* Always record the very first row */
75721 sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
75723 assert( pIdx->azColl!=0 );
75724 assert( pIdx->azColl[i]!=0 );
75725 pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
75726 sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
75727 (char*)pColl, P4_COLLSEQ);
75728 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
75730 if( db->mallocFailed ){
75731 /* If a malloc failure has occurred, then the result of the expression
75732 ** passed as the second argument to the call to sqlite3VdbeJumpHere()
75733 ** below may be negative. Which causes an assert() to fail (or an
75734 ** out-of-bounds write if SQLITE_DEBUG is not defined). */
75735 return;
75737 sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
75738 for(i=0; i<nCol; i++){
75739 int addr2 = sqlite3VdbeCurrentAddr(v) - (nCol*2);
75740 if( i==0 ){
75741 sqlite3VdbeJumpHere(v, addr2-1); /* Set jump dest for the OP_IfNot */
75743 sqlite3VdbeJumpHere(v, addr2); /* Set jump dest for the OP_Ne */
75744 sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
75745 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
75748 /* End of the analysis loop. */
75749 sqlite3VdbeResolveLabel(v, endOfLoop);
75750 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
75751 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
75753 /* Store the results in sqlite_stat1.
75755 ** The result is a single row of the sqlite_stat1 table. The first
75756 ** two columns are the names of the table and index. The third column
75757 ** is a string composed of a list of integer statistics about the
75758 ** index. The first integer in the list is the total number of entries
75759 ** in the index. There is one additional integer in the list for each
75760 ** column of the table. This additional integer is a guess of how many
75761 ** rows of the table the index will select. If D is the count of distinct
75762 ** values and K is the total number of rows, then the integer is computed
75763 ** as:
75765 ** I = (K+D-1)/D
75767 ** If K==0 then no entry is made into the sqlite_stat1 table.
75768 ** If K>0 then it is always the case the D>0 so division by zero
75769 ** is never possible.
75771 sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
75772 if( jZeroRows<0 ){
75773 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
75775 for(i=0; i<nCol; i++){
75776 sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
75777 sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
75778 sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
75779 sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
75780 sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
75781 sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
75782 sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
75784 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
75785 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
75786 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
75787 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75790 /* If the table has no indices, create a single sqlite_stat1 entry
75791 ** containing NULL as the index name and the row count as the content.
75793 if( pTab->pIndex==0 ){
75794 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
75795 VdbeComment((v, "%s", pTab->zName));
75796 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
75797 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
75798 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regSampleno);
75799 }else{
75800 sqlite3VdbeJumpHere(v, jZeroRows);
75801 jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
75803 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
75804 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
75805 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
75806 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
75807 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75808 if( pParse->nMem<regRec ) pParse->nMem = regRec;
75809 sqlite3VdbeJumpHere(v, jZeroRows);
75813 ** Generate code that will cause the most recent index analysis to
75814 ** be loaded into internal hash tables where is can be used.
75816 static void loadAnalysis(Parse *pParse, int iDb){
75817 Vdbe *v = sqlite3GetVdbe(pParse);
75818 if( v ){
75819 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
75824 ** Generate code that will do an analysis of an entire database
75826 static void analyzeDatabase(Parse *pParse, int iDb){
75827 sqlite3 *db = pParse->db;
75828 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
75829 HashElem *k;
75830 int iStatCur;
75831 int iMem;
75833 sqlite3BeginWriteOperation(pParse, 0, iDb);
75834 iStatCur = pParse->nTab;
75835 pParse->nTab += 2;
75836 openStatTable(pParse, iDb, iStatCur, 0, 0);
75837 iMem = pParse->nMem+1;
75838 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75839 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
75840 Table *pTab = (Table*)sqliteHashData(k);
75841 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
75843 loadAnalysis(pParse, iDb);
75847 ** Generate code that will do an analysis of a single table in
75848 ** a database. If pOnlyIdx is not NULL then it is a single index
75849 ** in pTab that should be analyzed.
75851 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
75852 int iDb;
75853 int iStatCur;
75855 assert( pTab!=0 );
75856 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75857 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75858 sqlite3BeginWriteOperation(pParse, 0, iDb);
75859 iStatCur = pParse->nTab;
75860 pParse->nTab += 2;
75861 if( pOnlyIdx ){
75862 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
75863 }else{
75864 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
75866 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
75867 loadAnalysis(pParse, iDb);
75871 ** Generate code for the ANALYZE command. The parser calls this routine
75872 ** when it recognizes an ANALYZE command.
75874 ** ANALYZE -- 1
75875 ** ANALYZE <database> -- 2
75876 ** ANALYZE ?<database>.?<tablename> -- 3
75878 ** Form 1 causes all indices in all attached databases to be analyzed.
75879 ** Form 2 analyzes all indices the single database named.
75880 ** Form 3 analyzes all indices associated with the named table.
75882 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
75883 sqlite3 *db = pParse->db;
75884 int iDb;
75885 int i;
75886 char *z, *zDb;
75887 Table *pTab;
75888 Index *pIdx;
75889 Token *pTableName;
75891 /* Read the database schema. If an error occurs, leave an error message
75892 ** and code in pParse and return NULL. */
75893 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75894 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75895 return;
75898 assert( pName2!=0 || pName1==0 );
75899 if( pName1==0 ){
75900 /* Form 1: Analyze everything */
75901 for(i=0; i<db->nDb; i++){
75902 if( i==1 ) continue; /* Do not analyze the TEMP database */
75903 analyzeDatabase(pParse, i);
75905 }else if( pName2->n==0 ){
75906 /* Form 2: Analyze the database or table named */
75907 iDb = sqlite3FindDb(db, pName1);
75908 if( iDb>=0 ){
75909 analyzeDatabase(pParse, iDb);
75910 }else{
75911 z = sqlite3NameFromToken(db, pName1);
75912 if( z ){
75913 if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
75914 analyzeTable(pParse, pIdx->pTable, pIdx);
75915 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
75916 analyzeTable(pParse, pTab, 0);
75918 sqlite3DbFree(db, z);
75921 }else{
75922 /* Form 3: Analyze the fully qualified table name */
75923 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
75924 if( iDb>=0 ){
75925 zDb = db->aDb[iDb].zName;
75926 z = sqlite3NameFromToken(db, pTableName);
75927 if( z ){
75928 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
75929 analyzeTable(pParse, pIdx->pTable, pIdx);
75930 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
75931 analyzeTable(pParse, pTab, 0);
75933 sqlite3DbFree(db, z);
75940 ** Used to pass information from the analyzer reader through to the
75941 ** callback routine.
75943 typedef struct analysisInfo analysisInfo;
75944 struct analysisInfo {
75945 sqlite3 *db;
75946 const char *zDatabase;
75950 ** This callback is invoked once for each index when reading the
75951 ** sqlite_stat1 table.
75953 ** argv[0] = name of the table
75954 ** argv[1] = name of the index (might be NULL)
75955 ** argv[2] = results of analysis - on integer for each column
75957 ** Entries for which argv[1]==NULL simply record the number of rows in
75958 ** the table.
75960 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
75961 analysisInfo *pInfo = (analysisInfo*)pData;
75962 Index *pIndex;
75963 Table *pTable;
75964 int i, c, n;
75965 unsigned int v;
75966 const char *z;
75968 assert( argc==3 );
75969 UNUSED_PARAMETER2(NotUsed, argc);
75971 if( argv==0 || argv[0]==0 || argv[2]==0 ){
75972 return 0;
75974 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
75975 if( pTable==0 ){
75976 return 0;
75978 if( argv[1] ){
75979 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
75980 }else{
75981 pIndex = 0;
75983 n = pIndex ? pIndex->nColumn : 0;
75984 z = argv[2];
75985 for(i=0; *z && i<=n; i++){
75986 v = 0;
75987 while( (c=z[0])>='0' && c<='9' ){
75988 v = v*10 + c - '0';
75989 z++;
75991 if( i==0 ) pTable->nRowEst = v;
75992 if( pIndex==0 ) break;
75993 pIndex->aiRowEst[i] = v;
75994 if( *z==' ' ) z++;
75995 if( memcmp(z, "unordered", 10)==0 ){
75996 pIndex->bUnordered = 1;
75997 break;
76000 return 0;
76004 ** If the Index.aSample variable is not NULL, delete the aSample[] array
76005 ** and its contents.
76007 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
76008 #ifdef SQLITE_ENABLE_STAT2
76009 if( pIdx->aSample ){
76010 int j;
76011 for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
76012 IndexSample *p = &pIdx->aSample[j];
76013 if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
76014 sqlite3DbFree(db, p->u.z);
76017 sqlite3DbFree(db, pIdx->aSample);
76019 #else
76020 UNUSED_PARAMETER(db);
76021 UNUSED_PARAMETER(pIdx);
76022 #endif
76026 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
76027 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
76028 ** arrays. The contents of sqlite_stat2 are used to populate the
76029 ** Index.aSample[] arrays.
76031 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
76032 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
76033 ** during compilation and the sqlite_stat2 table is present, no data is
76034 ** read from it.
76036 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the
76037 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
76038 ** returned. However, in this case, data is read from the sqlite_stat1
76039 ** table (if it is present) before returning.
76041 ** If an OOM error occurs, this function always sets db->mallocFailed.
76042 ** This means if the caller does not care about other errors, the return
76043 ** code may be ignored.
76045 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
76046 analysisInfo sInfo;
76047 HashElem *i;
76048 char *zSql;
76049 int rc;
76051 assert( iDb>=0 && iDb<db->nDb );
76052 assert( db->aDb[iDb].pBt!=0 );
76054 /* Clear any prior statistics */
76055 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
76056 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
76057 Index *pIdx = sqliteHashData(i);
76058 sqlite3DefaultRowEst(pIdx);
76059 sqlite3DeleteIndexSamples(db, pIdx);
76060 pIdx->aSample = 0;
76063 /* Check to make sure the sqlite_stat1 table exists */
76064 sInfo.db = db;
76065 sInfo.zDatabase = db->aDb[iDb].zName;
76066 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
76067 return SQLITE_ERROR;
76070 /* Load new statistics out of the sqlite_stat1 table */
76071 zSql = sqlite3MPrintf(db,
76072 "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
76073 if( zSql==0 ){
76074 rc = SQLITE_NOMEM;
76075 }else{
76076 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
76077 sqlite3DbFree(db, zSql);
76081 /* Load the statistics from the sqlite_stat2 table. */
76082 #ifdef SQLITE_ENABLE_STAT2
76083 if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
76084 rc = SQLITE_ERROR;
76086 if( rc==SQLITE_OK ){
76087 sqlite3_stmt *pStmt = 0;
76089 zSql = sqlite3MPrintf(db,
76090 "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
76091 if( !zSql ){
76092 rc = SQLITE_NOMEM;
76093 }else{
76094 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
76095 sqlite3DbFree(db, zSql);
76098 if( rc==SQLITE_OK ){
76099 while( sqlite3_step(pStmt)==SQLITE_ROW ){
76100 char *zIndex; /* Index name */
76101 Index *pIdx; /* Pointer to the index object */
76103 zIndex = (char *)sqlite3_column_text(pStmt, 0);
76104 pIdx = zIndex ? sqlite3FindIndex(db, zIndex, sInfo.zDatabase) : 0;
76105 if( pIdx ){
76106 int iSample = sqlite3_column_int(pStmt, 1);
76107 if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
76108 int eType = sqlite3_column_type(pStmt, 2);
76110 if( pIdx->aSample==0 ){
76111 static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
76112 pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
76113 if( pIdx->aSample==0 ){
76114 db->mallocFailed = 1;
76115 break;
76117 memset(pIdx->aSample, 0, sz);
76120 assert( pIdx->aSample );
76122 IndexSample *pSample = &pIdx->aSample[iSample];
76123 pSample->eType = (u8)eType;
76124 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
76125 pSample->u.r = sqlite3_column_double(pStmt, 2);
76126 }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
76127 const char *z = (const char *)(
76128 (eType==SQLITE_BLOB) ?
76129 sqlite3_column_blob(pStmt, 2):
76130 sqlite3_column_text(pStmt, 2)
76132 int n = sqlite3_column_bytes(pStmt, 2);
76133 if( n>24 ){
76134 n = 24;
76136 pSample->nByte = (u8)n;
76137 if( n < 1){
76138 pSample->u.z = 0;
76139 }else{
76140 pSample->u.z = sqlite3DbStrNDup(0, z, n);
76141 if( pSample->u.z==0 ){
76142 db->mallocFailed = 1;
76143 break;
76151 rc = sqlite3_finalize(pStmt);
76154 #endif
76156 if( rc==SQLITE_NOMEM ){
76157 db->mallocFailed = 1;
76159 return rc;
76163 #endif /* SQLITE_OMIT_ANALYZE */
76165 /************** End of analyze.c *********************************************/
76166 /************** Begin file attach.c ******************************************/
76168 ** 2003 April 6
76170 ** The author disclaims copyright to this source code. In place of
76171 ** a legal notice, here is a blessing:
76173 ** May you do good and not evil.
76174 ** May you find forgiveness for yourself and forgive others.
76175 ** May you share freely, never taking more than you give.
76177 *************************************************************************
76178 ** This file contains code used to implement the ATTACH and DETACH commands.
76181 #ifndef SQLITE_OMIT_ATTACH
76183 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
76184 ** is slightly different from resolving a normal SQL expression, because simple
76185 ** identifiers are treated as strings, not possible column names or aliases.
76187 ** i.e. if the parser sees:
76189 ** ATTACH DATABASE abc AS def
76191 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
76192 ** looking for columns of the same name.
76194 ** This only applies to the root node of pExpr, so the statement:
76196 ** ATTACH DATABASE abc||def AS 'db2'
76198 ** will fail because neither abc or def can be resolved.
76200 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
76202 int rc = SQLITE_OK;
76203 if( pExpr ){
76204 if( pExpr->op!=TK_ID ){
76205 rc = sqlite3ResolveExprNames(pName, pExpr);
76206 if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
76207 sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
76208 return SQLITE_ERROR;
76210 }else{
76211 pExpr->op = TK_STRING;
76214 return rc;
76218 ** An SQL user-function registered to do the work of an ATTACH statement. The
76219 ** three arguments to the function come directly from an attach statement:
76221 ** ATTACH DATABASE x AS y KEY z
76223 ** SELECT sqlite_attach(x, y, z)
76225 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
76226 ** third argument.
76228 static void attachFunc(
76229 sqlite3_context *context,
76230 int NotUsed,
76231 sqlite3_value **argv
76233 int i;
76234 int rc = 0;
76235 sqlite3 *db = sqlite3_context_db_handle(context);
76236 const char *zName;
76237 const char *zFile;
76238 Db *aNew;
76239 char *zErrDyn = 0;
76241 UNUSED_PARAMETER(NotUsed);
76243 zFile = (const char *)sqlite3_value_text(argv[0]);
76244 zName = (const char *)sqlite3_value_text(argv[1]);
76245 if( zFile==0 ) zFile = "";
76246 if( zName==0 ) zName = "";
76248 /* Check for the following errors:
76250 ** * Too many attached databases,
76251 ** * Transaction currently open
76252 ** * Specified database name already being used.
76254 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
76255 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
76256 db->aLimit[SQLITE_LIMIT_ATTACHED]
76258 goto attach_error;
76260 if( !db->autoCommit ){
76261 zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
76262 goto attach_error;
76264 for(i=0; i<db->nDb; i++){
76265 char *z = db->aDb[i].zName;
76266 assert( z && zName );
76267 if( sqlite3StrICmp(z, zName)==0 ){
76268 zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
76269 goto attach_error;
76273 /* Allocate the new entry in the db->aDb[] array and initialise the schema
76274 ** hash tables.
76276 if( db->aDb==db->aDbStatic ){
76277 aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
76278 if( aNew==0 ) return;
76279 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
76280 }else{
76281 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
76282 if( aNew==0 ) return;
76284 db->aDb = aNew;
76285 aNew = &db->aDb[db->nDb];
76286 memset(aNew, 0, sizeof(*aNew));
76288 /* Open the database file. If the btree is successfully opened, use
76289 ** it to obtain the database schema. At this point the schema may
76290 ** or may not be initialised.
76292 rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
76293 db->openFlags | SQLITE_OPEN_MAIN_DB);
76294 db->nDb++;
76295 if( rc==SQLITE_CONSTRAINT ){
76296 rc = SQLITE_ERROR;
76297 zErrDyn = sqlite3MPrintf(db, "database is already attached");
76298 }else if( rc==SQLITE_OK ){
76299 Pager *pPager;
76300 aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
76301 if( !aNew->pSchema ){
76302 rc = SQLITE_NOMEM;
76303 }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
76304 zErrDyn = sqlite3MPrintf(db,
76305 "attached databases must use the same text encoding as main database");
76306 rc = SQLITE_ERROR;
76308 pPager = sqlite3BtreePager(aNew->pBt);
76309 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
76310 sqlite3BtreeSecureDelete(aNew->pBt,
76311 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
76313 aNew->safety_level = 3;
76314 aNew->zName = sqlite3DbStrDup(db, zName);
76315 if( rc==SQLITE_OK && aNew->zName==0 ){
76316 rc = SQLITE_NOMEM;
76320 #ifdef SQLITE_HAS_CODEC
76321 if( rc==SQLITE_OK ){
76322 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
76323 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
76324 int nKey;
76325 char *zKey;
76326 int t = sqlite3_value_type(argv[2]);
76327 switch( t ){
76328 case SQLITE_INTEGER:
76329 case SQLITE_FLOAT:
76330 zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
76331 rc = SQLITE_ERROR;
76332 break;
76334 case SQLITE_TEXT:
76335 case SQLITE_BLOB:
76336 nKey = sqlite3_value_bytes(argv[2]);
76337 zKey = (char *)sqlite3_value_blob(argv[2]);
76338 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76339 break;
76341 case SQLITE_NULL:
76342 /* No key specified. Use the key from the main database */
76343 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
76344 if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
76345 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76347 break;
76350 #endif
76352 /* If the file was opened successfully, read the schema for the new database.
76353 ** If this fails, or if opening the file failed, then close the file and
76354 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
76355 ** we found it.
76357 if( rc==SQLITE_OK ){
76358 sqlite3BtreeEnterAll(db);
76359 rc = sqlite3Init(db, &zErrDyn);
76360 sqlite3BtreeLeaveAll(db);
76362 if( rc ){
76363 int iDb = db->nDb - 1;
76364 assert( iDb>=2 );
76365 if( db->aDb[iDb].pBt ){
76366 sqlite3BtreeClose(db->aDb[iDb].pBt);
76367 db->aDb[iDb].pBt = 0;
76368 db->aDb[iDb].pSchema = 0;
76370 sqlite3ResetInternalSchema(db, -1);
76371 db->nDb = iDb;
76372 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
76373 db->mallocFailed = 1;
76374 sqlite3DbFree(db, zErrDyn);
76375 zErrDyn = sqlite3MPrintf(db, "out of memory");
76376 }else if( zErrDyn==0 ){
76377 zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
76379 goto attach_error;
76382 return;
76384 attach_error:
76385 /* Return an error if we get here */
76386 if( zErrDyn ){
76387 sqlite3_result_error(context, zErrDyn, -1);
76388 sqlite3DbFree(db, zErrDyn);
76390 if( rc ) sqlite3_result_error_code(context, rc);
76394 ** An SQL user-function registered to do the work of an DETACH statement. The
76395 ** three arguments to the function come directly from a detach statement:
76397 ** DETACH DATABASE x
76399 ** SELECT sqlite_detach(x)
76401 static void detachFunc(
76402 sqlite3_context *context,
76403 int NotUsed,
76404 sqlite3_value **argv
76406 const char *zName = (const char *)sqlite3_value_text(argv[0]);
76407 sqlite3 *db = sqlite3_context_db_handle(context);
76408 int i;
76409 Db *pDb = 0;
76410 char zErr[128];
76412 UNUSED_PARAMETER(NotUsed);
76414 if( zName==0 ) zName = "";
76415 for(i=0; i<db->nDb; i++){
76416 pDb = &db->aDb[i];
76417 if( pDb->pBt==0 ) continue;
76418 if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
76421 if( i>=db->nDb ){
76422 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
76423 goto detach_error;
76425 if( i<2 ){
76426 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
76427 goto detach_error;
76429 if( !db->autoCommit ){
76430 sqlite3_snprintf(sizeof(zErr), zErr,
76431 "cannot DETACH database within transaction");
76432 goto detach_error;
76434 if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
76435 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
76436 goto detach_error;
76439 sqlite3BtreeClose(pDb->pBt);
76440 pDb->pBt = 0;
76441 pDb->pSchema = 0;
76442 sqlite3ResetInternalSchema(db, -1);
76443 return;
76445 detach_error:
76446 sqlite3_result_error(context, zErr, -1);
76450 ** This procedure generates VDBE code for a single invocation of either the
76451 ** sqlite_detach() or sqlite_attach() SQL user functions.
76453 static void codeAttach(
76454 Parse *pParse, /* The parser context */
76455 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
76456 FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
76457 Expr *pAuthArg, /* Expression to pass to authorization callback */
76458 Expr *pFilename, /* Name of database file */
76459 Expr *pDbname, /* Name of the database to use internally */
76460 Expr *pKey /* Database key for encryption extension */
76462 int rc;
76463 NameContext sName;
76464 Vdbe *v;
76465 sqlite3* db = pParse->db;
76466 int regArgs;
76468 memset(&sName, 0, sizeof(NameContext));
76469 sName.pParse = pParse;
76471 if(
76472 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
76473 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
76474 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
76476 pParse->nErr++;
76477 goto attach_end;
76480 #ifndef SQLITE_OMIT_AUTHORIZATION
76481 if( pAuthArg ){
76482 char *zAuthArg;
76483 if( pAuthArg->op==TK_STRING ){
76484 zAuthArg = pAuthArg->u.zToken;
76485 }else{
76486 zAuthArg = 0;
76488 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
76489 if(rc!=SQLITE_OK ){
76490 goto attach_end;
76493 #endif /* SQLITE_OMIT_AUTHORIZATION */
76496 v = sqlite3GetVdbe(pParse);
76497 regArgs = sqlite3GetTempRange(pParse, 4);
76498 sqlite3ExprCode(pParse, pFilename, regArgs);
76499 sqlite3ExprCode(pParse, pDbname, regArgs+1);
76500 sqlite3ExprCode(pParse, pKey, regArgs+2);
76502 assert( v || db->mallocFailed );
76503 if( v ){
76504 sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
76505 assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
76506 sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
76507 sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
76509 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
76510 ** statement only). For DETACH, set it to false (expire all existing
76511 ** statements).
76513 sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
76516 attach_end:
76517 sqlite3ExprDelete(db, pFilename);
76518 sqlite3ExprDelete(db, pDbname);
76519 sqlite3ExprDelete(db, pKey);
76523 ** Called by the parser to compile a DETACH statement.
76525 ** DETACH pDbname
76527 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
76528 static const FuncDef detach_func = {
76529 1, /* nArg */
76530 SQLITE_UTF8, /* iPrefEnc */
76531 0, /* flags */
76532 0, /* pUserData */
76533 0, /* pNext */
76534 detachFunc, /* xFunc */
76535 0, /* xStep */
76536 0, /* xFinalize */
76537 "sqlite_detach", /* zName */
76538 0, /* pHash */
76539 0 /* pDestructor */
76541 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
76545 ** Called by the parser to compile an ATTACH statement.
76547 ** ATTACH p AS pDbname KEY pKey
76549 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
76550 static const FuncDef attach_func = {
76551 3, /* nArg */
76552 SQLITE_UTF8, /* iPrefEnc */
76553 0, /* flags */
76554 0, /* pUserData */
76555 0, /* pNext */
76556 attachFunc, /* xFunc */
76557 0, /* xStep */
76558 0, /* xFinalize */
76559 "sqlite_attach", /* zName */
76560 0, /* pHash */
76561 0 /* pDestructor */
76563 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
76565 #endif /* SQLITE_OMIT_ATTACH */
76568 ** Initialize a DbFixer structure. This routine must be called prior
76569 ** to passing the structure to one of the sqliteFixAAAA() routines below.
76571 ** The return value indicates whether or not fixation is required. TRUE
76572 ** means we do need to fix the database references, FALSE means we do not.
76574 SQLITE_PRIVATE int sqlite3FixInit(
76575 DbFixer *pFix, /* The fixer to be initialized */
76576 Parse *pParse, /* Error messages will be written here */
76577 int iDb, /* This is the database that must be used */
76578 const char *zType, /* "view", "trigger", or "index" */
76579 const Token *pName /* Name of the view, trigger, or index */
76581 sqlite3 *db;
76583 if( NEVER(iDb<0) || iDb==1 ) return 0;
76584 db = pParse->db;
76585 assert( db->nDb>iDb );
76586 pFix->pParse = pParse;
76587 pFix->zDb = db->aDb[iDb].zName;
76588 pFix->zType = zType;
76589 pFix->pName = pName;
76590 return 1;
76594 ** The following set of routines walk through the parse tree and assign
76595 ** a specific database to all table references where the database name
76596 ** was left unspecified in the original SQL statement. The pFix structure
76597 ** must have been initialized by a prior call to sqlite3FixInit().
76599 ** These routines are used to make sure that an index, trigger, or
76600 ** view in one database does not refer to objects in a different database.
76601 ** (Exception: indices, triggers, and views in the TEMP database are
76602 ** allowed to refer to anything.) If a reference is explicitly made
76603 ** to an object in a different database, an error message is added to
76604 ** pParse->zErrMsg and these routines return non-zero. If everything
76605 ** checks out, these routines return 0.
76607 SQLITE_PRIVATE int sqlite3FixSrcList(
76608 DbFixer *pFix, /* Context of the fixation */
76609 SrcList *pList /* The Source list to check and modify */
76611 int i;
76612 const char *zDb;
76613 struct SrcList_item *pItem;
76615 if( NEVER(pList==0) ) return 0;
76616 zDb = pFix->zDb;
76617 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
76618 if( pItem->zDatabase==0 ){
76619 pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
76620 }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
76621 sqlite3ErrorMsg(pFix->pParse,
76622 "%s %T cannot reference objects in database %s",
76623 pFix->zType, pFix->pName, pItem->zDatabase);
76624 return 1;
76626 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
76627 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
76628 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
76629 #endif
76631 return 0;
76633 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
76634 SQLITE_PRIVATE int sqlite3FixSelect(
76635 DbFixer *pFix, /* Context of the fixation */
76636 Select *pSelect /* The SELECT statement to be fixed to one database */
76638 while( pSelect ){
76639 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
76640 return 1;
76642 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
76643 return 1;
76645 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
76646 return 1;
76648 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
76649 return 1;
76651 pSelect = pSelect->pPrior;
76653 return 0;
76655 SQLITE_PRIVATE int sqlite3FixExpr(
76656 DbFixer *pFix, /* Context of the fixation */
76657 Expr *pExpr /* The expression to be fixed to one database */
76659 while( pExpr ){
76660 if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
76661 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76662 if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
76663 }else{
76664 if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
76666 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
76667 return 1;
76669 pExpr = pExpr->pLeft;
76671 return 0;
76673 SQLITE_PRIVATE int sqlite3FixExprList(
76674 DbFixer *pFix, /* Context of the fixation */
76675 ExprList *pList /* The expression to be fixed to one database */
76677 int i;
76678 struct ExprList_item *pItem;
76679 if( pList==0 ) return 0;
76680 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
76681 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
76682 return 1;
76685 return 0;
76687 #endif
76689 #ifndef SQLITE_OMIT_TRIGGER
76690 SQLITE_PRIVATE int sqlite3FixTriggerStep(
76691 DbFixer *pFix, /* Context of the fixation */
76692 TriggerStep *pStep /* The trigger step be fixed to one database */
76694 while( pStep ){
76695 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
76696 return 1;
76698 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
76699 return 1;
76701 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
76702 return 1;
76704 pStep = pStep->pNext;
76706 return 0;
76708 #endif
76710 /************** End of attach.c **********************************************/
76711 /************** Begin file auth.c ********************************************/
76713 ** 2003 January 11
76715 ** The author disclaims copyright to this source code. In place of
76716 ** a legal notice, here is a blessing:
76718 ** May you do good and not evil.
76719 ** May you find forgiveness for yourself and forgive others.
76720 ** May you share freely, never taking more than you give.
76722 *************************************************************************
76723 ** This file contains code used to implement the sqlite3_set_authorizer()
76724 ** API. This facility is an optional feature of the library. Embedded
76725 ** systems that do not need this facility may omit it by recompiling
76726 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
76730 ** All of the code in this file may be omitted by defining a single
76731 ** macro.
76733 #ifndef SQLITE_OMIT_AUTHORIZATION
76736 ** Set or clear the access authorization function.
76738 ** The access authorization function is be called during the compilation
76739 ** phase to verify that the user has read and/or write access permission on
76740 ** various fields of the database. The first argument to the auth function
76741 ** is a copy of the 3rd argument to this routine. The second argument
76742 ** to the auth function is one of these constants:
76744 ** SQLITE_CREATE_INDEX
76745 ** SQLITE_CREATE_TABLE
76746 ** SQLITE_CREATE_TEMP_INDEX
76747 ** SQLITE_CREATE_TEMP_TABLE
76748 ** SQLITE_CREATE_TEMP_TRIGGER
76749 ** SQLITE_CREATE_TEMP_VIEW
76750 ** SQLITE_CREATE_TRIGGER
76751 ** SQLITE_CREATE_VIEW
76752 ** SQLITE_DELETE
76753 ** SQLITE_DROP_INDEX
76754 ** SQLITE_DROP_TABLE
76755 ** SQLITE_DROP_TEMP_INDEX
76756 ** SQLITE_DROP_TEMP_TABLE
76757 ** SQLITE_DROP_TEMP_TRIGGER
76758 ** SQLITE_DROP_TEMP_VIEW
76759 ** SQLITE_DROP_TRIGGER
76760 ** SQLITE_DROP_VIEW
76761 ** SQLITE_INSERT
76762 ** SQLITE_PRAGMA
76763 ** SQLITE_READ
76764 ** SQLITE_SELECT
76765 ** SQLITE_TRANSACTION
76766 ** SQLITE_UPDATE
76768 ** The third and fourth arguments to the auth function are the name of
76769 ** the table and the column that are being accessed. The auth function
76770 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
76771 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
76772 ** means that the SQL statement will never-run - the sqlite3_exec() call
76773 ** will return with an error. SQLITE_IGNORE means that the SQL statement
76774 ** should run but attempts to read the specified column will return NULL
76775 ** and attempts to write the column will be ignored.
76777 ** Setting the auth function to NULL disables this hook. The default
76778 ** setting of the auth function is NULL.
76780 SQLITE_API int sqlite3_set_authorizer(
76781 sqlite3 *db,
76782 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
76783 void *pArg
76785 sqlite3_mutex_enter(db->mutex);
76786 db->xAuth = xAuth;
76787 db->pAuthArg = pArg;
76788 sqlite3ExpirePreparedStatements(db);
76789 sqlite3_mutex_leave(db->mutex);
76790 return SQLITE_OK;
76794 ** Write an error message into pParse->zErrMsg that explains that the
76795 ** user-supplied authorization function returned an illegal value.
76797 static void sqliteAuthBadReturnCode(Parse *pParse){
76798 sqlite3ErrorMsg(pParse, "authorizer malfunction");
76799 pParse->rc = SQLITE_ERROR;
76803 ** Invoke the authorization callback for permission to read column zCol from
76804 ** table zTab in database zDb. This function assumes that an authorization
76805 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
76807 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
76808 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
76809 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
76811 SQLITE_PRIVATE int sqlite3AuthReadCol(
76812 Parse *pParse, /* The parser context */
76813 const char *zTab, /* Table name */
76814 const char *zCol, /* Column name */
76815 int iDb /* Index of containing database. */
76817 sqlite3 *db = pParse->db; /* Database handle */
76818 char *zDb = db->aDb[iDb].zName; /* Name of attached database */
76819 int rc; /* Auth callback return code */
76821 rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
76822 if( rc==SQLITE_DENY ){
76823 if( db->nDb>2 || iDb!=0 ){
76824 sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
76825 }else{
76826 sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
76828 pParse->rc = SQLITE_AUTH;
76829 }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
76830 sqliteAuthBadReturnCode(pParse);
76832 return rc;
76836 ** The pExpr should be a TK_COLUMN expression. The table referred to
76837 ** is in pTabList or else it is the NEW or OLD table of a trigger.
76838 ** Check to see if it is OK to read this particular column.
76840 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
76841 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
76842 ** then generate an error.
76844 SQLITE_PRIVATE void sqlite3AuthRead(
76845 Parse *pParse, /* The parser context */
76846 Expr *pExpr, /* The expression to check authorization on */
76847 Schema *pSchema, /* The schema of the expression */
76848 SrcList *pTabList /* All table that pExpr might refer to */
76850 sqlite3 *db = pParse->db;
76851 Table *pTab = 0; /* The table being read */
76852 const char *zCol; /* Name of the column of the table */
76853 int iSrc; /* Index in pTabList->a[] of table being read */
76854 int iDb; /* The index of the database the expression refers to */
76855 int iCol; /* Index of column in table */
76857 if( db->xAuth==0 ) return;
76858 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
76859 if( iDb<0 ){
76860 /* An attempt to read a column out of a subquery or other
76861 ** temporary table. */
76862 return;
76865 assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
76866 if( pExpr->op==TK_TRIGGER ){
76867 pTab = pParse->pTriggerTab;
76868 }else{
76869 assert( pTabList );
76870 for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
76871 if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
76872 pTab = pTabList->a[iSrc].pTab;
76873 break;
76877 iCol = pExpr->iColumn;
76878 if( NEVER(pTab==0) ) return;
76880 if( iCol>=0 ){
76881 assert( iCol<pTab->nCol );
76882 zCol = pTab->aCol[iCol].zName;
76883 }else if( pTab->iPKey>=0 ){
76884 assert( pTab->iPKey<pTab->nCol );
76885 zCol = pTab->aCol[pTab->iPKey].zName;
76886 }else{
76887 zCol = "ROWID";
76889 assert( iDb>=0 && iDb<db->nDb );
76890 if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
76891 pExpr->op = TK_NULL;
76896 ** Do an authorization check using the code and arguments given. Return
76897 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
76898 ** is returned, then the error count and error message in pParse are
76899 ** modified appropriately.
76901 SQLITE_PRIVATE int sqlite3AuthCheck(
76902 Parse *pParse,
76903 int code,
76904 const char *zArg1,
76905 const char *zArg2,
76906 const char *zArg3
76908 sqlite3 *db = pParse->db;
76909 int rc;
76911 /* Don't do any authorization checks if the database is initialising
76912 ** or if the parser is being invoked from within sqlite3_declare_vtab.
76914 if( db->init.busy || IN_DECLARE_VTAB ){
76915 return SQLITE_OK;
76918 if( db->xAuth==0 ){
76919 return SQLITE_OK;
76921 rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
76922 if( rc==SQLITE_DENY ){
76923 sqlite3ErrorMsg(pParse, "not authorized");
76924 pParse->rc = SQLITE_AUTH;
76925 }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
76926 rc = SQLITE_DENY;
76927 sqliteAuthBadReturnCode(pParse);
76929 return rc;
76933 ** Push an authorization context. After this routine is called, the
76934 ** zArg3 argument to authorization callbacks will be zContext until
76935 ** popped. Or if pParse==0, this routine is a no-op.
76937 SQLITE_PRIVATE void sqlite3AuthContextPush(
76938 Parse *pParse,
76939 AuthContext *pContext,
76940 const char *zContext
76942 assert( pParse );
76943 pContext->pParse = pParse;
76944 pContext->zAuthContext = pParse->zAuthContext;
76945 pParse->zAuthContext = zContext;
76949 ** Pop an authorization context that was previously pushed
76950 ** by sqlite3AuthContextPush
76952 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
76953 if( pContext->pParse ){
76954 pContext->pParse->zAuthContext = pContext->zAuthContext;
76955 pContext->pParse = 0;
76959 #endif /* SQLITE_OMIT_AUTHORIZATION */
76961 /************** End of auth.c ************************************************/
76962 /************** Begin file build.c *******************************************/
76964 ** 2001 September 15
76966 ** The author disclaims copyright to this source code. In place of
76967 ** a legal notice, here is a blessing:
76969 ** May you do good and not evil.
76970 ** May you find forgiveness for yourself and forgive others.
76971 ** May you share freely, never taking more than you give.
76973 *************************************************************************
76974 ** This file contains C code routines that are called by the SQLite parser
76975 ** when syntax rules are reduced. The routines in this file handle the
76976 ** following kinds of SQL syntax:
76978 ** CREATE TABLE
76979 ** DROP TABLE
76980 ** CREATE INDEX
76981 ** DROP INDEX
76982 ** creating ID lists
76983 ** BEGIN TRANSACTION
76984 ** COMMIT
76985 ** ROLLBACK
76990 ** This routine is called when a new SQL statement is beginning to
76991 ** be parsed. Initialize the pParse structure as needed.
76993 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
76994 pParse->explain = (u8)explainFlag;
76995 pParse->nVar = 0;
76998 #ifndef SQLITE_OMIT_SHARED_CACHE
77000 ** The TableLock structure is only used by the sqlite3TableLock() and
77001 ** codeTableLocks() functions.
77003 struct TableLock {
77004 int iDb; /* The database containing the table to be locked */
77005 int iTab; /* The root page of the table to be locked */
77006 u8 isWriteLock; /* True for write lock. False for a read lock */
77007 const char *zName; /* Name of the table */
77011 ** Record the fact that we want to lock a table at run-time.
77013 ** The table to be locked has root page iTab and is found in database iDb.
77014 ** A read or a write lock can be taken depending on isWritelock.
77016 ** This routine just records the fact that the lock is desired. The
77017 ** code to make the lock occur is generated by a later call to
77018 ** codeTableLocks() which occurs during sqlite3FinishCoding().
77020 SQLITE_PRIVATE void sqlite3TableLock(
77021 Parse *pParse, /* Parsing context */
77022 int iDb, /* Index of the database containing the table to lock */
77023 int iTab, /* Root page number of the table to be locked */
77024 u8 isWriteLock, /* True for a write lock */
77025 const char *zName /* Name of the table to be locked */
77027 Parse *pToplevel = sqlite3ParseToplevel(pParse);
77028 int i;
77029 int nBytes;
77030 TableLock *p;
77031 assert( iDb>=0 );
77033 for(i=0; i<pToplevel->nTableLock; i++){
77034 p = &pToplevel->aTableLock[i];
77035 if( p->iDb==iDb && p->iTab==iTab ){
77036 p->isWriteLock = (p->isWriteLock || isWriteLock);
77037 return;
77041 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
77042 pToplevel->aTableLock =
77043 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
77044 if( pToplevel->aTableLock ){
77045 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
77046 p->iDb = iDb;
77047 p->iTab = iTab;
77048 p->isWriteLock = isWriteLock;
77049 p->zName = zName;
77050 }else{
77051 pToplevel->nTableLock = 0;
77052 pToplevel->db->mallocFailed = 1;
77057 ** Code an OP_TableLock instruction for each table locked by the
77058 ** statement (configured by calls to sqlite3TableLock()).
77060 static void codeTableLocks(Parse *pParse){
77061 int i;
77062 Vdbe *pVdbe;
77064 pVdbe = sqlite3GetVdbe(pParse);
77065 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
77067 for(i=0; i<pParse->nTableLock; i++){
77068 TableLock *p = &pParse->aTableLock[i];
77069 int p1 = p->iDb;
77070 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
77071 p->zName, P4_STATIC);
77074 #else
77075 #define codeTableLocks(x)
77076 #endif
77079 ** This routine is called after a single SQL statement has been
77080 ** parsed and a VDBE program to execute that statement has been
77081 ** prepared. This routine puts the finishing touches on the
77082 ** VDBE program and resets the pParse structure for the next
77083 ** parse.
77085 ** Note that if an error occurred, it might be the case that
77086 ** no VDBE code was generated.
77088 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
77089 sqlite3 *db;
77090 Vdbe *v;
77092 db = pParse->db;
77093 if( db->mallocFailed ) return;
77094 if( pParse->nested ) return;
77095 if( pParse->nErr ) return;
77097 /* Begin by generating some termination code at the end of the
77098 ** vdbe program
77100 v = sqlite3GetVdbe(pParse);
77101 assert( !pParse->isMultiWrite
77102 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
77103 if( v ){
77104 sqlite3VdbeAddOp0(v, OP_Halt);
77106 /* The cookie mask contains one bit for each database file open.
77107 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
77108 ** set for each database that is used. Generate code to start a
77109 ** transaction on each used database and to verify the schema cookie
77110 ** on each used database.
77112 if( pParse->cookieGoto>0 ){
77113 yDbMask mask;
77114 int iDb;
77115 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
77116 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
77117 if( (mask & pParse->cookieMask)==0 ) continue;
77118 sqlite3VdbeUsesBtree(v, iDb);
77119 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
77120 if( db->init.busy==0 ){
77121 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77122 sqlite3VdbeAddOp3(v, OP_VerifyCookie,
77123 iDb, pParse->cookieValue[iDb],
77124 db->aDb[iDb].pSchema->iGeneration);
77127 #ifndef SQLITE_OMIT_VIRTUALTABLE
77129 int i;
77130 for(i=0; i<pParse->nVtabLock; i++){
77131 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
77132 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
77134 pParse->nVtabLock = 0;
77136 #endif
77138 /* Once all the cookies have been verified and transactions opened,
77139 ** obtain the required table-locks. This is a no-op unless the
77140 ** shared-cache feature is enabled.
77142 codeTableLocks(pParse);
77144 /* Initialize any AUTOINCREMENT data structures required.
77146 sqlite3AutoincrementBegin(pParse);
77148 /* Finally, jump back to the beginning of the executable code. */
77149 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
77154 /* Get the VDBE program ready for execution
77156 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
77157 #ifdef SQLITE_DEBUG
77158 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
77159 sqlite3VdbeTrace(v, trace);
77160 #endif
77161 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
77162 /* A minimum of one cursor is required if autoincrement is used
77163 * See ticket [a696379c1f08866] */
77164 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
77165 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
77166 pParse->nTab, pParse->nMaxArg, pParse->explain,
77167 pParse->isMultiWrite && pParse->mayAbort);
77168 pParse->rc = SQLITE_DONE;
77169 pParse->colNamesSet = 0;
77170 }else{
77171 pParse->rc = SQLITE_ERROR;
77173 pParse->nTab = 0;
77174 pParse->nMem = 0;
77175 pParse->nSet = 0;
77176 pParse->nVar = 0;
77177 pParse->cookieMask = 0;
77178 pParse->cookieGoto = 0;
77182 ** Run the parser and code generator recursively in order to generate
77183 ** code for the SQL statement given onto the end of the pParse context
77184 ** currently under construction. When the parser is run recursively
77185 ** this way, the final OP_Halt is not appended and other initialization
77186 ** and finalization steps are omitted because those are handling by the
77187 ** outermost parser.
77189 ** Not everything is nestable. This facility is designed to permit
77190 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
77191 ** care if you decide to try to use this routine for some other purposes.
77193 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
77194 va_list ap;
77195 char *zSql;
77196 char *zErrMsg = 0;
77197 sqlite3 *db = pParse->db;
77198 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
77199 char saveBuf[SAVE_SZ];
77201 if( pParse->nErr ) return;
77202 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
77203 va_start(ap, zFormat);
77204 zSql = sqlite3VMPrintf(db, zFormat, ap);
77205 va_end(ap);
77206 if( zSql==0 ){
77207 return; /* A malloc must have failed */
77209 pParse->nested++;
77210 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
77211 memset(&pParse->nVar, 0, SAVE_SZ);
77212 sqlite3RunParser(pParse, zSql, &zErrMsg);
77213 sqlite3DbFree(db, zErrMsg);
77214 sqlite3DbFree(db, zSql);
77215 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
77216 pParse->nested--;
77220 ** Locate the in-memory structure that describes a particular database
77221 ** table given the name of that table and (optionally) the name of the
77222 ** database containing the table. Return NULL if not found.
77224 ** If zDatabase is 0, all databases are searched for the table and the
77225 ** first matching table is returned. (No checking for duplicate table
77226 ** names is done.) The search order is TEMP first, then MAIN, then any
77227 ** auxiliary databases added using the ATTACH command.
77229 ** See also sqlite3LocateTable().
77231 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
77232 Table *p = 0;
77233 int i;
77234 int nName;
77235 assert( zName!=0 );
77236 nName = sqlite3Strlen30(zName);
77237 /* All mutexes are required for schema access. Make sure we hold them. */
77238 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
77239 for(i=OMIT_TEMPDB; i<db->nDb; i++){
77240 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
77241 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
77242 assert( sqlite3SchemaMutexHeld(db, j, 0) );
77243 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
77244 if( p ) break;
77246 return p;
77250 ** Locate the in-memory structure that describes a particular database
77251 ** table given the name of that table and (optionally) the name of the
77252 ** database containing the table. Return NULL if not found. Also leave an
77253 ** error message in pParse->zErrMsg.
77255 ** The difference between this routine and sqlite3FindTable() is that this
77256 ** routine leaves an error message in pParse->zErrMsg where
77257 ** sqlite3FindTable() does not.
77259 SQLITE_PRIVATE Table *sqlite3LocateTable(
77260 Parse *pParse, /* context in which to report errors */
77261 int isView, /* True if looking for a VIEW rather than a TABLE */
77262 const char *zName, /* Name of the table we are looking for */
77263 const char *zDbase /* Name of the database. Might be NULL */
77265 Table *p;
77267 /* Read the database schema. If an error occurs, leave an error message
77268 ** and code in pParse and return NULL. */
77269 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77270 return 0;
77273 p = sqlite3FindTable(pParse->db, zName, zDbase);
77274 if( p==0 ){
77275 const char *zMsg = isView ? "no such view" : "no such table";
77276 if( zDbase ){
77277 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
77278 }else{
77279 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
77281 pParse->checkSchema = 1;
77283 return p;
77287 ** Locate the in-memory structure that describes
77288 ** a particular index given the name of that index
77289 ** and the name of the database that contains the index.
77290 ** Return NULL if not found.
77292 ** If zDatabase is 0, all databases are searched for the
77293 ** table and the first matching index is returned. (No checking
77294 ** for duplicate index names is done.) The search order is
77295 ** TEMP first, then MAIN, then any auxiliary databases added
77296 ** using the ATTACH command.
77298 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
77299 Index *p = 0;
77300 int i;
77301 int nName = sqlite3Strlen30(zName);
77302 /* All mutexes are required for schema access. Make sure we hold them. */
77303 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
77304 for(i=OMIT_TEMPDB; i<db->nDb; i++){
77305 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
77306 Schema *pSchema = db->aDb[j].pSchema;
77307 assert( pSchema );
77308 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
77309 assert( sqlite3SchemaMutexHeld(db, j, 0) );
77310 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
77311 if( p ) break;
77313 return p;
77317 ** Reclaim the memory used by an index
77319 static void freeIndex(sqlite3 *db, Index *p){
77320 #ifndef SQLITE_OMIT_ANALYZE
77321 sqlite3DeleteIndexSamples(db, p);
77322 #endif
77323 sqlite3DbFree(db, p->zColAff);
77324 sqlite3DbFree(db, p);
77328 ** For the index called zIdxName which is found in the database iDb,
77329 ** unlike that index from its Table then remove the index from
77330 ** the index hash table and free all memory structures associated
77331 ** with the index.
77333 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
77334 Index *pIndex;
77335 int len;
77336 Hash *pHash;
77338 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77339 pHash = &db->aDb[iDb].pSchema->idxHash;
77340 len = sqlite3Strlen30(zIdxName);
77341 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
77342 if( ALWAYS(pIndex) ){
77343 if( pIndex->pTable->pIndex==pIndex ){
77344 pIndex->pTable->pIndex = pIndex->pNext;
77345 }else{
77346 Index *p;
77347 /* Justification of ALWAYS(); The index must be on the list of
77348 ** indices. */
77349 p = pIndex->pTable->pIndex;
77350 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
77351 if( ALWAYS(p && p->pNext==pIndex) ){
77352 p->pNext = pIndex->pNext;
77355 freeIndex(db, pIndex);
77357 db->flags |= SQLITE_InternChanges;
77361 ** Erase all schema information from the in-memory hash tables of
77362 ** a single database. This routine is called to reclaim memory
77363 ** before the database closes. It is also called during a rollback
77364 ** if there were schema changes during the transaction or if a
77365 ** schema-cookie mismatch occurs.
77367 ** If iDb<0 then reset the internal schema tables for all database
77368 ** files. If iDb>=0 then reset the internal schema for only the
77369 ** single file indicated.
77371 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
77372 int i, j;
77373 assert( iDb<db->nDb );
77375 if( iDb>=0 ){
77376 /* Case 1: Reset the single schema identified by iDb */
77377 Db *pDb = &db->aDb[iDb];
77378 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77379 assert( pDb->pSchema!=0 );
77380 sqlite3SchemaClear(pDb->pSchema);
77382 /* If any database other than TEMP is reset, then also reset TEMP
77383 ** since TEMP might be holding triggers that reference tables in the
77384 ** other database.
77386 if( iDb!=1 ){
77387 pDb = &db->aDb[1];
77388 assert( pDb->pSchema!=0 );
77389 sqlite3SchemaClear(pDb->pSchema);
77391 return;
77393 /* Case 2 (from here to the end): Reset all schemas for all attached
77394 ** databases. */
77395 assert( iDb<0 );
77396 sqlite3BtreeEnterAll(db);
77397 for(i=0; i<db->nDb; i++){
77398 Db *pDb = &db->aDb[i];
77399 if( pDb->pSchema ){
77400 sqlite3SchemaClear(pDb->pSchema);
77403 db->flags &= ~SQLITE_InternChanges;
77404 sqlite3VtabUnlockList(db);
77405 sqlite3BtreeLeaveAll(db);
77407 /* If one or more of the auxiliary database files has been closed,
77408 ** then remove them from the auxiliary database list. We take the
77409 ** opportunity to do this here since we have just deleted all of the
77410 ** schema hash tables and therefore do not have to make any changes
77411 ** to any of those tables.
77413 for(i=j=2; i<db->nDb; i++){
77414 struct Db *pDb = &db->aDb[i];
77415 if( pDb->pBt==0 ){
77416 sqlite3DbFree(db, pDb->zName);
77417 pDb->zName = 0;
77418 continue;
77420 if( j<i ){
77421 db->aDb[j] = db->aDb[i];
77423 j++;
77425 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
77426 db->nDb = j;
77427 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
77428 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
77429 sqlite3DbFree(db, db->aDb);
77430 db->aDb = db->aDbStatic;
77435 ** This routine is called when a commit occurs.
77437 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
77438 db->flags &= ~SQLITE_InternChanges;
77442 ** Delete memory allocated for the column names of a table or view (the
77443 ** Table.aCol[] array).
77445 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
77446 int i;
77447 Column *pCol;
77448 assert( pTable!=0 );
77449 if( (pCol = pTable->aCol)!=0 ){
77450 for(i=0; i<pTable->nCol; i++, pCol++){
77451 sqlite3DbFree(db, pCol->zName);
77452 sqlite3ExprDelete(db, pCol->pDflt);
77453 sqlite3DbFree(db, pCol->zDflt);
77454 sqlite3DbFree(db, pCol->zType);
77455 sqlite3DbFree(db, pCol->zColl);
77457 sqlite3DbFree(db, pTable->aCol);
77462 ** Remove the memory data structures associated with the given
77463 ** Table. No changes are made to disk by this routine.
77465 ** This routine just deletes the data structure. It does not unlink
77466 ** the table data structure from the hash table. But it does destroy
77467 ** memory structures of the indices and foreign keys associated with
77468 ** the table.
77470 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
77471 Index *pIndex, *pNext;
77473 assert( !pTable || pTable->nRef>0 );
77475 /* Do not delete the table until the reference count reaches zero. */
77476 if( !pTable ) return;
77477 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
77479 /* Delete all indices associated with this table. */
77480 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
77481 pNext = pIndex->pNext;
77482 assert( pIndex->pSchema==pTable->pSchema );
77483 if( !db || db->pnBytesFreed==0 ){
77484 char *zName = pIndex->zName;
77485 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
77486 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
77488 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
77489 assert( pOld==pIndex || pOld==0 );
77491 freeIndex(db, pIndex);
77494 /* Delete any foreign keys attached to this table. */
77495 sqlite3FkDelete(db, pTable);
77497 /* Delete the Table structure itself.
77499 sqliteDeleteColumnNames(db, pTable);
77500 sqlite3DbFree(db, pTable->zName);
77501 sqlite3DbFree(db, pTable->zColAff);
77502 sqlite3SelectDelete(db, pTable->pSelect);
77503 #ifndef SQLITE_OMIT_CHECK
77504 sqlite3ExprDelete(db, pTable->pCheck);
77505 #endif
77506 #ifndef SQLITE_OMIT_VIRTUALTABLE
77507 sqlite3VtabClear(db, pTable);
77508 #endif
77509 sqlite3DbFree(db, pTable);
77513 ** Unlink the given table from the hash tables and the delete the
77514 ** table structure with all its indices and foreign keys.
77516 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
77517 Table *p;
77518 Db *pDb;
77520 assert( db!=0 );
77521 assert( iDb>=0 && iDb<db->nDb );
77522 assert( zTabName );
77523 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77524 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
77525 pDb = &db->aDb[iDb];
77526 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
77527 sqlite3Strlen30(zTabName),0);
77528 sqlite3DeleteTable(db, p);
77529 db->flags |= SQLITE_InternChanges;
77533 ** Given a token, return a string that consists of the text of that
77534 ** token. Space to hold the returned string
77535 ** is obtained from sqliteMalloc() and must be freed by the calling
77536 ** function.
77538 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
77539 ** surround the body of the token are removed.
77541 ** Tokens are often just pointers into the original SQL text and so
77542 ** are not \000 terminated and are not persistent. The returned string
77543 ** is \000 terminated and is persistent.
77545 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
77546 char *zName;
77547 if( pName ){
77548 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
77549 sqlite3Dequote(zName);
77550 }else{
77551 zName = 0;
77553 return zName;
77557 ** Open the sqlite_master table stored in database number iDb for
77558 ** writing. The table is opened using cursor 0.
77560 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
77561 Vdbe *v = sqlite3GetVdbe(p);
77562 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
77563 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
77564 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
77565 if( p->nTab==0 ){
77566 p->nTab = 1;
77571 ** Parameter zName points to a nul-terminated buffer containing the name
77572 ** of a database ("main", "temp" or the name of an attached db). This
77573 ** function returns the index of the named database in db->aDb[], or
77574 ** -1 if the named db cannot be found.
77576 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
77577 int i = -1; /* Database number */
77578 if( zName ){
77579 Db *pDb;
77580 int n = sqlite3Strlen30(zName);
77581 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
77582 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
77583 0==sqlite3StrICmp(pDb->zName, zName) ){
77584 break;
77588 return i;
77592 ** The token *pName contains the name of a database (either "main" or
77593 ** "temp" or the name of an attached db). This routine returns the
77594 ** index of the named database in db->aDb[], or -1 if the named db
77595 ** does not exist.
77597 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
77598 int i; /* Database number */
77599 char *zName; /* Name we are searching for */
77600 zName = sqlite3NameFromToken(db, pName);
77601 i = sqlite3FindDbName(db, zName);
77602 sqlite3DbFree(db, zName);
77603 return i;
77606 /* The table or view or trigger name is passed to this routine via tokens
77607 ** pName1 and pName2. If the table name was fully qualified, for example:
77609 ** CREATE TABLE xxx.yyy (...);
77611 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
77612 ** the table name is not fully qualified, i.e.:
77614 ** CREATE TABLE yyy(...);
77616 ** Then pName1 is set to "yyy" and pName2 is "".
77618 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
77619 ** pName2) that stores the unqualified table name. The index of the
77620 ** database "xxx" is returned.
77622 SQLITE_PRIVATE int sqlite3TwoPartName(
77623 Parse *pParse, /* Parsing and code generating context */
77624 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
77625 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
77626 Token **pUnqual /* Write the unqualified object name here */
77628 int iDb; /* Database holding the object */
77629 sqlite3 *db = pParse->db;
77631 if( ALWAYS(pName2!=0) && pName2->n>0 ){
77632 if( db->init.busy ) {
77633 sqlite3ErrorMsg(pParse, "corrupt database");
77634 pParse->nErr++;
77635 return -1;
77637 *pUnqual = pName2;
77638 iDb = sqlite3FindDb(db, pName1);
77639 if( iDb<0 ){
77640 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
77641 pParse->nErr++;
77642 return -1;
77644 }else{
77645 assert( db->init.iDb==0 || db->init.busy );
77646 iDb = db->init.iDb;
77647 *pUnqual = pName1;
77649 return iDb;
77653 ** This routine is used to check if the UTF-8 string zName is a legal
77654 ** unqualified name for a new schema object (table, index, view or
77655 ** trigger). All names are legal except those that begin with the string
77656 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
77657 ** is reserved for internal use.
77659 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
77660 if( !pParse->db->init.busy && pParse->nested==0
77661 && (pParse->db->flags & SQLITE_WriteSchema)==0
77662 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
77663 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
77664 return SQLITE_ERROR;
77666 return SQLITE_OK;
77670 ** Begin constructing a new table representation in memory. This is
77671 ** the first of several action routines that get called in response
77672 ** to a CREATE TABLE statement. In particular, this routine is called
77673 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
77674 ** flag is true if the table should be stored in the auxiliary database
77675 ** file instead of in the main database file. This is normally the case
77676 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
77677 ** CREATE and TABLE.
77679 ** The new table record is initialized and put in pParse->pNewTable.
77680 ** As more of the CREATE TABLE statement is parsed, additional action
77681 ** routines will be called to add more information to this record.
77682 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
77683 ** is called to complete the construction of the new table record.
77685 SQLITE_PRIVATE void sqlite3StartTable(
77686 Parse *pParse, /* Parser context */
77687 Token *pName1, /* First part of the name of the table or view */
77688 Token *pName2, /* Second part of the name of the table or view */
77689 int isTemp, /* True if this is a TEMP table */
77690 int isView, /* True if this is a VIEW */
77691 int isVirtual, /* True if this is a VIRTUAL table */
77692 int noErr /* Do nothing if table already exists */
77694 Table *pTable;
77695 char *zName = 0; /* The name of the new table */
77696 sqlite3 *db = pParse->db;
77697 Vdbe *v;
77698 int iDb; /* Database number to create the table in */
77699 Token *pName; /* Unqualified name of the table to create */
77701 /* The table or view name to create is passed to this routine via tokens
77702 ** pName1 and pName2. If the table name was fully qualified, for example:
77704 ** CREATE TABLE xxx.yyy (...);
77706 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
77707 ** the table name is not fully qualified, i.e.:
77709 ** CREATE TABLE yyy(...);
77711 ** Then pName1 is set to "yyy" and pName2 is "".
77713 ** The call below sets the pName pointer to point at the token (pName1 or
77714 ** pName2) that stores the unqualified table name. The variable iDb is
77715 ** set to the index of the database that the table or view is to be
77716 ** created in.
77718 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
77719 if( iDb<0 ) return;
77720 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
77721 /* If creating a temp table, the name may not be qualified. Unless
77722 ** the database name is "temp" anyway. */
77723 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
77724 return;
77726 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
77728 pParse->sNameToken = *pName;
77729 zName = sqlite3NameFromToken(db, pName);
77730 if( zName==0 ) return;
77731 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
77732 goto begin_table_error;
77734 if( db->init.iDb==1 ) isTemp = 1;
77735 #ifndef SQLITE_OMIT_AUTHORIZATION
77736 assert( (isTemp & 1)==isTemp );
77738 int code;
77739 char *zDb = db->aDb[iDb].zName;
77740 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
77741 goto begin_table_error;
77743 if( isView ){
77744 if( !OMIT_TEMPDB && isTemp ){
77745 code = SQLITE_CREATE_TEMP_VIEW;
77746 }else{
77747 code = SQLITE_CREATE_VIEW;
77749 }else{
77750 if( !OMIT_TEMPDB && isTemp ){
77751 code = SQLITE_CREATE_TEMP_TABLE;
77752 }else{
77753 code = SQLITE_CREATE_TABLE;
77756 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
77757 goto begin_table_error;
77760 #endif
77762 /* Make sure the new table name does not collide with an existing
77763 ** index or table name in the same database. Issue an error message if
77764 ** it does. The exception is if the statement being parsed was passed
77765 ** to an sqlite3_declare_vtab() call. In that case only the column names
77766 ** and types will be used, so there is no need to test for namespace
77767 ** collisions.
77769 if( !IN_DECLARE_VTAB ){
77770 char *zDb = db->aDb[iDb].zName;
77771 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77772 goto begin_table_error;
77774 pTable = sqlite3FindTable(db, zName, zDb);
77775 if( pTable ){
77776 if( !noErr ){
77777 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
77778 }else{
77779 assert( !db->init.busy );
77780 sqlite3CodeVerifySchema(pParse, iDb);
77782 goto begin_table_error;
77784 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
77785 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
77786 goto begin_table_error;
77790 pTable = sqlite3DbMallocZero(db, sizeof(Table));
77791 if( pTable==0 ){
77792 db->mallocFailed = 1;
77793 pParse->rc = SQLITE_NOMEM;
77794 pParse->nErr++;
77795 goto begin_table_error;
77797 pTable->zName = zName;
77798 pTable->iPKey = -1;
77799 pTable->pSchema = db->aDb[iDb].pSchema;
77800 pTable->nRef = 1;
77801 pTable->nRowEst = 1000000;
77802 assert( pParse->pNewTable==0 );
77803 pParse->pNewTable = pTable;
77805 /* If this is the magic sqlite_sequence table used by autoincrement,
77806 ** then record a pointer to this table in the main database structure
77807 ** so that INSERT can find the table easily.
77809 #ifndef SQLITE_OMIT_AUTOINCREMENT
77810 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
77811 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77812 pTable->pSchema->pSeqTab = pTable;
77814 #endif
77816 /* Begin generating the code that will insert the table record into
77817 ** the SQLITE_MASTER table. Note in particular that we must go ahead
77818 ** and allocate the record number for the table entry now. Before any
77819 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
77820 ** indices to be created and the table record must come before the
77821 ** indices. Hence, the record number for the table must be allocated
77822 ** now.
77824 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
77825 int j1;
77826 int fileFormat;
77827 int reg1, reg2, reg3;
77828 sqlite3BeginWriteOperation(pParse, 0, iDb);
77830 #ifndef SQLITE_OMIT_VIRTUALTABLE
77831 if( isVirtual ){
77832 sqlite3VdbeAddOp0(v, OP_VBegin);
77834 #endif
77836 /* If the file format and encoding in the database have not been set,
77837 ** set them now.
77839 reg1 = pParse->regRowid = ++pParse->nMem;
77840 reg2 = pParse->regRoot = ++pParse->nMem;
77841 reg3 = ++pParse->nMem;
77842 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
77843 sqlite3VdbeUsesBtree(v, iDb);
77844 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
77845 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
77846 1 : SQLITE_MAX_FILE_FORMAT;
77847 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
77848 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
77849 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
77850 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
77851 sqlite3VdbeJumpHere(v, j1);
77853 /* This just creates a place-holder record in the sqlite_master table.
77854 ** The record created does not contain anything yet. It will be replaced
77855 ** by the real entry in code generated at sqlite3EndTable().
77857 ** The rowid for the new entry is left in register pParse->regRowid.
77858 ** The root page number of the new table is left in reg pParse->regRoot.
77859 ** The rowid and root page number values are needed by the code that
77860 ** sqlite3EndTable will generate.
77862 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
77863 if( isView || isVirtual ){
77864 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
77865 }else
77866 #endif
77868 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
77870 sqlite3OpenMasterTable(pParse, iDb);
77871 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
77872 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
77873 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
77874 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
77875 sqlite3VdbeAddOp0(v, OP_Close);
77878 /* Normal (non-error) return. */
77879 return;
77881 /* If an error occurs, we jump here */
77882 begin_table_error:
77883 sqlite3DbFree(db, zName);
77884 return;
77888 ** This macro is used to compare two strings in a case-insensitive manner.
77889 ** It is slightly faster than calling sqlite3StrICmp() directly, but
77890 ** produces larger code.
77892 ** WARNING: This macro is not compatible with the strcmp() family. It
77893 ** returns true if the two strings are equal, otherwise false.
77895 #define STRICMP(x, y) (\
77896 sqlite3UpperToLower[*(unsigned char *)(x)]== \
77897 sqlite3UpperToLower[*(unsigned char *)(y)] \
77898 && sqlite3StrICmp((x)+1,(y)+1)==0 )
77901 ** Add a new column to the table currently being constructed.
77903 ** The parser calls this routine once for each column declaration
77904 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
77905 ** first to get things going. Then this routine is called for each
77906 ** column.
77908 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
77909 Table *p;
77910 int i;
77911 char *z;
77912 Column *pCol;
77913 sqlite3 *db = pParse->db;
77914 if( (p = pParse->pNewTable)==0 ) return;
77915 #if SQLITE_MAX_COLUMN
77916 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
77917 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
77918 return;
77920 #endif
77921 z = sqlite3NameFromToken(db, pName);
77922 if( z==0 ) return;
77923 for(i=0; i<p->nCol; i++){
77924 if( STRICMP(z, p->aCol[i].zName) ){
77925 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
77926 sqlite3DbFree(db, z);
77927 return;
77930 if( (p->nCol & 0x7)==0 ){
77931 Column *aNew;
77932 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
77933 if( aNew==0 ){
77934 sqlite3DbFree(db, z);
77935 return;
77937 p->aCol = aNew;
77939 pCol = &p->aCol[p->nCol];
77940 memset(pCol, 0, sizeof(p->aCol[0]));
77941 pCol->zName = z;
77943 /* If there is no type specified, columns have the default affinity
77944 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
77945 ** be called next to set pCol->affinity correctly.
77947 pCol->affinity = SQLITE_AFF_NONE;
77948 p->nCol++;
77952 ** This routine is called by the parser while in the middle of
77953 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
77954 ** been seen on a column. This routine sets the notNull flag on
77955 ** the column currently under construction.
77957 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
77958 Table *p;
77959 p = pParse->pNewTable;
77960 if( p==0 || NEVER(p->nCol<1) ) return;
77961 p->aCol[p->nCol-1].notNull = (u8)onError;
77965 ** Scan the column type name zType (length nType) and return the
77966 ** associated affinity type.
77968 ** This routine does a case-independent search of zType for the
77969 ** substrings in the following table. If one of the substrings is
77970 ** found, the corresponding affinity is returned. If zType contains
77971 ** more than one of the substrings, entries toward the top of
77972 ** the table take priority. For example, if zType is 'BLOBINT',
77973 ** SQLITE_AFF_INTEGER is returned.
77975 ** Substring | Affinity
77976 ** --------------------------------
77977 ** 'INT' | SQLITE_AFF_INTEGER
77978 ** 'CHAR' | SQLITE_AFF_TEXT
77979 ** 'CLOB' | SQLITE_AFF_TEXT
77980 ** 'TEXT' | SQLITE_AFF_TEXT
77981 ** 'BLOB' | SQLITE_AFF_NONE
77982 ** 'REAL' | SQLITE_AFF_REAL
77983 ** 'FLOA' | SQLITE_AFF_REAL
77984 ** 'DOUB' | SQLITE_AFF_REAL
77986 ** If none of the substrings in the above table are found,
77987 ** SQLITE_AFF_NUMERIC is returned.
77989 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
77990 u32 h = 0;
77991 char aff = SQLITE_AFF_NUMERIC;
77993 if( zIn ) while( zIn[0] ){
77994 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
77995 zIn++;
77996 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
77997 aff = SQLITE_AFF_TEXT;
77998 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
77999 aff = SQLITE_AFF_TEXT;
78000 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
78001 aff = SQLITE_AFF_TEXT;
78002 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
78003 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
78004 aff = SQLITE_AFF_NONE;
78005 #ifndef SQLITE_OMIT_FLOATING_POINT
78006 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
78007 && aff==SQLITE_AFF_NUMERIC ){
78008 aff = SQLITE_AFF_REAL;
78009 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
78010 && aff==SQLITE_AFF_NUMERIC ){
78011 aff = SQLITE_AFF_REAL;
78012 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
78013 && aff==SQLITE_AFF_NUMERIC ){
78014 aff = SQLITE_AFF_REAL;
78015 #endif
78016 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
78017 aff = SQLITE_AFF_INTEGER;
78018 break;
78022 return aff;
78026 ** This routine is called by the parser while in the middle of
78027 ** parsing a CREATE TABLE statement. The pFirst token is the first
78028 ** token in the sequence of tokens that describe the type of the
78029 ** column currently under construction. pLast is the last token
78030 ** in the sequence. Use this information to construct a string
78031 ** that contains the typename of the column and store that string
78032 ** in zType.
78034 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
78035 Table *p;
78036 Column *pCol;
78038 p = pParse->pNewTable;
78039 if( p==0 || NEVER(p->nCol<1) ) return;
78040 pCol = &p->aCol[p->nCol-1];
78041 assert( pCol->zType==0 );
78042 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
78043 pCol->affinity = sqlite3AffinityType(pCol->zType);
78047 ** The expression is the default value for the most recently added column
78048 ** of the table currently under construction.
78050 ** Default value expressions must be constant. Raise an exception if this
78051 ** is not the case.
78053 ** This routine is called by the parser while in the middle of
78054 ** parsing a CREATE TABLE statement.
78056 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
78057 Table *p;
78058 Column *pCol;
78059 sqlite3 *db = pParse->db;
78060 p = pParse->pNewTable;
78061 if( p!=0 ){
78062 pCol = &(p->aCol[p->nCol-1]);
78063 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
78064 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
78065 pCol->zName);
78066 }else{
78067 /* A copy of pExpr is used instead of the original, as pExpr contains
78068 ** tokens that point to volatile memory. The 'span' of the expression
78069 ** is required by pragma table_info.
78071 sqlite3ExprDelete(db, pCol->pDflt);
78072 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
78073 sqlite3DbFree(db, pCol->zDflt);
78074 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
78075 (int)(pSpan->zEnd - pSpan->zStart));
78078 sqlite3ExprDelete(db, pSpan->pExpr);
78082 ** Designate the PRIMARY KEY for the table. pList is a list of names
78083 ** of columns that form the primary key. If pList is NULL, then the
78084 ** most recently added column of the table is the primary key.
78086 ** A table can have at most one primary key. If the table already has
78087 ** a primary key (and this is the second primary key) then create an
78088 ** error.
78090 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
78091 ** then we will try to use that column as the rowid. Set the Table.iPKey
78092 ** field of the table under construction to be the index of the
78093 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
78094 ** no INTEGER PRIMARY KEY.
78096 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
78097 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
78099 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
78100 Parse *pParse, /* Parsing context */
78101 ExprList *pList, /* List of field names to be indexed */
78102 int onError, /* What to do with a uniqueness conflict */
78103 int autoInc, /* True if the AUTOINCREMENT keyword is present */
78104 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
78106 Table *pTab = pParse->pNewTable;
78107 char *zType = 0;
78108 int iCol = -1, i;
78109 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
78110 if( pTab->tabFlags & TF_HasPrimaryKey ){
78111 sqlite3ErrorMsg(pParse,
78112 "table \"%s\" has more than one primary key", pTab->zName);
78113 goto primary_key_exit;
78115 pTab->tabFlags |= TF_HasPrimaryKey;
78116 if( pList==0 ){
78117 iCol = pTab->nCol - 1;
78118 pTab->aCol[iCol].isPrimKey = 1;
78119 }else{
78120 for(i=0; i<pList->nExpr; i++){
78121 for(iCol=0; iCol<pTab->nCol; iCol++){
78122 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
78123 break;
78126 if( iCol<pTab->nCol ){
78127 pTab->aCol[iCol].isPrimKey = 1;
78130 if( pList->nExpr>1 ) iCol = -1;
78132 if( iCol>=0 && iCol<pTab->nCol ){
78133 zType = pTab->aCol[iCol].zType;
78135 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
78136 && sortOrder==SQLITE_SO_ASC ){
78137 pTab->iPKey = iCol;
78138 pTab->keyConf = (u8)onError;
78139 assert( autoInc==0 || autoInc==1 );
78140 pTab->tabFlags |= autoInc*TF_Autoincrement;
78141 }else if( autoInc ){
78142 #ifndef SQLITE_OMIT_AUTOINCREMENT
78143 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
78144 "INTEGER PRIMARY KEY");
78145 #endif
78146 }else{
78147 Index *p;
78148 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
78149 if( p ){
78150 p->autoIndex = 2;
78152 pList = 0;
78155 primary_key_exit:
78156 sqlite3ExprListDelete(pParse->db, pList);
78157 return;
78161 ** Add a new CHECK constraint to the table currently under construction.
78163 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
78164 Parse *pParse, /* Parsing context */
78165 Expr *pCheckExpr /* The check expression */
78167 sqlite3 *db = pParse->db;
78168 #ifndef SQLITE_OMIT_CHECK
78169 Table *pTab = pParse->pNewTable;
78170 if( pTab && !IN_DECLARE_VTAB ){
78171 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
78172 }else
78173 #endif
78175 sqlite3ExprDelete(db, pCheckExpr);
78180 ** Set the collation function of the most recently parsed table column
78181 ** to the CollSeq given.
78183 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
78184 Table *p;
78185 int i;
78186 char *zColl; /* Dequoted name of collation sequence */
78187 sqlite3 *db;
78189 if( (p = pParse->pNewTable)==0 ) return;
78190 i = p->nCol-1;
78191 db = pParse->db;
78192 zColl = sqlite3NameFromToken(db, pToken);
78193 if( !zColl ) return;
78195 if( sqlite3LocateCollSeq(pParse, zColl) ){
78196 Index *pIdx;
78197 p->aCol[i].zColl = zColl;
78199 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
78200 ** then an index may have been created on this column before the
78201 ** collation type was added. Correct this if it is the case.
78203 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
78204 assert( pIdx->nColumn==1 );
78205 if( pIdx->aiColumn[0]==i ){
78206 pIdx->azColl[0] = p->aCol[i].zColl;
78209 }else{
78210 sqlite3DbFree(db, zColl);
78215 ** This function returns the collation sequence for database native text
78216 ** encoding identified by the string zName, length nName.
78218 ** If the requested collation sequence is not available, or not available
78219 ** in the database native encoding, the collation factory is invoked to
78220 ** request it. If the collation factory does not supply such a sequence,
78221 ** and the sequence is available in another text encoding, then that is
78222 ** returned instead.
78224 ** If no versions of the requested collations sequence are available, or
78225 ** another error occurs, NULL is returned and an error message written into
78226 ** pParse.
78228 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
78229 ** invokes the collation factory if the named collation cannot be found
78230 ** and generates an error message.
78232 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
78234 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
78235 sqlite3 *db = pParse->db;
78236 u8 enc = ENC(db);
78237 u8 initbusy = db->init.busy;
78238 CollSeq *pColl;
78240 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
78241 if( !initbusy && (!pColl || !pColl->xCmp) ){
78242 pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
78243 if( !pColl ){
78244 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
78248 return pColl;
78253 ** Generate code that will increment the schema cookie.
78255 ** The schema cookie is used to determine when the schema for the
78256 ** database changes. After each schema change, the cookie value
78257 ** changes. When a process first reads the schema it records the
78258 ** cookie. Thereafter, whenever it goes to access the database,
78259 ** it checks the cookie to make sure the schema has not changed
78260 ** since it was last read.
78262 ** This plan is not completely bullet-proof. It is possible for
78263 ** the schema to change multiple times and for the cookie to be
78264 ** set back to prior value. But schema changes are infrequent
78265 ** and the probability of hitting the same cookie value is only
78266 ** 1 chance in 2^32. So we're safe enough.
78268 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
78269 int r1 = sqlite3GetTempReg(pParse);
78270 sqlite3 *db = pParse->db;
78271 Vdbe *v = pParse->pVdbe;
78272 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78273 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
78274 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
78275 sqlite3ReleaseTempReg(pParse, r1);
78279 ** Measure the number of characters needed to output the given
78280 ** identifier. The number returned includes any quotes used
78281 ** but does not include the null terminator.
78283 ** The estimate is conservative. It might be larger that what is
78284 ** really needed.
78286 static int identLength(const char *z){
78287 int n;
78288 for(n=0; *z; n++, z++){
78289 if( *z=='"' ){ n++; }
78291 return n + 2;
78295 ** The first parameter is a pointer to an output buffer. The second
78296 ** parameter is a pointer to an integer that contains the offset at
78297 ** which to write into the output buffer. This function copies the
78298 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
78299 ** to the specified offset in the buffer and updates *pIdx to refer
78300 ** to the first byte after the last byte written before returning.
78302 ** If the string zSignedIdent consists entirely of alpha-numeric
78303 ** characters, does not begin with a digit and is not an SQL keyword,
78304 ** then it is copied to the output buffer exactly as it is. Otherwise,
78305 ** it is quoted using double-quotes.
78307 static void identPut(char *z, int *pIdx, char *zSignedIdent){
78308 unsigned char *zIdent = (unsigned char*)zSignedIdent;
78309 int i, j, needQuote;
78310 i = *pIdx;
78312 for(j=0; zIdent[j]; j++){
78313 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
78315 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
78316 if( !needQuote ){
78317 needQuote = zIdent[j];
78320 if( needQuote ) z[i++] = '"';
78321 for(j=0; zIdent[j]; j++){
78322 z[i++] = zIdent[j];
78323 if( zIdent[j]=='"' ) z[i++] = '"';
78325 if( needQuote ) z[i++] = '"';
78326 z[i] = 0;
78327 *pIdx = i;
78331 ** Generate a CREATE TABLE statement appropriate for the given
78332 ** table. Memory to hold the text of the statement is obtained
78333 ** from sqliteMalloc() and must be freed by the calling function.
78335 static char *createTableStmt(sqlite3 *db, Table *p){
78336 int i, k, n;
78337 char *zStmt;
78338 char *zSep, *zSep2, *zEnd;
78339 Column *pCol;
78340 n = 0;
78341 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
78342 n += identLength(pCol->zName) + 5;
78344 n += identLength(p->zName);
78345 if( n<50 ){
78346 zSep = "";
78347 zSep2 = ",";
78348 zEnd = ")";
78349 }else{
78350 zSep = "\n ";
78351 zSep2 = ",\n ";
78352 zEnd = "\n)";
78354 n += 35 + 6*p->nCol;
78355 zStmt = sqlite3DbMallocRaw(0, n);
78356 if( zStmt==0 ){
78357 db->mallocFailed = 1;
78358 return 0;
78360 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
78361 k = sqlite3Strlen30(zStmt);
78362 identPut(zStmt, &k, p->zName);
78363 zStmt[k++] = '(';
78364 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
78365 static const char * const azType[] = {
78366 /* SQLITE_AFF_TEXT */ " TEXT",
78367 /* SQLITE_AFF_NONE */ "",
78368 /* SQLITE_AFF_NUMERIC */ " NUM",
78369 /* SQLITE_AFF_INTEGER */ " INT",
78370 /* SQLITE_AFF_REAL */ " REAL"
78372 int len;
78373 const char *zType;
78375 sqlite3_snprintf(n-k, &zStmt[k], zSep);
78376 k += sqlite3Strlen30(&zStmt[k]);
78377 zSep = zSep2;
78378 identPut(zStmt, &k, pCol->zName);
78379 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
78380 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
78381 testcase( pCol->affinity==SQLITE_AFF_TEXT );
78382 testcase( pCol->affinity==SQLITE_AFF_NONE );
78383 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
78384 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
78385 testcase( pCol->affinity==SQLITE_AFF_REAL );
78387 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
78388 len = sqlite3Strlen30(zType);
78389 assert( pCol->affinity==SQLITE_AFF_NONE
78390 || pCol->affinity==sqlite3AffinityType(zType) );
78391 memcpy(&zStmt[k], zType, len);
78392 k += len;
78393 assert( k<=n );
78395 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
78396 return zStmt;
78400 ** This routine is called to report the final ")" that terminates
78401 ** a CREATE TABLE statement.
78403 ** The table structure that other action routines have been building
78404 ** is added to the internal hash tables, assuming no errors have
78405 ** occurred.
78407 ** An entry for the table is made in the master table on disk, unless
78408 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
78409 ** it means we are reading the sqlite_master table because we just
78410 ** connected to the database or because the sqlite_master table has
78411 ** recently changed, so the entry for this table already exists in
78412 ** the sqlite_master table. We do not want to create it again.
78414 ** If the pSelect argument is not NULL, it means that this routine
78415 ** was called to create a table generated from a
78416 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
78417 ** the new table will match the result set of the SELECT.
78419 SQLITE_PRIVATE void sqlite3EndTable(
78420 Parse *pParse, /* Parse context */
78421 Token *pCons, /* The ',' token after the last column defn. */
78422 Token *pEnd, /* The final ')' token in the CREATE TABLE */
78423 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
78425 Table *p;
78426 sqlite3 *db = pParse->db;
78427 int iDb;
78429 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
78430 return;
78432 p = pParse->pNewTable;
78433 if( p==0 ) return;
78435 assert( !db->init.busy || !pSelect );
78437 iDb = sqlite3SchemaToIndex(db, p->pSchema);
78439 #ifndef SQLITE_OMIT_CHECK
78440 /* Resolve names in all CHECK constraint expressions.
78442 if( p->pCheck ){
78443 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
78444 NameContext sNC; /* Name context for pParse->pNewTable */
78446 memset(&sNC, 0, sizeof(sNC));
78447 memset(&sSrc, 0, sizeof(sSrc));
78448 sSrc.nSrc = 1;
78449 sSrc.a[0].zName = p->zName;
78450 sSrc.a[0].pTab = p;
78451 sSrc.a[0].iCursor = -1;
78452 sNC.pParse = pParse;
78453 sNC.pSrcList = &sSrc;
78454 sNC.isCheck = 1;
78455 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
78456 return;
78459 #endif /* !defined(SQLITE_OMIT_CHECK) */
78461 /* If the db->init.busy is 1 it means we are reading the SQL off the
78462 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
78463 ** So do not write to the disk again. Extract the root page number
78464 ** for the table from the db->init.newTnum field. (The page number
78465 ** should have been put there by the sqliteOpenCb routine.)
78467 if( db->init.busy ){
78468 p->tnum = db->init.newTnum;
78471 /* If not initializing, then create a record for the new table
78472 ** in the SQLITE_MASTER table of the database.
78474 ** If this is a TEMPORARY table, write the entry into the auxiliary
78475 ** file instead of into the main database file.
78477 if( !db->init.busy ){
78478 int n;
78479 Vdbe *v;
78480 char *zType; /* "view" or "table" */
78481 char *zType2; /* "VIEW" or "TABLE" */
78482 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
78484 v = sqlite3GetVdbe(pParse);
78485 if( NEVER(v==0) ) return;
78487 sqlite3VdbeAddOp1(v, OP_Close, 0);
78490 ** Initialize zType for the new view or table.
78492 if( p->pSelect==0 ){
78493 /* A regular table */
78494 zType = "table";
78495 zType2 = "TABLE";
78496 #ifndef SQLITE_OMIT_VIEW
78497 }else{
78498 /* A view */
78499 zType = "view";
78500 zType2 = "VIEW";
78501 #endif
78504 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
78505 ** statement to populate the new table. The root-page number for the
78506 ** new table is in register pParse->regRoot.
78508 ** Once the SELECT has been coded by sqlite3Select(), it is in a
78509 ** suitable state to query for the column names and types to be used
78510 ** by the new table.
78512 ** A shared-cache write-lock is not required to write to the new table,
78513 ** as a schema-lock must have already been obtained to create it. Since
78514 ** a schema-lock excludes all other database users, the write-lock would
78515 ** be redundant.
78517 if( pSelect ){
78518 SelectDest dest;
78519 Table *pSelTab;
78521 assert(pParse->nTab==1);
78522 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
78523 sqlite3VdbeChangeP5(v, 1);
78524 pParse->nTab = 2;
78525 sqlite3SelectDestInit(&dest, SRT_Table, 1);
78526 sqlite3Select(pParse, pSelect, &dest);
78527 sqlite3VdbeAddOp1(v, OP_Close, 1);
78528 if( pParse->nErr==0 ){
78529 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
78530 if( pSelTab==0 ) return;
78531 assert( p->aCol==0 );
78532 p->nCol = pSelTab->nCol;
78533 p->aCol = pSelTab->aCol;
78534 pSelTab->nCol = 0;
78535 pSelTab->aCol = 0;
78536 sqlite3DeleteTable(db, pSelTab);
78540 /* Compute the complete text of the CREATE statement */
78541 if( pSelect ){
78542 zStmt = createTableStmt(db, p);
78543 }else{
78544 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
78545 zStmt = sqlite3MPrintf(db,
78546 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
78550 /* A slot for the record has already been allocated in the
78551 ** SQLITE_MASTER table. We just need to update that slot with all
78552 ** the information we've collected.
78554 sqlite3NestedParse(pParse,
78555 "UPDATE %Q.%s "
78556 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
78557 "WHERE rowid=#%d",
78558 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
78559 zType,
78560 p->zName,
78561 p->zName,
78562 pParse->regRoot,
78563 zStmt,
78564 pParse->regRowid
78566 sqlite3DbFree(db, zStmt);
78567 sqlite3ChangeCookie(pParse, iDb);
78569 #ifndef SQLITE_OMIT_AUTOINCREMENT
78570 /* Check to see if we need to create an sqlite_sequence table for
78571 ** keeping track of autoincrement keys.
78573 if( p->tabFlags & TF_Autoincrement ){
78574 Db *pDb = &db->aDb[iDb];
78575 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78576 if( pDb->pSchema->pSeqTab==0 ){
78577 sqlite3NestedParse(pParse,
78578 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
78579 pDb->zName
78583 #endif
78585 /* Reparse everything to update our internal data structures */
78586 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
78587 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
78591 /* Add the table to the in-memory representation of the database.
78593 if( db->init.busy ){
78594 Table *pOld;
78595 Schema *pSchema = p->pSchema;
78596 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78597 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
78598 sqlite3Strlen30(p->zName),p);
78599 if( pOld ){
78600 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
78601 db->mallocFailed = 1;
78602 return;
78604 pParse->pNewTable = 0;
78605 db->nTable++;
78606 db->flags |= SQLITE_InternChanges;
78608 #ifndef SQLITE_OMIT_ALTERTABLE
78609 if( !p->pSelect ){
78610 const char *zName = (const char *)pParse->sNameToken.z;
78611 int nName;
78612 assert( !pSelect && pCons && pEnd );
78613 if( pCons->z==0 ){
78614 pCons = pEnd;
78616 nName = (int)((const char *)pCons->z - zName);
78617 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
78619 #endif
78623 #ifndef SQLITE_OMIT_VIEW
78625 ** The parser calls this routine in order to create a new VIEW
78627 SQLITE_PRIVATE void sqlite3CreateView(
78628 Parse *pParse, /* The parsing context */
78629 Token *pBegin, /* The CREATE token that begins the statement */
78630 Token *pName1, /* The token that holds the name of the view */
78631 Token *pName2, /* The token that holds the name of the view */
78632 Select *pSelect, /* A SELECT statement that will become the new view */
78633 int isTemp, /* TRUE for a TEMPORARY view */
78634 int noErr /* Suppress error messages if VIEW already exists */
78636 Table *p;
78637 int n;
78638 const char *z;
78639 Token sEnd;
78640 DbFixer sFix;
78641 Token *pName;
78642 int iDb;
78643 sqlite3 *db = pParse->db;
78645 if( pParse->nVar>0 ){
78646 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
78647 sqlite3SelectDelete(db, pSelect);
78648 return;
78650 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
78651 p = pParse->pNewTable;
78652 if( p==0 || pParse->nErr ){
78653 sqlite3SelectDelete(db, pSelect);
78654 return;
78656 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
78657 iDb = sqlite3SchemaToIndex(db, p->pSchema);
78658 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
78659 && sqlite3FixSelect(&sFix, pSelect)
78661 sqlite3SelectDelete(db, pSelect);
78662 return;
78665 /* Make a copy of the entire SELECT statement that defines the view.
78666 ** This will force all the Expr.token.z values to be dynamically
78667 ** allocated rather than point to the input string - which means that
78668 ** they will persist after the current sqlite3_exec() call returns.
78670 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
78671 sqlite3SelectDelete(db, pSelect);
78672 if( db->mallocFailed ){
78673 return;
78675 if( !db->init.busy ){
78676 sqlite3ViewGetColumnNames(pParse, p);
78679 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
78680 ** the end.
78682 sEnd = pParse->sLastToken;
78683 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
78684 sEnd.z += sEnd.n;
78686 sEnd.n = 0;
78687 n = (int)(sEnd.z - pBegin->z);
78688 z = pBegin->z;
78689 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
78690 sEnd.z = &z[n-1];
78691 sEnd.n = 1;
78693 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
78694 sqlite3EndTable(pParse, 0, &sEnd, 0);
78695 return;
78697 #endif /* SQLITE_OMIT_VIEW */
78699 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
78701 ** The Table structure pTable is really a VIEW. Fill in the names of
78702 ** the columns of the view in the pTable structure. Return the number
78703 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
78705 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
78706 Table *pSelTab; /* A fake table from which we get the result set */
78707 Select *pSel; /* Copy of the SELECT that implements the view */
78708 int nErr = 0; /* Number of errors encountered */
78709 int n; /* Temporarily holds the number of cursors assigned */
78710 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
78711 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
78713 assert( pTable );
78715 #ifndef SQLITE_OMIT_VIRTUALTABLE
78716 if( sqlite3VtabCallConnect(pParse, pTable) ){
78717 return SQLITE_ERROR;
78719 if( IsVirtual(pTable) ) return 0;
78720 #endif
78722 #ifndef SQLITE_OMIT_VIEW
78723 /* A positive nCol means the columns names for this view are
78724 ** already known.
78726 if( pTable->nCol>0 ) return 0;
78728 /* A negative nCol is a special marker meaning that we are currently
78729 ** trying to compute the column names. If we enter this routine with
78730 ** a negative nCol, it means two or more views form a loop, like this:
78732 ** CREATE VIEW one AS SELECT * FROM two;
78733 ** CREATE VIEW two AS SELECT * FROM one;
78735 ** Actually, the error above is now caught prior to reaching this point.
78736 ** But the following test is still important as it does come up
78737 ** in the following:
78739 ** CREATE TABLE main.ex1(a);
78740 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
78741 ** SELECT * FROM temp.ex1;
78743 if( pTable->nCol<0 ){
78744 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
78745 return 1;
78747 assert( pTable->nCol>=0 );
78749 /* If we get this far, it means we need to compute the table names.
78750 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
78751 ** "*" elements in the results set of the view and will assign cursors
78752 ** to the elements of the FROM clause. But we do not want these changes
78753 ** to be permanent. So the computation is done on a copy of the SELECT
78754 ** statement that defines the view.
78756 assert( pTable->pSelect );
78757 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
78758 if( pSel ){
78759 u8 enableLookaside = db->lookaside.bEnabled;
78760 n = pParse->nTab;
78761 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
78762 pTable->nCol = -1;
78763 db->lookaside.bEnabled = 0;
78764 #ifndef SQLITE_OMIT_AUTHORIZATION
78765 xAuth = db->xAuth;
78766 db->xAuth = 0;
78767 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
78768 db->xAuth = xAuth;
78769 #else
78770 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
78771 #endif
78772 db->lookaside.bEnabled = enableLookaside;
78773 pParse->nTab = n;
78774 if( pSelTab ){
78775 assert( pTable->aCol==0 );
78776 pTable->nCol = pSelTab->nCol;
78777 pTable->aCol = pSelTab->aCol;
78778 pSelTab->nCol = 0;
78779 pSelTab->aCol = 0;
78780 sqlite3DeleteTable(db, pSelTab);
78781 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
78782 pTable->pSchema->flags |= DB_UnresetViews;
78783 }else{
78784 pTable->nCol = 0;
78785 nErr++;
78787 sqlite3SelectDelete(db, pSel);
78788 } else {
78789 nErr++;
78791 #endif /* SQLITE_OMIT_VIEW */
78792 return nErr;
78794 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
78796 #ifndef SQLITE_OMIT_VIEW
78798 ** Clear the column names from every VIEW in database idx.
78800 static void sqliteViewResetAll(sqlite3 *db, int idx){
78801 HashElem *i;
78802 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
78803 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
78804 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
78805 Table *pTab = sqliteHashData(i);
78806 if( pTab->pSelect ){
78807 sqliteDeleteColumnNames(db, pTab);
78808 pTab->aCol = 0;
78809 pTab->nCol = 0;
78812 DbClearProperty(db, idx, DB_UnresetViews);
78814 #else
78815 # define sqliteViewResetAll(A,B)
78816 #endif /* SQLITE_OMIT_VIEW */
78819 ** This function is called by the VDBE to adjust the internal schema
78820 ** used by SQLite when the btree layer moves a table root page. The
78821 ** root-page of a table or index in database iDb has changed from iFrom
78822 ** to iTo.
78824 ** Ticket #1728: The symbol table might still contain information
78825 ** on tables and/or indices that are the process of being deleted.
78826 ** If you are unlucky, one of those deleted indices or tables might
78827 ** have the same rootpage number as the real table or index that is
78828 ** being moved. So we cannot stop searching after the first match
78829 ** because the first match might be for one of the deleted indices
78830 ** or tables and not the table/index that is actually being moved.
78831 ** We must continue looping until all tables and indices with
78832 ** rootpage==iFrom have been converted to have a rootpage of iTo
78833 ** in order to be certain that we got the right one.
78835 #ifndef SQLITE_OMIT_AUTOVACUUM
78836 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
78837 HashElem *pElem;
78838 Hash *pHash;
78839 Db *pDb;
78841 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78842 pDb = &db->aDb[iDb];
78843 pHash = &pDb->pSchema->tblHash;
78844 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
78845 Table *pTab = sqliteHashData(pElem);
78846 if( pTab->tnum==iFrom ){
78847 pTab->tnum = iTo;
78850 pHash = &pDb->pSchema->idxHash;
78851 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
78852 Index *pIdx = sqliteHashData(pElem);
78853 if( pIdx->tnum==iFrom ){
78854 pIdx->tnum = iTo;
78858 #endif
78861 ** Write code to erase the table with root-page iTable from database iDb.
78862 ** Also write code to modify the sqlite_master table and internal schema
78863 ** if a root-page of another table is moved by the btree-layer whilst
78864 ** erasing iTable (this can happen with an auto-vacuum database).
78866 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
78867 Vdbe *v = sqlite3GetVdbe(pParse);
78868 int r1 = sqlite3GetTempReg(pParse);
78869 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
78870 sqlite3MayAbort(pParse);
78871 #ifndef SQLITE_OMIT_AUTOVACUUM
78872 /* OP_Destroy stores an in integer r1. If this integer
78873 ** is non-zero, then it is the root page number of a table moved to
78874 ** location iTable. The following code modifies the sqlite_master table to
78875 ** reflect this.
78877 ** The "#NNN" in the SQL is a special constant that means whatever value
78878 ** is in register NNN. See grammar rules associated with the TK_REGISTER
78879 ** token for additional information.
78881 sqlite3NestedParse(pParse,
78882 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
78883 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
78884 #endif
78885 sqlite3ReleaseTempReg(pParse, r1);
78889 ** Write VDBE code to erase table pTab and all associated indices on disk.
78890 ** Code to update the sqlite_master tables and internal schema definitions
78891 ** in case a root-page belonging to another table is moved by the btree layer
78892 ** is also added (this can happen with an auto-vacuum database).
78894 static void destroyTable(Parse *pParse, Table *pTab){
78895 #ifdef SQLITE_OMIT_AUTOVACUUM
78896 Index *pIdx;
78897 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78898 destroyRootPage(pParse, pTab->tnum, iDb);
78899 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78900 destroyRootPage(pParse, pIdx->tnum, iDb);
78902 #else
78903 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
78904 ** is not defined), then it is important to call OP_Destroy on the
78905 ** table and index root-pages in order, starting with the numerically
78906 ** largest root-page number. This guarantees that none of the root-pages
78907 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
78908 ** following were coded:
78910 ** OP_Destroy 4 0
78911 ** ...
78912 ** OP_Destroy 5 0
78914 ** and root page 5 happened to be the largest root-page number in the
78915 ** database, then root page 5 would be moved to page 4 by the
78916 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
78917 ** a free-list page.
78919 int iTab = pTab->tnum;
78920 int iDestroyed = 0;
78922 while( 1 ){
78923 Index *pIdx;
78924 int iLargest = 0;
78926 if( iDestroyed==0 || iTab<iDestroyed ){
78927 iLargest = iTab;
78929 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78930 int iIdx = pIdx->tnum;
78931 assert( pIdx->pSchema==pTab->pSchema );
78932 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
78933 iLargest = iIdx;
78936 if( iLargest==0 ){
78937 return;
78938 }else{
78939 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78940 destroyRootPage(pParse, iLargest, iDb);
78941 iDestroyed = iLargest;
78944 #endif
78948 ** This routine is called to do the work of a DROP TABLE statement.
78949 ** pName is the name of the table to be dropped.
78951 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
78952 Table *pTab;
78953 Vdbe *v;
78954 sqlite3 *db = pParse->db;
78955 int iDb;
78957 if( db->mallocFailed ){
78958 goto exit_drop_table;
78960 assert( pParse->nErr==0 );
78961 assert( pName->nSrc==1 );
78962 if( noErr ) db->suppressErr++;
78963 pTab = sqlite3LocateTable(pParse, isView,
78964 pName->a[0].zName, pName->a[0].zDatabase);
78965 if( noErr ) db->suppressErr--;
78967 if( pTab==0 ){
78968 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
78969 goto exit_drop_table;
78971 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78972 assert( iDb>=0 && iDb<db->nDb );
78974 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
78975 ** it is initialized.
78977 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
78978 goto exit_drop_table;
78980 #ifndef SQLITE_OMIT_AUTHORIZATION
78982 int code;
78983 const char *zTab = SCHEMA_TABLE(iDb);
78984 const char *zDb = db->aDb[iDb].zName;
78985 const char *zArg2 = 0;
78986 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
78987 goto exit_drop_table;
78989 if( isView ){
78990 if( !OMIT_TEMPDB && iDb==1 ){
78991 code = SQLITE_DROP_TEMP_VIEW;
78992 }else{
78993 code = SQLITE_DROP_VIEW;
78995 #ifndef SQLITE_OMIT_VIRTUALTABLE
78996 }else if( IsVirtual(pTab) ){
78997 code = SQLITE_DROP_VTABLE;
78998 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
78999 #endif
79000 }else{
79001 if( !OMIT_TEMPDB && iDb==1 ){
79002 code = SQLITE_DROP_TEMP_TABLE;
79003 }else{
79004 code = SQLITE_DROP_TABLE;
79007 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
79008 goto exit_drop_table;
79010 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
79011 goto exit_drop_table;
79014 #endif
79015 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
79016 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
79017 goto exit_drop_table;
79020 #ifndef SQLITE_OMIT_VIEW
79021 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
79022 ** on a table.
79024 if( isView && pTab->pSelect==0 ){
79025 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
79026 goto exit_drop_table;
79028 if( !isView && pTab->pSelect ){
79029 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
79030 goto exit_drop_table;
79032 #endif
79034 /* Generate code to remove the table from the master table
79035 ** on disk.
79037 v = sqlite3GetVdbe(pParse);
79038 if( v ){
79039 Trigger *pTrigger;
79040 Db *pDb = &db->aDb[iDb];
79041 sqlite3BeginWriteOperation(pParse, 1, iDb);
79043 #ifndef SQLITE_OMIT_VIRTUALTABLE
79044 if( IsVirtual(pTab) ){
79045 sqlite3VdbeAddOp0(v, OP_VBegin);
79047 #endif
79048 sqlite3FkDropTable(pParse, pName, pTab);
79050 /* Drop all triggers associated with the table being dropped. Code
79051 ** is generated to remove entries from sqlite_master and/or
79052 ** sqlite_temp_master if required.
79054 pTrigger = sqlite3TriggerList(pParse, pTab);
79055 while( pTrigger ){
79056 assert( pTrigger->pSchema==pTab->pSchema ||
79057 pTrigger->pSchema==db->aDb[1].pSchema );
79058 sqlite3DropTriggerPtr(pParse, pTrigger);
79059 pTrigger = pTrigger->pNext;
79062 #ifndef SQLITE_OMIT_AUTOINCREMENT
79063 /* Remove any entries of the sqlite_sequence table associated with
79064 ** the table being dropped. This is done before the table is dropped
79065 ** at the btree level, in case the sqlite_sequence table needs to
79066 ** move as a result of the drop (can happen in auto-vacuum mode).
79068 if( pTab->tabFlags & TF_Autoincrement ){
79069 sqlite3NestedParse(pParse,
79070 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
79071 pDb->zName, pTab->zName
79074 #endif
79076 /* Drop all SQLITE_MASTER table and index entries that refer to the
79077 ** table. The program name loops through the master table and deletes
79078 ** every row that refers to a table of the same name as the one being
79079 ** dropped. Triggers are handled seperately because a trigger can be
79080 ** created in the temp database that refers to a table in another
79081 ** database.
79083 sqlite3NestedParse(pParse,
79084 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
79085 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
79087 /* Drop any statistics from the sqlite_stat1 table, if it exists */
79088 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
79089 sqlite3NestedParse(pParse,
79090 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
79094 if( !isView && !IsVirtual(pTab) ){
79095 destroyTable(pParse, pTab);
79098 /* Remove the table entry from SQLite's internal schema and modify
79099 ** the schema cookie.
79101 if( IsVirtual(pTab) ){
79102 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
79104 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
79105 sqlite3ChangeCookie(pParse, iDb);
79107 sqliteViewResetAll(db, iDb);
79109 exit_drop_table:
79110 sqlite3SrcListDelete(db, pName);
79114 ** This routine is called to create a new foreign key on the table
79115 ** currently under construction. pFromCol determines which columns
79116 ** in the current table point to the foreign key. If pFromCol==0 then
79117 ** connect the key to the last column inserted. pTo is the name of
79118 ** the table referred to. pToCol is a list of tables in the other
79119 ** pTo table that the foreign key points to. flags contains all
79120 ** information about the conflict resolution algorithms specified
79121 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
79123 ** An FKey structure is created and added to the table currently
79124 ** under construction in the pParse->pNewTable field.
79126 ** The foreign key is set for IMMEDIATE processing. A subsequent call
79127 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
79129 SQLITE_PRIVATE void sqlite3CreateForeignKey(
79130 Parse *pParse, /* Parsing context */
79131 ExprList *pFromCol, /* Columns in this table that point to other table */
79132 Token *pTo, /* Name of the other table */
79133 ExprList *pToCol, /* Columns in the other table */
79134 int flags /* Conflict resolution algorithms. */
79136 sqlite3 *db = pParse->db;
79137 #ifndef SQLITE_OMIT_FOREIGN_KEY
79138 FKey *pFKey = 0;
79139 FKey *pNextTo;
79140 Table *p = pParse->pNewTable;
79141 int nByte;
79142 int i;
79143 int nCol;
79144 char *z;
79146 assert( pTo!=0 );
79147 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
79148 if( pFromCol==0 ){
79149 int iCol = p->nCol-1;
79150 if( NEVER(iCol<0) ) goto fk_end;
79151 if( pToCol && pToCol->nExpr!=1 ){
79152 sqlite3ErrorMsg(pParse, "foreign key on %s"
79153 " should reference only one column of table %T",
79154 p->aCol[iCol].zName, pTo);
79155 goto fk_end;
79157 nCol = 1;
79158 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
79159 sqlite3ErrorMsg(pParse,
79160 "number of columns in foreign key does not match the number of "
79161 "columns in the referenced table");
79162 goto fk_end;
79163 }else{
79164 nCol = pFromCol->nExpr;
79166 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
79167 if( pToCol ){
79168 for(i=0; i<pToCol->nExpr; i++){
79169 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
79172 pFKey = sqlite3DbMallocZero(db, nByte );
79173 if( pFKey==0 ){
79174 goto fk_end;
79176 pFKey->pFrom = p;
79177 pFKey->pNextFrom = p->pFKey;
79178 z = (char*)&pFKey->aCol[nCol];
79179 pFKey->zTo = z;
79180 memcpy(z, pTo->z, pTo->n);
79181 z[pTo->n] = 0;
79182 sqlite3Dequote(z);
79183 z += pTo->n+1;
79184 pFKey->nCol = nCol;
79185 if( pFromCol==0 ){
79186 pFKey->aCol[0].iFrom = p->nCol-1;
79187 }else{
79188 for(i=0; i<nCol; i++){
79189 int j;
79190 for(j=0; j<p->nCol; j++){
79191 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
79192 pFKey->aCol[i].iFrom = j;
79193 break;
79196 if( j>=p->nCol ){
79197 sqlite3ErrorMsg(pParse,
79198 "unknown column \"%s\" in foreign key definition",
79199 pFromCol->a[i].zName);
79200 goto fk_end;
79204 if( pToCol ){
79205 for(i=0; i<nCol; i++){
79206 int n = sqlite3Strlen30(pToCol->a[i].zName);
79207 pFKey->aCol[i].zCol = z;
79208 memcpy(z, pToCol->a[i].zName, n);
79209 z[n] = 0;
79210 z += n+1;
79213 pFKey->isDeferred = 0;
79214 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
79215 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
79217 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
79218 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
79219 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
79221 if( pNextTo==pFKey ){
79222 db->mallocFailed = 1;
79223 goto fk_end;
79225 if( pNextTo ){
79226 assert( pNextTo->pPrevTo==0 );
79227 pFKey->pNextTo = pNextTo;
79228 pNextTo->pPrevTo = pFKey;
79231 /* Link the foreign key to the table as the last step.
79233 p->pFKey = pFKey;
79234 pFKey = 0;
79236 fk_end:
79237 sqlite3DbFree(db, pFKey);
79238 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
79239 sqlite3ExprListDelete(db, pFromCol);
79240 sqlite3ExprListDelete(db, pToCol);
79244 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
79245 ** clause is seen as part of a foreign key definition. The isDeferred
79246 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
79247 ** The behavior of the most recently created foreign key is adjusted
79248 ** accordingly.
79250 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
79251 #ifndef SQLITE_OMIT_FOREIGN_KEY
79252 Table *pTab;
79253 FKey *pFKey;
79254 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
79255 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
79256 pFKey->isDeferred = (u8)isDeferred;
79257 #endif
79261 ** Generate code that will erase and refill index *pIdx. This is
79262 ** used to initialize a newly created index or to recompute the
79263 ** content of an index in response to a REINDEX command.
79265 ** if memRootPage is not negative, it means that the index is newly
79266 ** created. The register specified by memRootPage contains the
79267 ** root page number of the index. If memRootPage is negative, then
79268 ** the index already exists and must be cleared before being refilled and
79269 ** the root page number of the index is taken from pIndex->tnum.
79271 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
79272 Table *pTab = pIndex->pTable; /* The table that is indexed */
79273 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
79274 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
79275 int addr1; /* Address of top of loop */
79276 int tnum; /* Root page of index */
79277 Vdbe *v; /* Generate code into this virtual machine */
79278 KeyInfo *pKey; /* KeyInfo for index */
79279 int regIdxKey; /* Registers containing the index key */
79280 int regRecord; /* Register holding assemblied index record */
79281 sqlite3 *db = pParse->db; /* The database connection */
79282 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
79284 #ifndef SQLITE_OMIT_AUTHORIZATION
79285 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
79286 db->aDb[iDb].zName ) ){
79287 return;
79289 #endif
79291 /* Require a write-lock on the table to perform this operation */
79292 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
79294 v = sqlite3GetVdbe(pParse);
79295 if( v==0 ) return;
79296 if( memRootPage>=0 ){
79297 tnum = memRootPage;
79298 }else{
79299 tnum = pIndex->tnum;
79300 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
79302 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
79303 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
79304 (char *)pKey, P4_KEYINFO_HANDOFF);
79305 if( memRootPage>=0 ){
79306 sqlite3VdbeChangeP5(v, 1);
79308 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
79309 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
79310 regRecord = sqlite3GetTempReg(pParse);
79311 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
79312 if( pIndex->onError!=OE_None ){
79313 const int regRowid = regIdxKey + pIndex->nColumn;
79314 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
79315 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
79317 /* The registers accessed by the OP_IsUnique opcode were allocated
79318 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
79319 ** call above. Just before that function was freed they were released
79320 ** (made available to the compiler for reuse) using
79321 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
79322 ** opcode use the values stored within seems dangerous. However, since
79323 ** we can be sure that no other temp registers have been allocated
79324 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
79326 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
79327 sqlite3HaltConstraint(
79328 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
79330 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
79331 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
79332 sqlite3ReleaseTempReg(pParse, regRecord);
79333 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
79334 sqlite3VdbeJumpHere(v, addr1);
79335 sqlite3VdbeAddOp1(v, OP_Close, iTab);
79336 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
79340 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
79341 ** and pTblList is the name of the table that is to be indexed. Both will
79342 ** be NULL for a primary key or an index that is created to satisfy a
79343 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
79344 ** as the table to be indexed. pParse->pNewTable is a table that is
79345 ** currently being constructed by a CREATE TABLE statement.
79347 ** pList is a list of columns to be indexed. pList will be NULL if this
79348 ** is a primary key or unique-constraint on the most recent column added
79349 ** to the table currently under construction.
79351 ** If the index is created successfully, return a pointer to the new Index
79352 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
79353 ** as the tables primary key (Index.autoIndex==2).
79355 SQLITE_PRIVATE Index *sqlite3CreateIndex(
79356 Parse *pParse, /* All information about this parse */
79357 Token *pName1, /* First part of index name. May be NULL */
79358 Token *pName2, /* Second part of index name. May be NULL */
79359 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
79360 ExprList *pList, /* A list of columns to be indexed */
79361 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
79362 Token *pStart, /* The CREATE token that begins this statement */
79363 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
79364 int sortOrder, /* Sort order of primary key when pList==NULL */
79365 int ifNotExist /* Omit error if index already exists */
79367 Index *pRet = 0; /* Pointer to return */
79368 Table *pTab = 0; /* Table to be indexed */
79369 Index *pIndex = 0; /* The index to be created */
79370 char *zName = 0; /* Name of the index */
79371 int nName; /* Number of characters in zName */
79372 int i, j;
79373 Token nullId; /* Fake token for an empty ID list */
79374 DbFixer sFix; /* For assigning database names to pTable */
79375 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
79376 sqlite3 *db = pParse->db;
79377 Db *pDb; /* The specific table containing the indexed database */
79378 int iDb; /* Index of the database that is being written */
79379 Token *pName = 0; /* Unqualified name of the index to create */
79380 struct ExprList_item *pListItem; /* For looping over pList */
79381 int nCol;
79382 int nExtra = 0;
79383 char *zExtra;
79385 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
79386 assert( pParse->nErr==0 ); /* Never called with prior errors */
79387 if( db->mallocFailed || IN_DECLARE_VTAB ){
79388 goto exit_create_index;
79390 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79391 goto exit_create_index;
79395 ** Find the table that is to be indexed. Return early if not found.
79397 if( pTblName!=0 ){
79399 /* Use the two-part index name to determine the database
79400 ** to search for the table. 'Fix' the table name to this db
79401 ** before looking up the table.
79403 assert( pName1 && pName2 );
79404 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
79405 if( iDb<0 ) goto exit_create_index;
79407 #ifndef SQLITE_OMIT_TEMPDB
79408 /* If the index name was unqualified, check if the the table
79409 ** is a temp table. If so, set the database to 1. Do not do this
79410 ** if initialising a database schema.
79412 if( !db->init.busy ){
79413 pTab = sqlite3SrcListLookup(pParse, pTblName);
79414 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
79415 iDb = 1;
79418 #endif
79420 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
79421 sqlite3FixSrcList(&sFix, pTblName)
79423 /* Because the parser constructs pTblName from a single identifier,
79424 ** sqlite3FixSrcList can never fail. */
79425 assert(0);
79427 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
79428 pTblName->a[0].zDatabase);
79429 if( !pTab || db->mallocFailed ) goto exit_create_index;
79430 assert( db->aDb[iDb].pSchema==pTab->pSchema );
79431 }else{
79432 assert( pName==0 );
79433 pTab = pParse->pNewTable;
79434 if( !pTab ) goto exit_create_index;
79435 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79437 pDb = &db->aDb[iDb];
79439 assert( pTab!=0 );
79440 assert( pParse->nErr==0 );
79441 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
79442 && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
79443 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
79444 goto exit_create_index;
79446 #ifndef SQLITE_OMIT_VIEW
79447 if( pTab->pSelect ){
79448 sqlite3ErrorMsg(pParse, "views may not be indexed");
79449 goto exit_create_index;
79451 #endif
79452 #ifndef SQLITE_OMIT_VIRTUALTABLE
79453 if( IsVirtual(pTab) ){
79454 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
79455 goto exit_create_index;
79457 #endif
79460 ** Find the name of the index. Make sure there is not already another
79461 ** index or table with the same name.
79463 ** Exception: If we are reading the names of permanent indices from the
79464 ** sqlite_master table (because some other process changed the schema) and
79465 ** one of the index names collides with the name of a temporary table or
79466 ** index, then we will continue to process this index.
79468 ** If pName==0 it means that we are
79469 ** dealing with a primary key or UNIQUE constraint. We have to invent our
79470 ** own name.
79472 if( pName ){
79473 zName = sqlite3NameFromToken(db, pName);
79474 if( zName==0 ) goto exit_create_index;
79475 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
79476 goto exit_create_index;
79478 if( !db->init.busy ){
79479 if( sqlite3FindTable(db, zName, 0)!=0 ){
79480 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
79481 goto exit_create_index;
79484 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
79485 if( !ifNotExist ){
79486 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
79487 }else{
79488 assert( !db->init.busy );
79489 sqlite3CodeVerifySchema(pParse, iDb);
79491 goto exit_create_index;
79493 }else{
79494 int n;
79495 Index *pLoop;
79496 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
79497 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
79498 if( zName==0 ){
79499 goto exit_create_index;
79503 /* Check for authorization to create an index.
79505 #ifndef SQLITE_OMIT_AUTHORIZATION
79507 const char *zDb = pDb->zName;
79508 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
79509 goto exit_create_index;
79511 i = SQLITE_CREATE_INDEX;
79512 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
79513 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
79514 goto exit_create_index;
79517 #endif
79519 /* If pList==0, it means this routine was called to make a primary
79520 ** key out of the last column added to the table under construction.
79521 ** So create a fake list to simulate this.
79523 if( pList==0 ){
79524 nullId.z = pTab->aCol[pTab->nCol-1].zName;
79525 nullId.n = sqlite3Strlen30((char*)nullId.z);
79526 pList = sqlite3ExprListAppend(pParse, 0, 0);
79527 if( pList==0 ) goto exit_create_index;
79528 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
79529 pList->a[0].sortOrder = (u8)sortOrder;
79532 /* Figure out how many bytes of space are required to store explicitly
79533 ** specified collation sequence names.
79535 for(i=0; i<pList->nExpr; i++){
79536 Expr *pExpr = pList->a[i].pExpr;
79537 if( pExpr ){
79538 CollSeq *pColl = pExpr->pColl;
79539 /* Either pColl!=0 or there was an OOM failure. But if an OOM
79540 ** failure we have quit before reaching this point. */
79541 if( ALWAYS(pColl) ){
79542 nExtra += (1 + sqlite3Strlen30(pColl->zName));
79548 ** Allocate the index structure.
79550 nName = sqlite3Strlen30(zName);
79551 nCol = pList->nExpr;
79552 pIndex = sqlite3DbMallocZero(db,
79553 sizeof(Index) + /* Index structure */
79554 sizeof(int)*nCol + /* Index.aiColumn */
79555 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
79556 sizeof(char *)*nCol + /* Index.azColl */
79557 sizeof(u8)*nCol + /* Index.aSortOrder */
79558 nName + 1 + /* Index.zName */
79559 nExtra /* Collation sequence names */
79561 if( db->mallocFailed ){
79562 goto exit_create_index;
79564 pIndex->azColl = (char**)(&pIndex[1]);
79565 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
79566 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
79567 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
79568 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
79569 zExtra = (char *)(&pIndex->zName[nName+1]);
79570 memcpy(pIndex->zName, zName, nName+1);
79571 pIndex->pTable = pTab;
79572 pIndex->nColumn = pList->nExpr;
79573 pIndex->onError = (u8)onError;
79574 pIndex->autoIndex = (u8)(pName==0);
79575 pIndex->pSchema = db->aDb[iDb].pSchema;
79576 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79578 /* Check to see if we should honor DESC requests on index columns
79580 if( pDb->pSchema->file_format>=4 ){
79581 sortOrderMask = -1; /* Honor DESC */
79582 }else{
79583 sortOrderMask = 0; /* Ignore DESC */
79586 /* Scan the names of the columns of the table to be indexed and
79587 ** load the column indices into the Index structure. Report an error
79588 ** if any column is not found.
79590 ** TODO: Add a test to make sure that the same column is not named
79591 ** more than once within the same index. Only the first instance of
79592 ** the column will ever be used by the optimizer. Note that using the
79593 ** same column more than once cannot be an error because that would
79594 ** break backwards compatibility - it needs to be a warning.
79596 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
79597 const char *zColName = pListItem->zName;
79598 Column *pTabCol;
79599 int requestedSortOrder;
79600 char *zColl; /* Collation sequence name */
79602 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
79603 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
79605 if( j>=pTab->nCol ){
79606 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
79607 pTab->zName, zColName);
79608 pParse->checkSchema = 1;
79609 goto exit_create_index;
79611 pIndex->aiColumn[i] = j;
79612 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
79613 ** the way the "idxlist" non-terminal is constructed by the parser,
79614 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
79615 ** must exist or else there must have been an OOM error. But if there
79616 ** was an OOM error, we would never reach this point. */
79617 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
79618 int nColl;
79619 zColl = pListItem->pExpr->pColl->zName;
79620 nColl = sqlite3Strlen30(zColl) + 1;
79621 assert( nExtra>=nColl );
79622 memcpy(zExtra, zColl, nColl);
79623 zColl = zExtra;
79624 zExtra += nColl;
79625 nExtra -= nColl;
79626 }else{
79627 zColl = pTab->aCol[j].zColl;
79628 if( !zColl ){
79629 zColl = db->pDfltColl->zName;
79632 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
79633 goto exit_create_index;
79635 pIndex->azColl[i] = zColl;
79636 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
79637 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
79639 sqlite3DefaultRowEst(pIndex);
79641 if( pTab==pParse->pNewTable ){
79642 /* This routine has been called to create an automatic index as a
79643 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
79644 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
79645 ** i.e. one of:
79647 ** CREATE TABLE t(x PRIMARY KEY, y);
79648 ** CREATE TABLE t(x, y, UNIQUE(x, y));
79650 ** Either way, check to see if the table already has such an index. If
79651 ** so, don't bother creating this one. This only applies to
79652 ** automatically created indices. Users can do as they wish with
79653 ** explicit indices.
79655 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
79656 ** (and thus suppressing the second one) even if they have different
79657 ** sort orders.
79659 ** If there are different collating sequences or if the columns of
79660 ** the constraint occur in different orders, then the constraints are
79661 ** considered distinct and both result in separate indices.
79663 Index *pIdx;
79664 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79665 int k;
79666 assert( pIdx->onError!=OE_None );
79667 assert( pIdx->autoIndex );
79668 assert( pIndex->onError!=OE_None );
79670 if( pIdx->nColumn!=pIndex->nColumn ) continue;
79671 for(k=0; k<pIdx->nColumn; k++){
79672 const char *z1;
79673 const char *z2;
79674 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
79675 z1 = pIdx->azColl[k];
79676 z2 = pIndex->azColl[k];
79677 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
79679 if( k==pIdx->nColumn ){
79680 if( pIdx->onError!=pIndex->onError ){
79681 /* This constraint creates the same index as a previous
79682 ** constraint specified somewhere in the CREATE TABLE statement.
79683 ** However the ON CONFLICT clauses are different. If both this
79684 ** constraint and the previous equivalent constraint have explicit
79685 ** ON CONFLICT clauses this is an error. Otherwise, use the
79686 ** explicitly specified behaviour for the index.
79688 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
79689 sqlite3ErrorMsg(pParse,
79690 "conflicting ON CONFLICT clauses specified", 0);
79692 if( pIdx->onError==OE_Default ){
79693 pIdx->onError = pIndex->onError;
79696 goto exit_create_index;
79701 /* Link the new Index structure to its table and to the other
79702 ** in-memory database structures.
79704 if( db->init.busy ){
79705 Index *p;
79706 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
79707 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
79708 pIndex->zName, sqlite3Strlen30(pIndex->zName),
79709 pIndex);
79710 if( p ){
79711 assert( p==pIndex ); /* Malloc must have failed */
79712 db->mallocFailed = 1;
79713 goto exit_create_index;
79715 db->flags |= SQLITE_InternChanges;
79716 if( pTblName!=0 ){
79717 pIndex->tnum = db->init.newTnum;
79721 /* If the db->init.busy is 0 then create the index on disk. This
79722 ** involves writing the index into the master table and filling in the
79723 ** index with the current table contents.
79725 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
79726 ** command. db->init.busy is 1 when a database is opened and
79727 ** CREATE INDEX statements are read out of the master table. In
79728 ** the latter case the index already exists on disk, which is why
79729 ** we don't want to recreate it.
79731 ** If pTblName==0 it means this index is generated as a primary key
79732 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
79733 ** has just been created, it contains no data and the index initialization
79734 ** step can be skipped.
79736 else{ /* if( db->init.busy==0 ) */
79737 Vdbe *v;
79738 char *zStmt;
79739 int iMem = ++pParse->nMem;
79741 v = sqlite3GetVdbe(pParse);
79742 if( v==0 ) goto exit_create_index;
79745 /* Create the rootpage for the index
79747 sqlite3BeginWriteOperation(pParse, 1, iDb);
79748 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
79750 /* Gather the complete text of the CREATE INDEX statement into
79751 ** the zStmt variable
79753 if( pStart ){
79754 assert( pEnd!=0 );
79755 /* A named index with an explicit CREATE INDEX statement */
79756 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
79757 onError==OE_None ? "" : " UNIQUE",
79758 pEnd->z - pName->z + 1,
79759 pName->z);
79760 }else{
79761 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
79762 /* zStmt = sqlite3MPrintf(""); */
79763 zStmt = 0;
79766 /* Add an entry in sqlite_master for this index
79768 sqlite3NestedParse(pParse,
79769 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
79770 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
79771 pIndex->zName,
79772 pTab->zName,
79773 iMem,
79774 zStmt
79776 sqlite3DbFree(db, zStmt);
79778 /* Fill the index with data and reparse the schema. Code an OP_Expire
79779 ** to invalidate all pre-compiled statements.
79781 if( pTblName ){
79782 sqlite3RefillIndex(pParse, pIndex, iMem);
79783 sqlite3ChangeCookie(pParse, iDb);
79784 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
79785 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName),
79786 P4_DYNAMIC);
79787 sqlite3VdbeAddOp1(v, OP_Expire, 0);
79791 /* When adding an index to the list of indices for a table, make
79792 ** sure all indices labeled OE_Replace come after all those labeled
79793 ** OE_Ignore. This is necessary for the correct constraint check
79794 ** processing (in sqlite3GenerateConstraintChecks()) as part of
79795 ** UPDATE and INSERT statements.
79797 if( db->init.busy || pTblName==0 ){
79798 if( onError!=OE_Replace || pTab->pIndex==0
79799 || pTab->pIndex->onError==OE_Replace){
79800 pIndex->pNext = pTab->pIndex;
79801 pTab->pIndex = pIndex;
79802 }else{
79803 Index *pOther = pTab->pIndex;
79804 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
79805 pOther = pOther->pNext;
79807 pIndex->pNext = pOther->pNext;
79808 pOther->pNext = pIndex;
79810 pRet = pIndex;
79811 pIndex = 0;
79814 /* Clean up before exiting */
79815 exit_create_index:
79816 if( pIndex ){
79817 sqlite3DbFree(db, pIndex->zColAff);
79818 sqlite3DbFree(db, pIndex);
79820 sqlite3ExprListDelete(db, pList);
79821 sqlite3SrcListDelete(db, pTblName);
79822 sqlite3DbFree(db, zName);
79823 return pRet;
79827 ** Fill the Index.aiRowEst[] array with default information - information
79828 ** to be used when we have not run the ANALYZE command.
79830 ** aiRowEst[0] is suppose to contain the number of elements in the index.
79831 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
79832 ** number of rows in the table that match any particular value of the
79833 ** first column of the index. aiRowEst[2] is an estimate of the number
79834 ** of rows that match any particular combiniation of the first 2 columns
79835 ** of the index. And so forth. It must always be the case that
79837 ** aiRowEst[N]<=aiRowEst[N-1]
79838 ** aiRowEst[N]>=1
79840 ** Apart from that, we have little to go on besides intuition as to
79841 ** how aiRowEst[] should be initialized. The numbers generated here
79842 ** are based on typical values found in actual indices.
79844 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
79845 unsigned *a = pIdx->aiRowEst;
79846 int i;
79847 unsigned n;
79848 assert( a!=0 );
79849 a[0] = pIdx->pTable->nRowEst;
79850 if( a[0]<10 ) a[0] = 10;
79851 n = 10;
79852 for(i=1; i<=pIdx->nColumn; i++){
79853 a[i] = n;
79854 if( n>5 ) n--;
79856 if( pIdx->onError!=OE_None ){
79857 a[pIdx->nColumn] = 1;
79862 ** This routine will drop an existing named index. This routine
79863 ** implements the DROP INDEX statement.
79865 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
79866 Index *pIndex;
79867 Vdbe *v;
79868 sqlite3 *db = pParse->db;
79869 int iDb;
79871 assert( pParse->nErr==0 ); /* Never called with prior errors */
79872 if( db->mallocFailed ){
79873 goto exit_drop_index;
79875 assert( pName->nSrc==1 );
79876 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79877 goto exit_drop_index;
79879 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
79880 if( pIndex==0 ){
79881 if( !ifExists ){
79882 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
79883 }else{
79884 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
79886 pParse->checkSchema = 1;
79887 goto exit_drop_index;
79889 if( pIndex->autoIndex ){
79890 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
79891 "or PRIMARY KEY constraint cannot be dropped", 0);
79892 goto exit_drop_index;
79894 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
79895 #ifndef SQLITE_OMIT_AUTHORIZATION
79897 int code = SQLITE_DROP_INDEX;
79898 Table *pTab = pIndex->pTable;
79899 const char *zDb = db->aDb[iDb].zName;
79900 const char *zTab = SCHEMA_TABLE(iDb);
79901 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
79902 goto exit_drop_index;
79904 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
79905 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
79906 goto exit_drop_index;
79909 #endif
79911 /* Generate code to remove the index and from the master table */
79912 v = sqlite3GetVdbe(pParse);
79913 if( v ){
79914 sqlite3BeginWriteOperation(pParse, 1, iDb);
79915 sqlite3NestedParse(pParse,
79916 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
79917 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
79918 pIndex->zName
79920 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
79921 sqlite3NestedParse(pParse,
79922 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
79923 db->aDb[iDb].zName, pIndex->zName
79926 sqlite3ChangeCookie(pParse, iDb);
79927 destroyRootPage(pParse, pIndex->tnum, iDb);
79928 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
79931 exit_drop_index:
79932 sqlite3SrcListDelete(db, pName);
79936 ** pArray is a pointer to an array of objects. Each object in the
79937 ** array is szEntry bytes in size. This routine allocates a new
79938 ** object on the end of the array.
79940 ** *pnEntry is the number of entries already in use. *pnAlloc is
79941 ** the previously allocated size of the array. initSize is the
79942 ** suggested initial array size allocation.
79944 ** The index of the new entry is returned in *pIdx.
79946 ** This routine returns a pointer to the array of objects. This
79947 ** might be the same as the pArray parameter or it might be a different
79948 ** pointer if the array was resized.
79950 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
79951 sqlite3 *db, /* Connection to notify of malloc failures */
79952 void *pArray, /* Array of objects. Might be reallocated */
79953 int szEntry, /* Size of each object in the array */
79954 int initSize, /* Suggested initial allocation, in elements */
79955 int *pnEntry, /* Number of objects currently in use */
79956 int *pnAlloc, /* Current size of the allocation, in elements */
79957 int *pIdx /* Write the index of a new slot here */
79959 char *z;
79960 if( *pnEntry >= *pnAlloc ){
79961 void *pNew;
79962 int newSize;
79963 newSize = (*pnAlloc)*2 + initSize;
79964 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
79965 if( pNew==0 ){
79966 *pIdx = -1;
79967 return pArray;
79969 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
79970 pArray = pNew;
79972 z = (char*)pArray;
79973 memset(&z[*pnEntry * szEntry], 0, szEntry);
79974 *pIdx = *pnEntry;
79975 ++*pnEntry;
79976 return pArray;
79980 ** Append a new element to the given IdList. Create a new IdList if
79981 ** need be.
79983 ** A new IdList is returned, or NULL if malloc() fails.
79985 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
79986 int i;
79987 if( pList==0 ){
79988 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
79989 if( pList==0 ) return 0;
79990 pList->nAlloc = 0;
79992 pList->a = sqlite3ArrayAllocate(
79994 pList->a,
79995 sizeof(pList->a[0]),
79997 &pList->nId,
79998 &pList->nAlloc,
80001 if( i<0 ){
80002 sqlite3IdListDelete(db, pList);
80003 return 0;
80005 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
80006 return pList;
80010 ** Delete an IdList.
80012 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
80013 int i;
80014 if( pList==0 ) return;
80015 for(i=0; i<pList->nId; i++){
80016 sqlite3DbFree(db, pList->a[i].zName);
80018 sqlite3DbFree(db, pList->a);
80019 sqlite3DbFree(db, pList);
80023 ** Return the index in pList of the identifier named zId. Return -1
80024 ** if not found.
80026 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
80027 int i;
80028 if( pList==0 ) return -1;
80029 for(i=0; i<pList->nId; i++){
80030 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
80032 return -1;
80036 ** Expand the space allocated for the given SrcList object by
80037 ** creating nExtra new slots beginning at iStart. iStart is zero based.
80038 ** New slots are zeroed.
80040 ** For example, suppose a SrcList initially contains two entries: A,B.
80041 ** To append 3 new entries onto the end, do this:
80043 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
80045 ** After the call above it would contain: A, B, nil, nil, nil.
80046 ** If the iStart argument had been 1 instead of 2, then the result
80047 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
80048 ** the iStart value would be 0. The result then would
80049 ** be: nil, nil, nil, A, B.
80051 ** If a memory allocation fails the SrcList is unchanged. The
80052 ** db->mallocFailed flag will be set to true.
80054 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
80055 sqlite3 *db, /* Database connection to notify of OOM errors */
80056 SrcList *pSrc, /* The SrcList to be enlarged */
80057 int nExtra, /* Number of new slots to add to pSrc->a[] */
80058 int iStart /* Index in pSrc->a[] of first new slot */
80060 int i;
80062 /* Sanity checking on calling parameters */
80063 assert( iStart>=0 );
80064 assert( nExtra>=1 );
80065 assert( pSrc!=0 );
80066 assert( iStart<=pSrc->nSrc );
80068 /* Allocate additional space if needed */
80069 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
80070 SrcList *pNew;
80071 int nAlloc = pSrc->nSrc+nExtra;
80072 int nGot;
80073 pNew = sqlite3DbRealloc(db, pSrc,
80074 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
80075 if( pNew==0 ){
80076 assert( db->mallocFailed );
80077 return pSrc;
80079 pSrc = pNew;
80080 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
80081 pSrc->nAlloc = (u16)nGot;
80084 /* Move existing slots that come after the newly inserted slots
80085 ** out of the way */
80086 for(i=pSrc->nSrc-1; i>=iStart; i--){
80087 pSrc->a[i+nExtra] = pSrc->a[i];
80089 pSrc->nSrc += (i16)nExtra;
80091 /* Zero the newly allocated slots */
80092 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
80093 for(i=iStart; i<iStart+nExtra; i++){
80094 pSrc->a[i].iCursor = -1;
80097 /* Return a pointer to the enlarged SrcList */
80098 return pSrc;
80103 ** Append a new table name to the given SrcList. Create a new SrcList if
80104 ** need be. A new entry is created in the SrcList even if pTable is NULL.
80106 ** A SrcList is returned, or NULL if there is an OOM error. The returned
80107 ** SrcList might be the same as the SrcList that was input or it might be
80108 ** a new one. If an OOM error does occurs, then the prior value of pList
80109 ** that is input to this routine is automatically freed.
80111 ** If pDatabase is not null, it means that the table has an optional
80112 ** database name prefix. Like this: "database.table". The pDatabase
80113 ** points to the table name and the pTable points to the database name.
80114 ** The SrcList.a[].zName field is filled with the table name which might
80115 ** come from pTable (if pDatabase is NULL) or from pDatabase.
80116 ** SrcList.a[].zDatabase is filled with the database name from pTable,
80117 ** or with NULL if no database is specified.
80119 ** In other words, if call like this:
80121 ** sqlite3SrcListAppend(D,A,B,0);
80123 ** Then B is a table name and the database name is unspecified. If called
80124 ** like this:
80126 ** sqlite3SrcListAppend(D,A,B,C);
80128 ** Then C is the table name and B is the database name. If C is defined
80129 ** then so is B. In other words, we never have a case where:
80131 ** sqlite3SrcListAppend(D,A,0,C);
80133 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
80134 ** before being added to the SrcList.
80136 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
80137 sqlite3 *db, /* Connection to notify of malloc failures */
80138 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
80139 Token *pTable, /* Table to append */
80140 Token *pDatabase /* Database of the table */
80142 struct SrcList_item *pItem;
80143 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
80144 if( pList==0 ){
80145 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
80146 if( pList==0 ) return 0;
80147 pList->nAlloc = 1;
80149 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
80150 if( db->mallocFailed ){
80151 sqlite3SrcListDelete(db, pList);
80152 return 0;
80154 pItem = &pList->a[pList->nSrc-1];
80155 if( pDatabase && pDatabase->z==0 ){
80156 pDatabase = 0;
80158 if( pDatabase ){
80159 Token *pTemp = pDatabase;
80160 pDatabase = pTable;
80161 pTable = pTemp;
80163 pItem->zName = sqlite3NameFromToken(db, pTable);
80164 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
80165 return pList;
80169 ** Assign VdbeCursor index numbers to all tables in a SrcList
80171 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
80172 int i;
80173 struct SrcList_item *pItem;
80174 assert(pList || pParse->db->mallocFailed );
80175 if( pList ){
80176 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
80177 if( pItem->iCursor>=0 ) break;
80178 pItem->iCursor = pParse->nTab++;
80179 if( pItem->pSelect ){
80180 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
80187 ** Delete an entire SrcList including all its substructure.
80189 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
80190 int i;
80191 struct SrcList_item *pItem;
80192 if( pList==0 ) return;
80193 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
80194 sqlite3DbFree(db, pItem->zDatabase);
80195 sqlite3DbFree(db, pItem->zName);
80196 sqlite3DbFree(db, pItem->zAlias);
80197 sqlite3DbFree(db, pItem->zIndex);
80198 sqlite3DeleteTable(db, pItem->pTab);
80199 sqlite3SelectDelete(db, pItem->pSelect);
80200 sqlite3ExprDelete(db, pItem->pOn);
80201 sqlite3IdListDelete(db, pItem->pUsing);
80203 sqlite3DbFree(db, pList);
80207 ** This routine is called by the parser to add a new term to the
80208 ** end of a growing FROM clause. The "p" parameter is the part of
80209 ** the FROM clause that has already been constructed. "p" is NULL
80210 ** if this is the first term of the FROM clause. pTable and pDatabase
80211 ** are the name of the table and database named in the FROM clause term.
80212 ** pDatabase is NULL if the database name qualifier is missing - the
80213 ** usual case. If the term has a alias, then pAlias points to the
80214 ** alias token. If the term is a subquery, then pSubquery is the
80215 ** SELECT statement that the subquery encodes. The pTable and
80216 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
80217 ** parameters are the content of the ON and USING clauses.
80219 ** Return a new SrcList which encodes is the FROM with the new
80220 ** term added.
80222 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
80223 Parse *pParse, /* Parsing context */
80224 SrcList *p, /* The left part of the FROM clause already seen */
80225 Token *pTable, /* Name of the table to add to the FROM clause */
80226 Token *pDatabase, /* Name of the database containing pTable */
80227 Token *pAlias, /* The right-hand side of the AS subexpression */
80228 Select *pSubquery, /* A subquery used in place of a table name */
80229 Expr *pOn, /* The ON clause of a join */
80230 IdList *pUsing /* The USING clause of a join */
80232 struct SrcList_item *pItem;
80233 sqlite3 *db = pParse->db;
80234 if( !p && (pOn || pUsing) ){
80235 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
80236 (pOn ? "ON" : "USING")
80238 goto append_from_error;
80240 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
80241 if( p==0 || NEVER(p->nSrc==0) ){
80242 goto append_from_error;
80244 pItem = &p->a[p->nSrc-1];
80245 assert( pAlias!=0 );
80246 if( pAlias->n ){
80247 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
80249 pItem->pSelect = pSubquery;
80250 pItem->pOn = pOn;
80251 pItem->pUsing = pUsing;
80252 return p;
80254 append_from_error:
80255 assert( p==0 );
80256 sqlite3ExprDelete(db, pOn);
80257 sqlite3IdListDelete(db, pUsing);
80258 sqlite3SelectDelete(db, pSubquery);
80259 return 0;
80263 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
80264 ** element of the source-list passed as the second argument.
80266 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
80267 assert( pIndexedBy!=0 );
80268 if( p && ALWAYS(p->nSrc>0) ){
80269 struct SrcList_item *pItem = &p->a[p->nSrc-1];
80270 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
80271 if( pIndexedBy->n==1 && !pIndexedBy->z ){
80272 /* A "NOT INDEXED" clause was supplied. See parse.y
80273 ** construct "indexed_opt" for details. */
80274 pItem->notIndexed = 1;
80275 }else{
80276 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
80282 ** When building up a FROM clause in the parser, the join operator
80283 ** is initially attached to the left operand. But the code generator
80284 ** expects the join operator to be on the right operand. This routine
80285 ** Shifts all join operators from left to right for an entire FROM
80286 ** clause.
80288 ** Example: Suppose the join is like this:
80290 ** A natural cross join B
80292 ** The operator is "natural cross join". The A and B operands are stored
80293 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
80294 ** operator with A. This routine shifts that operator over to B.
80296 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
80297 if( p && p->a ){
80298 int i;
80299 for(i=p->nSrc-1; i>0; i--){
80300 p->a[i].jointype = p->a[i-1].jointype;
80302 p->a[0].jointype = 0;
80307 ** Begin a transaction
80309 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
80310 sqlite3 *db;
80311 Vdbe *v;
80312 int i;
80314 assert( pParse!=0 );
80315 db = pParse->db;
80316 assert( db!=0 );
80317 /* if( db->aDb[0].pBt==0 ) return; */
80318 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
80319 return;
80321 v = sqlite3GetVdbe(pParse);
80322 if( !v ) return;
80323 if( type!=TK_DEFERRED ){
80324 for(i=0; i<db->nDb; i++){
80325 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
80326 sqlite3VdbeUsesBtree(v, i);
80329 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
80333 ** Commit a transaction
80335 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
80336 sqlite3 *db;
80337 Vdbe *v;
80339 assert( pParse!=0 );
80340 db = pParse->db;
80341 assert( db!=0 );
80342 /* if( db->aDb[0].pBt==0 ) return; */
80343 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
80344 return;
80346 v = sqlite3GetVdbe(pParse);
80347 if( v ){
80348 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
80353 ** Rollback a transaction
80355 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
80356 sqlite3 *db;
80357 Vdbe *v;
80359 assert( pParse!=0 );
80360 db = pParse->db;
80361 assert( db!=0 );
80362 /* if( db->aDb[0].pBt==0 ) return; */
80363 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
80364 return;
80366 v = sqlite3GetVdbe(pParse);
80367 if( v ){
80368 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
80373 ** This function is called by the parser when it parses a command to create,
80374 ** release or rollback an SQL savepoint.
80376 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
80377 char *zName = sqlite3NameFromToken(pParse->db, pName);
80378 if( zName ){
80379 Vdbe *v = sqlite3GetVdbe(pParse);
80380 #ifndef SQLITE_OMIT_AUTHORIZATION
80381 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
80382 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
80383 #endif
80384 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
80385 sqlite3DbFree(pParse->db, zName);
80386 return;
80388 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
80393 ** Make sure the TEMP database is open and available for use. Return
80394 ** the number of errors. Leave any error messages in the pParse structure.
80396 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
80397 sqlite3 *db = pParse->db;
80398 if( db->aDb[1].pBt==0 && !pParse->explain ){
80399 int rc;
80400 Btree *pBt;
80401 static const int flags =
80402 SQLITE_OPEN_READWRITE |
80403 SQLITE_OPEN_CREATE |
80404 SQLITE_OPEN_EXCLUSIVE |
80405 SQLITE_OPEN_DELETEONCLOSE |
80406 SQLITE_OPEN_TEMP_DB;
80408 rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
80409 if( rc!=SQLITE_OK ){
80410 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
80411 "file for storing temporary tables");
80412 pParse->rc = rc;
80413 return 1;
80415 db->aDb[1].pBt = pBt;
80416 assert( db->aDb[1].pSchema );
80417 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
80418 db->mallocFailed = 1;
80419 return 1;
80422 return 0;
80426 ** Generate VDBE code that will verify the schema cookie and start
80427 ** a read-transaction for all named database files.
80429 ** It is important that all schema cookies be verified and all
80430 ** read transactions be started before anything else happens in
80431 ** the VDBE program. But this routine can be called after much other
80432 ** code has been generated. So here is what we do:
80434 ** The first time this routine is called, we code an OP_Goto that
80435 ** will jump to a subroutine at the end of the program. Then we
80436 ** record every database that needs its schema verified in the
80437 ** pParse->cookieMask field. Later, after all other code has been
80438 ** generated, the subroutine that does the cookie verifications and
80439 ** starts the transactions will be coded and the OP_Goto P2 value
80440 ** will be made to point to that subroutine. The generation of the
80441 ** cookie verification subroutine code happens in sqlite3FinishCoding().
80443 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
80444 ** schema on any databases. This can be used to position the OP_Goto
80445 ** early in the code, before we know if any database tables will be used.
80447 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
80448 Parse *pToplevel = sqlite3ParseToplevel(pParse);
80450 if( pToplevel->cookieGoto==0 ){
80451 Vdbe *v = sqlite3GetVdbe(pToplevel);
80452 if( v==0 ) return; /* This only happens if there was a prior error */
80453 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
80455 if( iDb>=0 ){
80456 sqlite3 *db = pToplevel->db;
80457 yDbMask mask;
80459 assert( iDb<db->nDb );
80460 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
80461 assert( iDb<SQLITE_MAX_ATTACHED+2 );
80462 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80463 mask = ((yDbMask)1)<<iDb;
80464 if( (pToplevel->cookieMask & mask)==0 ){
80465 pToplevel->cookieMask |= mask;
80466 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
80467 if( !OMIT_TEMPDB && iDb==1 ){
80468 sqlite3OpenTempDatabase(pToplevel);
80475 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
80476 ** attached database. Otherwise, invoke it for the database named zDb only.
80478 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
80479 sqlite3 *db = pParse->db;
80480 int i;
80481 for(i=0; i<db->nDb; i++){
80482 Db *pDb = &db->aDb[i];
80483 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
80484 sqlite3CodeVerifySchema(pParse, i);
80490 ** Generate VDBE code that prepares for doing an operation that
80491 ** might change the database.
80493 ** This routine starts a new transaction if we are not already within
80494 ** a transaction. If we are already within a transaction, then a checkpoint
80495 ** is set if the setStatement parameter is true. A checkpoint should
80496 ** be set for operations that might fail (due to a constraint) part of
80497 ** the way through and which will need to undo some writes without having to
80498 ** rollback the whole transaction. For operations where all constraints
80499 ** can be checked before any changes are made to the database, it is never
80500 ** necessary to undo a write and the checkpoint should not be set.
80502 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
80503 Parse *pToplevel = sqlite3ParseToplevel(pParse);
80504 sqlite3CodeVerifySchema(pParse, iDb);
80505 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
80506 pToplevel->isMultiWrite |= setStatement;
80510 ** Indicate that the statement currently under construction might write
80511 ** more than one entry (example: deleting one row then inserting another,
80512 ** inserting multiple rows in a table, or inserting a row and index entries.)
80513 ** If an abort occurs after some of these writes have completed, then it will
80514 ** be necessary to undo the completed writes.
80516 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
80517 Parse *pToplevel = sqlite3ParseToplevel(pParse);
80518 pToplevel->isMultiWrite = 1;
80522 ** The code generator calls this routine if is discovers that it is
80523 ** possible to abort a statement prior to completion. In order to
80524 ** perform this abort without corrupting the database, we need to make
80525 ** sure that the statement is protected by a statement transaction.
80527 ** Technically, we only need to set the mayAbort flag if the
80528 ** isMultiWrite flag was previously set. There is a time dependency
80529 ** such that the abort must occur after the multiwrite. This makes
80530 ** some statements involving the REPLACE conflict resolution algorithm
80531 ** go a little faster. But taking advantage of this time dependency
80532 ** makes it more difficult to prove that the code is correct (in
80533 ** particular, it prevents us from writing an effective
80534 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
80535 ** to take the safe route and skip the optimization.
80537 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
80538 Parse *pToplevel = sqlite3ParseToplevel(pParse);
80539 pToplevel->mayAbort = 1;
80543 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
80544 ** error. The onError parameter determines which (if any) of the statement
80545 ** and/or current transaction is rolled back.
80547 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
80548 Vdbe *v = sqlite3GetVdbe(pParse);
80549 if( onError==OE_Abort ){
80550 sqlite3MayAbort(pParse);
80552 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
80556 ** Check to see if pIndex uses the collating sequence pColl. Return
80557 ** true if it does and false if it does not.
80559 #ifndef SQLITE_OMIT_REINDEX
80560 static int collationMatch(const char *zColl, Index *pIndex){
80561 int i;
80562 assert( zColl!=0 );
80563 for(i=0; i<pIndex->nColumn; i++){
80564 const char *z = pIndex->azColl[i];
80565 assert( z!=0 );
80566 if( 0==sqlite3StrICmp(z, zColl) ){
80567 return 1;
80570 return 0;
80572 #endif
80575 ** Recompute all indices of pTab that use the collating sequence pColl.
80576 ** If pColl==0 then recompute all indices of pTab.
80578 #ifndef SQLITE_OMIT_REINDEX
80579 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
80580 Index *pIndex; /* An index associated with pTab */
80582 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
80583 if( zColl==0 || collationMatch(zColl, pIndex) ){
80584 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80585 sqlite3BeginWriteOperation(pParse, 0, iDb);
80586 sqlite3RefillIndex(pParse, pIndex, -1);
80590 #endif
80593 ** Recompute all indices of all tables in all databases where the
80594 ** indices use the collating sequence pColl. If pColl==0 then recompute
80595 ** all indices everywhere.
80597 #ifndef SQLITE_OMIT_REINDEX
80598 static void reindexDatabases(Parse *pParse, char const *zColl){
80599 Db *pDb; /* A single database */
80600 int iDb; /* The database index number */
80601 sqlite3 *db = pParse->db; /* The database connection */
80602 HashElem *k; /* For looping over tables in pDb */
80603 Table *pTab; /* A table in the database */
80605 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
80606 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
80607 assert( pDb!=0 );
80608 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
80609 pTab = (Table*)sqliteHashData(k);
80610 reindexTable(pParse, pTab, zColl);
80614 #endif
80617 ** Generate code for the REINDEX command.
80619 ** REINDEX -- 1
80620 ** REINDEX <collation> -- 2
80621 ** REINDEX ?<database>.?<tablename> -- 3
80622 ** REINDEX ?<database>.?<indexname> -- 4
80624 ** Form 1 causes all indices in all attached databases to be rebuilt.
80625 ** Form 2 rebuilds all indices in all databases that use the named
80626 ** collating function. Forms 3 and 4 rebuild the named index or all
80627 ** indices associated with the named table.
80629 #ifndef SQLITE_OMIT_REINDEX
80630 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
80631 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
80632 char *z; /* Name of a table or index */
80633 const char *zDb; /* Name of the database */
80634 Table *pTab; /* A table in the database */
80635 Index *pIndex; /* An index associated with pTab */
80636 int iDb; /* The database index number */
80637 sqlite3 *db = pParse->db; /* The database connection */
80638 Token *pObjName; /* Name of the table or index to be reindexed */
80640 /* Read the database schema. If an error occurs, leave an error message
80641 ** and code in pParse and return NULL. */
80642 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
80643 return;
80646 if( pName1==0 ){
80647 reindexDatabases(pParse, 0);
80648 return;
80649 }else if( NEVER(pName2==0) || pName2->z==0 ){
80650 char *zColl;
80651 assert( pName1->z );
80652 zColl = sqlite3NameFromToken(pParse->db, pName1);
80653 if( !zColl ) return;
80654 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
80655 if( pColl ){
80656 reindexDatabases(pParse, zColl);
80657 sqlite3DbFree(db, zColl);
80658 return;
80660 sqlite3DbFree(db, zColl);
80662 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
80663 if( iDb<0 ) return;
80664 z = sqlite3NameFromToken(db, pObjName);
80665 if( z==0 ) return;
80666 zDb = db->aDb[iDb].zName;
80667 pTab = sqlite3FindTable(db, z, zDb);
80668 if( pTab ){
80669 reindexTable(pParse, pTab, 0);
80670 sqlite3DbFree(db, z);
80671 return;
80673 pIndex = sqlite3FindIndex(db, z, zDb);
80674 sqlite3DbFree(db, z);
80675 if( pIndex ){
80676 sqlite3BeginWriteOperation(pParse, 0, iDb);
80677 sqlite3RefillIndex(pParse, pIndex, -1);
80678 return;
80680 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
80682 #endif
80685 ** Return a dynamicly allocated KeyInfo structure that can be used
80686 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
80688 ** If successful, a pointer to the new structure is returned. In this case
80689 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
80690 ** pointer. If an error occurs (out of memory or missing collation
80691 ** sequence), NULL is returned and the state of pParse updated to reflect
80692 ** the error.
80694 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
80695 int i;
80696 int nCol = pIdx->nColumn;
80697 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
80698 sqlite3 *db = pParse->db;
80699 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
80701 if( pKey ){
80702 pKey->db = pParse->db;
80703 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
80704 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
80705 for(i=0; i<nCol; i++){
80706 char *zColl = pIdx->azColl[i];
80707 assert( zColl );
80708 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
80709 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
80711 pKey->nField = (u16)nCol;
80714 if( pParse->nErr ){
80715 sqlite3DbFree(db, pKey);
80716 pKey = 0;
80718 return pKey;
80721 /* Begin preload-cache.patch for Chromium */
80722 /* See declaration in sqlite3.h for information */
80723 SQLITE_API int sqlite3_preload(sqlite3 *db)
80725 Pager *pPager;
80726 Btree *pBt;
80727 int rc;
80728 int i;
80729 int dbsLoaded = 0;
80731 for(i=0; i<db->nDb; i++) {
80732 pBt = db->aDb[i].pBt;
80733 if( !pBt )
80734 continue;
80735 pPager = sqlite3BtreePager(pBt);
80736 if( pPager ) {
80737 rc = sqlite3PagerLoadall(pPager);
80738 if (rc == SQLITE_OK)
80739 dbsLoaded++;
80742 if (dbsLoaded == 0)
80743 return SQLITE_ERROR;
80744 return SQLITE_OK;
80746 /* End preload-cache.patch for Chromium */
80748 /************** End of build.c ***********************************************/
80749 /************** Begin file callback.c ****************************************/
80751 ** 2005 May 23
80753 ** The author disclaims copyright to this source code. In place of
80754 ** a legal notice, here is a blessing:
80756 ** May you do good and not evil.
80757 ** May you find forgiveness for yourself and forgive others.
80758 ** May you share freely, never taking more than you give.
80760 *************************************************************************
80762 ** This file contains functions used to access the internal hash tables
80763 ** of user defined functions and collation sequences.
80768 ** Invoke the 'collation needed' callback to request a collation sequence
80769 ** in the encoding enc of name zName, length nName.
80771 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
80772 assert( !db->xCollNeeded || !db->xCollNeeded16 );
80773 if( db->xCollNeeded ){
80774 char *zExternal = sqlite3DbStrDup(db, zName);
80775 if( !zExternal ) return;
80776 db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
80777 sqlite3DbFree(db, zExternal);
80779 #ifndef SQLITE_OMIT_UTF16
80780 if( db->xCollNeeded16 ){
80781 char const *zExternal;
80782 sqlite3_value *pTmp = sqlite3ValueNew(db);
80783 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
80784 zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
80785 if( zExternal ){
80786 db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
80788 sqlite3ValueFree(pTmp);
80790 #endif
80794 ** This routine is called if the collation factory fails to deliver a
80795 ** collation function in the best encoding but there may be other versions
80796 ** of this collation function (for other text encodings) available. Use one
80797 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
80798 ** possible.
80800 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
80801 CollSeq *pColl2;
80802 char *z = pColl->zName;
80803 int i;
80804 static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
80805 for(i=0; i<3; i++){
80806 pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
80807 if( pColl2->xCmp!=0 ){
80808 memcpy(pColl, pColl2, sizeof(CollSeq));
80809 pColl->xDel = 0; /* Do not copy the destructor */
80810 return SQLITE_OK;
80813 return SQLITE_ERROR;
80817 ** This function is responsible for invoking the collation factory callback
80818 ** or substituting a collation sequence of a different encoding when the
80819 ** requested collation sequence is not available in the desired encoding.
80821 ** If it is not NULL, then pColl must point to the database native encoding
80822 ** collation sequence with name zName, length nName.
80824 ** The return value is either the collation sequence to be used in database
80825 ** db for collation type name zName, length nName, or NULL, if no collation
80826 ** sequence can be found.
80828 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
80830 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
80831 sqlite3* db, /* The database connection */
80832 u8 enc, /* The desired encoding for the collating sequence */
80833 CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
80834 const char *zName /* Collating sequence name */
80836 CollSeq *p;
80838 p = pColl;
80839 if( !p ){
80840 p = sqlite3FindCollSeq(db, enc, zName, 0);
80842 if( !p || !p->xCmp ){
80843 /* No collation sequence of this type for this encoding is registered.
80844 ** Call the collation factory to see if it can supply us with one.
80846 callCollNeeded(db, enc, zName);
80847 p = sqlite3FindCollSeq(db, enc, zName, 0);
80849 if( p && !p->xCmp && synthCollSeq(db, p) ){
80850 p = 0;
80852 assert( !p || p->xCmp );
80853 return p;
80857 ** This routine is called on a collation sequence before it is used to
80858 ** check that it is defined. An undefined collation sequence exists when
80859 ** a database is loaded that contains references to collation sequences
80860 ** that have not been defined by sqlite3_create_collation() etc.
80862 ** If required, this routine calls the 'collation needed' callback to
80863 ** request a definition of the collating sequence. If this doesn't work,
80864 ** an equivalent collating sequence that uses a text encoding different
80865 ** from the main database is substituted, if one is available.
80867 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
80868 if( pColl ){
80869 const char *zName = pColl->zName;
80870 sqlite3 *db = pParse->db;
80871 CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
80872 if( !p ){
80873 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
80874 pParse->nErr++;
80875 return SQLITE_ERROR;
80877 assert( p==pColl );
80879 return SQLITE_OK;
80885 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
80886 ** specified by zName and nName is not found and parameter 'create' is
80887 ** true, then create a new entry. Otherwise return NULL.
80889 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
80890 ** array of three CollSeq structures. The first is the collation sequence
80891 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
80893 ** Stored immediately after the three collation sequences is a copy of
80894 ** the collation sequence name. A pointer to this string is stored in
80895 ** each collation sequence structure.
80897 static CollSeq *findCollSeqEntry(
80898 sqlite3 *db, /* Database connection */
80899 const char *zName, /* Name of the collating sequence */
80900 int create /* Create a new entry if true */
80902 CollSeq *pColl;
80903 int nName = sqlite3Strlen30(zName);
80904 pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
80906 if( 0==pColl && create ){
80907 pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
80908 if( pColl ){
80909 CollSeq *pDel = 0;
80910 pColl[0].zName = (char*)&pColl[3];
80911 pColl[0].enc = SQLITE_UTF8;
80912 pColl[1].zName = (char*)&pColl[3];
80913 pColl[1].enc = SQLITE_UTF16LE;
80914 pColl[2].zName = (char*)&pColl[3];
80915 pColl[2].enc = SQLITE_UTF16BE;
80916 memcpy(pColl[0].zName, zName, nName);
80917 pColl[0].zName[nName] = 0;
80918 pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
80920 /* If a malloc() failure occurred in sqlite3HashInsert(), it will
80921 ** return the pColl pointer to be deleted (because it wasn't added
80922 ** to the hash table).
80924 assert( pDel==0 || pDel==pColl );
80925 if( pDel!=0 ){
80926 db->mallocFailed = 1;
80927 sqlite3DbFree(db, pDel);
80928 pColl = 0;
80932 return pColl;
80936 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
80937 ** Return the CollSeq* pointer for the collation sequence named zName
80938 ** for the encoding 'enc' from the database 'db'.
80940 ** If the entry specified is not found and 'create' is true, then create a
80941 ** new entry. Otherwise return NULL.
80943 ** A separate function sqlite3LocateCollSeq() is a wrapper around
80944 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
80945 ** if necessary and generates an error message if the collating sequence
80946 ** cannot be found.
80948 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
80950 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
80951 sqlite3 *db,
80952 u8 enc,
80953 const char *zName,
80954 int create
80956 CollSeq *pColl;
80957 if( zName ){
80958 pColl = findCollSeqEntry(db, zName, create);
80959 }else{
80960 pColl = db->pDfltColl;
80962 assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
80963 assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
80964 if( pColl ) pColl += enc-1;
80965 return pColl;
80968 /* During the search for the best function definition, this procedure
80969 ** is called to test how well the function passed as the first argument
80970 ** matches the request for a function with nArg arguments in a system
80971 ** that uses encoding enc. The value returned indicates how well the
80972 ** request is matched. A higher value indicates a better match.
80974 ** The returned value is always between 0 and 6, as follows:
80976 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
80977 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
80978 ** encoding is requested, or vice versa.
80979 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
80980 ** requested, or vice versa.
80981 ** 3: A variable arguments function using the same text encoding.
80982 ** 4: A function with the exact number of arguments requested that
80983 ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
80984 ** 5: A function with the exact number of arguments requested that
80985 ** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
80986 ** 6: An exact match.
80989 static int matchQuality(FuncDef *p, int nArg, u8 enc){
80990 int match = 0;
80991 if( p->nArg==-1 || p->nArg==nArg
80992 || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
80994 match = 1;
80995 if( p->nArg==nArg || nArg==-1 ){
80996 match = 4;
80998 if( enc==p->iPrefEnc ){
80999 match += 2;
81001 else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
81002 (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
81003 match += 1;
81006 return match;
81010 ** Search a FuncDefHash for a function with the given name. Return
81011 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
81013 static FuncDef *functionSearch(
81014 FuncDefHash *pHash, /* Hash table to search */
81015 int h, /* Hash of the name */
81016 const char *zFunc, /* Name of function */
81017 int nFunc /* Number of bytes in zFunc */
81019 FuncDef *p;
81020 for(p=pHash->a[h]; p; p=p->pHash){
81021 if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
81022 return p;
81025 return 0;
81029 ** Insert a new FuncDef into a FuncDefHash hash table.
81031 SQLITE_PRIVATE void sqlite3FuncDefInsert(
81032 FuncDefHash *pHash, /* The hash table into which to insert */
81033 FuncDef *pDef /* The function definition to insert */
81035 FuncDef *pOther;
81036 int nName = sqlite3Strlen30(pDef->zName);
81037 u8 c1 = (u8)pDef->zName[0];
81038 int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
81039 pOther = functionSearch(pHash, h, pDef->zName, nName);
81040 if( pOther ){
81041 assert( pOther!=pDef && pOther->pNext!=pDef );
81042 pDef->pNext = pOther->pNext;
81043 pOther->pNext = pDef;
81044 }else{
81045 pDef->pNext = 0;
81046 pDef->pHash = pHash->a[h];
81047 pHash->a[h] = pDef;
81054 ** Locate a user function given a name, a number of arguments and a flag
81055 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
81056 ** pointer to the FuncDef structure that defines that function, or return
81057 ** NULL if the function does not exist.
81059 ** If the createFlag argument is true, then a new (blank) FuncDef
81060 ** structure is created and liked into the "db" structure if a
81061 ** no matching function previously existed. When createFlag is true
81062 ** and the nArg parameter is -1, then only a function that accepts
81063 ** any number of arguments will be returned.
81065 ** If createFlag is false and nArg is -1, then the first valid
81066 ** function found is returned. A function is valid if either xFunc
81067 ** or xStep is non-zero.
81069 ** If createFlag is false, then a function with the required name and
81070 ** number of arguments may be returned even if the eTextRep flag does not
81071 ** match that requested.
81073 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
81074 sqlite3 *db, /* An open database */
81075 const char *zName, /* Name of the function. Not null-terminated */
81076 int nName, /* Number of characters in the name */
81077 int nArg, /* Number of arguments. -1 means any number */
81078 u8 enc, /* Preferred text encoding */
81079 int createFlag /* Create new entry if true and does not otherwise exist */
81081 FuncDef *p; /* Iterator variable */
81082 FuncDef *pBest = 0; /* Best match found so far */
81083 int bestScore = 0; /* Score of best match */
81084 int h; /* Hash value */
81087 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
81088 h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
81090 /* First search for a match amongst the application-defined functions.
81092 p = functionSearch(&db->aFunc, h, zName, nName);
81093 while( p ){
81094 int score = matchQuality(p, nArg, enc);
81095 if( score>bestScore ){
81096 pBest = p;
81097 bestScore = score;
81099 p = p->pNext;
81102 /* If no match is found, search the built-in functions.
81104 ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
81105 ** functions even if a prior app-defined function was found. And give
81106 ** priority to built-in functions.
81108 ** Except, if createFlag is true, that means that we are trying to
81109 ** install a new function. Whatever FuncDef structure is returned it will
81110 ** have fields overwritten with new information appropriate for the
81111 ** new function. But the FuncDefs for built-in functions are read-only.
81112 ** So we must not search for built-ins when creating a new function.
81114 if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
81115 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
81116 bestScore = 0;
81117 p = functionSearch(pHash, h, zName, nName);
81118 while( p ){
81119 int score = matchQuality(p, nArg, enc);
81120 if( score>bestScore ){
81121 pBest = p;
81122 bestScore = score;
81124 p = p->pNext;
81128 /* If the createFlag parameter is true and the search did not reveal an
81129 ** exact match for the name, number of arguments and encoding, then add a
81130 ** new entry to the hash table and return it.
81132 if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
81133 (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
81134 pBest->zName = (char *)&pBest[1];
81135 pBest->nArg = (u16)nArg;
81136 pBest->iPrefEnc = enc;
81137 memcpy(pBest->zName, zName, nName);
81138 pBest->zName[nName] = 0;
81139 sqlite3FuncDefInsert(&db->aFunc, pBest);
81142 if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
81143 return pBest;
81145 return 0;
81149 ** Free all resources held by the schema structure. The void* argument points
81150 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
81151 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
81152 ** of the schema hash tables).
81154 ** The Schema.cache_size variable is not cleared.
81156 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
81157 Hash temp1;
81158 Hash temp2;
81159 HashElem *pElem;
81160 Schema *pSchema = (Schema *)p;
81162 temp1 = pSchema->tblHash;
81163 temp2 = pSchema->trigHash;
81164 sqlite3HashInit(&pSchema->trigHash);
81165 sqlite3HashClear(&pSchema->idxHash);
81166 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
81167 sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
81169 sqlite3HashClear(&temp2);
81170 sqlite3HashInit(&pSchema->tblHash);
81171 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
81172 Table *pTab = sqliteHashData(pElem);
81173 sqlite3DeleteTable(0, pTab);
81175 sqlite3HashClear(&temp1);
81176 sqlite3HashClear(&pSchema->fkeyHash);
81177 pSchema->pSeqTab = 0;
81178 if( pSchema->flags & DB_SchemaLoaded ){
81179 pSchema->iGeneration++;
81180 pSchema->flags &= ~DB_SchemaLoaded;
81185 ** Find and return the schema associated with a BTree. Create
81186 ** a new one if necessary.
81188 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
81189 Schema * p;
81190 if( pBt ){
81191 p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
81192 }else{
81193 p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
81195 if( !p ){
81196 db->mallocFailed = 1;
81197 }else if ( 0==p->file_format ){
81198 sqlite3HashInit(&p->tblHash);
81199 sqlite3HashInit(&p->idxHash);
81200 sqlite3HashInit(&p->trigHash);
81201 sqlite3HashInit(&p->fkeyHash);
81202 p->enc = SQLITE_UTF8;
81204 return p;
81207 /************** End of callback.c ********************************************/
81208 /************** Begin file delete.c ******************************************/
81210 ** 2001 September 15
81212 ** The author disclaims copyright to this source code. In place of
81213 ** a legal notice, here is a blessing:
81215 ** May you do good and not evil.
81216 ** May you find forgiveness for yourself and forgive others.
81217 ** May you share freely, never taking more than you give.
81219 *************************************************************************
81220 ** This file contains C code routines that are called by the parser
81221 ** in order to generate code for DELETE FROM statements.
81225 ** While a SrcList can in general represent multiple tables and subqueries
81226 ** (as in the FROM clause of a SELECT statement) in this case it contains
81227 ** the name of a single table, as one might find in an INSERT, DELETE,
81228 ** or UPDATE statement. Look up that table in the symbol table and
81229 ** return a pointer. Set an error message and return NULL if the table
81230 ** name is not found or if any other error occurs.
81232 ** The following fields are initialized appropriate in pSrc:
81234 ** pSrc->a[0].pTab Pointer to the Table object
81235 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
81238 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
81239 struct SrcList_item *pItem = pSrc->a;
81240 Table *pTab;
81241 assert( pItem && pSrc->nSrc==1 );
81242 pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
81243 sqlite3DeleteTable(pParse->db, pItem->pTab);
81244 pItem->pTab = pTab;
81245 if( pTab ){
81246 pTab->nRef++;
81248 if( sqlite3IndexedByLookup(pParse, pItem) ){
81249 pTab = 0;
81251 return pTab;
81255 ** Check to make sure the given table is writable. If it is not
81256 ** writable, generate an error message and return 1. If it is
81257 ** writable return 0;
81259 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
81260 /* A table is not writable under the following circumstances:
81262 ** 1) It is a virtual table and no implementation of the xUpdate method
81263 ** has been provided, or
81264 ** 2) It is a system table (i.e. sqlite_master), this call is not
81265 ** part of a nested parse and writable_schema pragma has not
81266 ** been specified.
81268 ** In either case leave an error message in pParse and return non-zero.
81270 if( ( IsVirtual(pTab)
81271 && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
81272 || ( (pTab->tabFlags & TF_Readonly)!=0
81273 && (pParse->db->flags & SQLITE_WriteSchema)==0
81274 && pParse->nested==0 )
81276 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
81277 return 1;
81280 #ifndef SQLITE_OMIT_VIEW
81281 if( !viewOk && pTab->pSelect ){
81282 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
81283 return 1;
81285 #endif
81286 return 0;
81290 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81292 ** Evaluate a view and store its result in an ephemeral table. The
81293 ** pWhere argument is an optional WHERE clause that restricts the
81294 ** set of rows in the view that are to be added to the ephemeral table.
81296 SQLITE_PRIVATE void sqlite3MaterializeView(
81297 Parse *pParse, /* Parsing context */
81298 Table *pView, /* View definition */
81299 Expr *pWhere, /* Optional WHERE clause to be added */
81300 int iCur /* Cursor number for ephemerial table */
81302 SelectDest dest;
81303 Select *pDup;
81304 sqlite3 *db = pParse->db;
81306 pDup = sqlite3SelectDup(db, pView->pSelect, 0);
81307 if( pWhere ){
81308 SrcList *pFrom;
81310 pWhere = sqlite3ExprDup(db, pWhere, 0);
81311 pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
81312 if( pFrom ){
81313 assert( pFrom->nSrc==1 );
81314 pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
81315 pFrom->a[0].pSelect = pDup;
81316 assert( pFrom->a[0].pOn==0 );
81317 assert( pFrom->a[0].pUsing==0 );
81318 }else{
81319 sqlite3SelectDelete(db, pDup);
81321 pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
81323 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
81324 sqlite3Select(pParse, pDup, &dest);
81325 sqlite3SelectDelete(db, pDup);
81327 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
81329 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
81331 ** Generate an expression tree to implement the WHERE, ORDER BY,
81332 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
81334 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
81335 ** \__________________________/
81336 ** pLimitWhere (pInClause)
81338 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
81339 Parse *pParse, /* The parser context */
81340 SrcList *pSrc, /* the FROM clause -- which tables to scan */
81341 Expr *pWhere, /* The WHERE clause. May be null */
81342 ExprList *pOrderBy, /* The ORDER BY clause. May be null */
81343 Expr *pLimit, /* The LIMIT clause. May be null */
81344 Expr *pOffset, /* The OFFSET clause. May be null */
81345 char *zStmtType /* Either DELETE or UPDATE. For error messages. */
81347 Expr *pWhereRowid = NULL; /* WHERE rowid .. */
81348 Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
81349 Expr *pSelectRowid = NULL; /* SELECT rowid ... */
81350 ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
81351 SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
81352 Select *pSelect = NULL; /* Complete SELECT tree */
81354 /* Check that there isn't an ORDER BY without a LIMIT clause.
81356 if( pOrderBy && (pLimit == 0) ) {
81357 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
81358 pParse->parseError = 1;
81359 goto limit_where_cleanup_2;
81362 /* We only need to generate a select expression if there
81363 ** is a limit/offset term to enforce.
81365 if( pLimit == 0 ) {
81366 /* if pLimit is null, pOffset will always be null as well. */
81367 assert( pOffset == 0 );
81368 return pWhere;
81371 /* Generate a select expression tree to enforce the limit/offset
81372 ** term for the DELETE or UPDATE statement. For example:
81373 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81374 ** becomes:
81375 ** DELETE FROM table_a WHERE rowid IN (
81376 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81377 ** );
81380 pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81381 if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
81382 pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
81383 if( pEList == 0 ) goto limit_where_cleanup_2;
81385 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
81386 ** and the SELECT subtree. */
81387 pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
81388 if( pSelectSrc == 0 ) {
81389 sqlite3ExprListDelete(pParse->db, pEList);
81390 goto limit_where_cleanup_2;
81393 /* generate the SELECT expression tree. */
81394 pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
81395 pOrderBy,0,pLimit,pOffset);
81396 if( pSelect == 0 ) return 0;
81398 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
81399 pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81400 if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
81401 pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
81402 if( pInClause == 0 ) goto limit_where_cleanup_1;
81404 pInClause->x.pSelect = pSelect;
81405 pInClause->flags |= EP_xIsSelect;
81406 sqlite3ExprSetHeight(pParse, pInClause);
81407 return pInClause;
81409 /* something went wrong. clean up anything allocated. */
81410 limit_where_cleanup_1:
81411 sqlite3SelectDelete(pParse->db, pSelect);
81412 return 0;
81414 limit_where_cleanup_2:
81415 sqlite3ExprDelete(pParse->db, pWhere);
81416 sqlite3ExprListDelete(pParse->db, pOrderBy);
81417 sqlite3ExprDelete(pParse->db, pLimit);
81418 sqlite3ExprDelete(pParse->db, pOffset);
81419 return 0;
81421 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
81424 ** Generate code for a DELETE FROM statement.
81426 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
81427 ** \________/ \________________/
81428 ** pTabList pWhere
81430 SQLITE_PRIVATE void sqlite3DeleteFrom(
81431 Parse *pParse, /* The parser context */
81432 SrcList *pTabList, /* The table from which we should delete things */
81433 Expr *pWhere /* The WHERE clause. May be null */
81435 Vdbe *v; /* The virtual database engine */
81436 Table *pTab; /* The table from which records will be deleted */
81437 const char *zDb; /* Name of database holding pTab */
81438 int end, addr = 0; /* A couple addresses of generated code */
81439 int i; /* Loop counter */
81440 WhereInfo *pWInfo; /* Information about the WHERE clause */
81441 Index *pIdx; /* For looping over indices of the table */
81442 int iCur; /* VDBE Cursor number for pTab */
81443 sqlite3 *db; /* Main database structure */
81444 AuthContext sContext; /* Authorization context */
81445 NameContext sNC; /* Name context to resolve expressions in */
81446 int iDb; /* Database number */
81447 int memCnt = -1; /* Memory cell used for change counting */
81448 int rcauth; /* Value returned by authorization callback */
81450 #ifndef SQLITE_OMIT_TRIGGER
81451 int isView; /* True if attempting to delete from a view */
81452 Trigger *pTrigger; /* List of table triggers, if required */
81453 #endif
81455 memset(&sContext, 0, sizeof(sContext));
81456 db = pParse->db;
81457 if( pParse->nErr || db->mallocFailed ){
81458 goto delete_from_cleanup;
81460 assert( pTabList->nSrc==1 );
81462 /* Locate the table which we want to delete. This table has to be
81463 ** put in an SrcList structure because some of the subroutines we
81464 ** will be calling are designed to work with multiple tables and expect
81465 ** an SrcList* parameter instead of just a Table* parameter.
81467 pTab = sqlite3SrcListLookup(pParse, pTabList);
81468 if( pTab==0 ) goto delete_from_cleanup;
81470 /* Figure out if we have any triggers and if the table being
81471 ** deleted from is a view
81473 #ifndef SQLITE_OMIT_TRIGGER
81474 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81475 isView = pTab->pSelect!=0;
81476 #else
81477 # define pTrigger 0
81478 # define isView 0
81479 #endif
81480 #ifdef SQLITE_OMIT_VIEW
81481 # undef isView
81482 # define isView 0
81483 #endif
81485 /* If pTab is really a view, make sure it has been initialized.
81487 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
81488 goto delete_from_cleanup;
81491 if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
81492 goto delete_from_cleanup;
81494 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81495 assert( iDb<db->nDb );
81496 zDb = db->aDb[iDb].zName;
81497 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
81498 assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
81499 if( rcauth==SQLITE_DENY ){
81500 goto delete_from_cleanup;
81502 assert(!isView || pTrigger);
81504 /* Assign cursor number to the table and all its indices.
81506 assert( pTabList->nSrc==1 );
81507 iCur = pTabList->a[0].iCursor = pParse->nTab++;
81508 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81509 pParse->nTab++;
81512 /* Start the view context
81514 if( isView ){
81515 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
81518 /* Begin generating code.
81520 v = sqlite3GetVdbe(pParse);
81521 if( v==0 ){
81522 goto delete_from_cleanup;
81524 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
81525 sqlite3BeginWriteOperation(pParse, 1, iDb);
81527 /* If we are trying to delete from a view, realize that view into
81528 ** a ephemeral table.
81530 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81531 if( isView ){
81532 sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
81534 #endif
81536 /* Resolve the column names in the WHERE clause.
81538 memset(&sNC, 0, sizeof(sNC));
81539 sNC.pParse = pParse;
81540 sNC.pSrcList = pTabList;
81541 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
81542 goto delete_from_cleanup;
81545 /* Initialize the counter of the number of rows deleted, if
81546 ** we are counting rows.
81548 if( db->flags & SQLITE_CountRows ){
81549 memCnt = ++pParse->nMem;
81550 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
81553 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
81554 /* Special case: A DELETE without a WHERE clause deletes everything.
81555 ** It is easier just to erase the whole table. Prior to version 3.6.5,
81556 ** this optimization caused the row change count (the value returned by
81557 ** API function sqlite3_count_changes) to be set incorrectly. */
81558 if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
81559 && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
81561 assert( !isView );
81562 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
81563 pTab->zName, P4_STATIC);
81564 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81565 assert( pIdx->pSchema==pTab->pSchema );
81566 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
81568 }else
81569 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
81570 /* The usual case: There is a WHERE clause so we have to scan through
81571 ** the table and pick which records to delete.
81574 int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
81575 int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
81576 int regRowid; /* Actual register containing rowids */
81578 /* Collect rowids of every row to be deleted.
81580 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
81581 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
81582 if( pWInfo==0 ) goto delete_from_cleanup;
81583 regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
81584 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
81585 if( db->flags & SQLITE_CountRows ){
81586 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
81588 sqlite3WhereEnd(pWInfo);
81590 /* Delete every item whose key was written to the list during the
81591 ** database scan. We have to delete items after the scan is complete
81592 ** because deleting an item can change the scan order. */
81593 end = sqlite3VdbeMakeLabel(v);
81595 /* Unless this is a view, open cursors for the table we are
81596 ** deleting from and all its indices. If this is a view, then the
81597 ** only effect this statement has is to fire the INSTEAD OF
81598 ** triggers. */
81599 if( !isView ){
81600 sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
81603 addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
81605 /* Delete the row */
81606 #ifndef SQLITE_OMIT_VIRTUALTABLE
81607 if( IsVirtual(pTab) ){
81608 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
81609 sqlite3VtabMakeWritable(pParse, pTab);
81610 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
81611 sqlite3MayAbort(pParse);
81612 }else
81613 #endif
81615 int count = (pParse->nested==0); /* True to count changes */
81616 sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
81619 /* End of the delete loop */
81620 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
81621 sqlite3VdbeResolveLabel(v, end);
81623 /* Close the cursors open on the table and its indexes. */
81624 if( !isView && !IsVirtual(pTab) ){
81625 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
81626 sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
81628 sqlite3VdbeAddOp1(v, OP_Close, iCur);
81632 /* Update the sqlite_sequence table by storing the content of the
81633 ** maximum rowid counter values recorded while inserting into
81634 ** autoincrement tables.
81636 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
81637 sqlite3AutoincrementEnd(pParse);
81640 /* Return the number of rows that were deleted. If this routine is
81641 ** generating code because of a call to sqlite3NestedParse(), do not
81642 ** invoke the callback function.
81644 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
81645 sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
81646 sqlite3VdbeSetNumCols(v, 1);
81647 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
81650 delete_from_cleanup:
81651 sqlite3AuthContextPop(&sContext);
81652 sqlite3SrcListDelete(db, pTabList);
81653 sqlite3ExprDelete(db, pWhere);
81654 return;
81656 /* Make sure "isView" and other macros defined above are undefined. Otherwise
81657 ** thely may interfere with compilation of other functions in this file
81658 ** (or in another file, if this file becomes part of the amalgamation). */
81659 #ifdef isView
81660 #undef isView
81661 #endif
81662 #ifdef pTrigger
81663 #undef pTrigger
81664 #endif
81667 ** This routine generates VDBE code that causes a single row of a
81668 ** single table to be deleted.
81670 ** The VDBE must be in a particular state when this routine is called.
81671 ** These are the requirements:
81673 ** 1. A read/write cursor pointing to pTab, the table containing the row
81674 ** to be deleted, must be opened as cursor number $iCur.
81676 ** 2. Read/write cursors for all indices of pTab must be open as
81677 ** cursor number base+i for the i-th index.
81679 ** 3. The record number of the row to be deleted must be stored in
81680 ** memory cell iRowid.
81682 ** This routine generates code to remove both the table record and all
81683 ** index entries that point to that record.
81685 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
81686 Parse *pParse, /* Parsing context */
81687 Table *pTab, /* Table containing the row to be deleted */
81688 int iCur, /* Cursor number for the table */
81689 int iRowid, /* Memory cell that contains the rowid to delete */
81690 int count, /* If non-zero, increment the row change counter */
81691 Trigger *pTrigger, /* List of triggers to (potentially) fire */
81692 int onconf /* Default ON CONFLICT policy for triggers */
81694 Vdbe *v = pParse->pVdbe; /* Vdbe */
81695 int iOld = 0; /* First register in OLD.* array */
81696 int iLabel; /* Label resolved to end of generated code */
81698 /* Vdbe is guaranteed to have been allocated by this stage. */
81699 assert( v );
81701 /* Seek cursor iCur to the row to delete. If this row no longer exists
81702 ** (this can happen if a trigger program has already deleted it), do
81703 ** not attempt to delete it or fire any DELETE triggers. */
81704 iLabel = sqlite3VdbeMakeLabel(v);
81705 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
81707 /* If there are any triggers to fire, allocate a range of registers to
81708 ** use for the old.* references in the triggers. */
81709 if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
81710 u32 mask; /* Mask of OLD.* columns in use */
81711 int iCol; /* Iterator used while populating OLD.* */
81713 /* TODO: Could use temporary registers here. Also could attempt to
81714 ** avoid copying the contents of the rowid register. */
81715 mask = sqlite3TriggerColmask(
81716 pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
81718 mask |= sqlite3FkOldmask(pParse, pTab);
81719 iOld = pParse->nMem+1;
81720 pParse->nMem += (1 + pTab->nCol);
81722 /* Populate the OLD.* pseudo-table register array. These values will be
81723 ** used by any BEFORE and AFTER triggers that exist. */
81724 sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
81725 for(iCol=0; iCol<pTab->nCol; iCol++){
81726 if( mask==0xffffffff || mask&(1<<iCol) ){
81727 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
81731 /* Invoke BEFORE DELETE trigger programs. */
81732 sqlite3CodeRowTrigger(pParse, pTrigger,
81733 TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
81736 /* Seek the cursor to the row to be deleted again. It may be that
81737 ** the BEFORE triggers coded above have already removed the row
81738 ** being deleted. Do not attempt to delete the row a second time, and
81739 ** do not fire AFTER triggers. */
81740 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
81742 /* Do FK processing. This call checks that any FK constraints that
81743 ** refer to this table (i.e. constraints attached to other tables)
81744 ** are not violated by deleting this row. */
81745 sqlite3FkCheck(pParse, pTab, iOld, 0);
81748 /* Delete the index and table entries. Skip this step if pTab is really
81749 ** a view (in which case the only effect of the DELETE statement is to
81750 ** fire the INSTEAD OF triggers). */
81751 if( pTab->pSelect==0 ){
81752 sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
81753 sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
81754 if( count ){
81755 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
81759 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
81760 ** handle rows (possibly in other tables) that refer via a foreign key
81761 ** to the row just deleted. */
81762 sqlite3FkActions(pParse, pTab, 0, iOld);
81764 /* Invoke AFTER DELETE trigger programs. */
81765 sqlite3CodeRowTrigger(pParse, pTrigger,
81766 TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
81769 /* Jump here if the row had already been deleted before any BEFORE
81770 ** trigger programs were invoked. Or if a trigger program throws a
81771 ** RAISE(IGNORE) exception. */
81772 sqlite3VdbeResolveLabel(v, iLabel);
81776 ** This routine generates VDBE code that causes the deletion of all
81777 ** index entries associated with a single row of a single table.
81779 ** The VDBE must be in a particular state when this routine is called.
81780 ** These are the requirements:
81782 ** 1. A read/write cursor pointing to pTab, the table containing the row
81783 ** to be deleted, must be opened as cursor number "iCur".
81785 ** 2. Read/write cursors for all indices of pTab must be open as
81786 ** cursor number iCur+i for the i-th index.
81788 ** 3. The "iCur" cursor must be pointing to the row that is to be
81789 ** deleted.
81791 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
81792 Parse *pParse, /* Parsing and code generating context */
81793 Table *pTab, /* Table containing the row to be deleted */
81794 int iCur, /* Cursor number for the table */
81795 int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
81797 int i;
81798 Index *pIdx;
81799 int r1;
81801 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
81802 if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
81803 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
81804 sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
81809 ** Generate code that will assemble an index key and put it in register
81810 ** regOut. The key with be for index pIdx which is an index on pTab.
81811 ** iCur is the index of a cursor open on the pTab table and pointing to
81812 ** the entry that needs indexing.
81814 ** Return a register number which is the first in a block of
81815 ** registers that holds the elements of the index key. The
81816 ** block of registers has already been deallocated by the time
81817 ** this routine returns.
81819 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
81820 Parse *pParse, /* Parsing context */
81821 Index *pIdx, /* The index for which to generate a key */
81822 int iCur, /* Cursor number for the pIdx->pTable table */
81823 int regOut, /* Write the new index key to this register */
81824 int doMakeRec /* Run the OP_MakeRecord instruction if true */
81826 Vdbe *v = pParse->pVdbe;
81827 int j;
81828 Table *pTab = pIdx->pTable;
81829 int regBase;
81830 int nCol;
81832 nCol = pIdx->nColumn;
81833 regBase = sqlite3GetTempRange(pParse, nCol+1);
81834 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
81835 for(j=0; j<nCol; j++){
81836 int idx = pIdx->aiColumn[j];
81837 if( idx==pTab->iPKey ){
81838 sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
81839 }else{
81840 sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
81841 sqlite3ColumnDefault(v, pTab, idx, -1);
81844 if( doMakeRec ){
81845 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
81846 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
81848 sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
81849 return regBase;
81852 /************** End of delete.c **********************************************/
81853 /************** Begin file func.c ********************************************/
81855 ** 2002 February 23
81857 ** The author disclaims copyright to this source code. In place of
81858 ** a legal notice, here is a blessing:
81860 ** May you do good and not evil.
81861 ** May you find forgiveness for yourself and forgive others.
81862 ** May you share freely, never taking more than you give.
81864 *************************************************************************
81865 ** This file contains the C functions that implement various SQL
81866 ** functions of SQLite.
81868 ** There is only one exported symbol in this file - the function
81869 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
81870 ** All other code has file scope.
81874 ** Return the collating function associated with a function.
81876 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
81877 return context->pColl;
81881 ** Implementation of the non-aggregate min() and max() functions
81883 static void minmaxFunc(
81884 sqlite3_context *context,
81885 int argc,
81886 sqlite3_value **argv
81888 int i;
81889 int mask; /* 0 for min() or 0xffffffff for max() */
81890 int iBest;
81891 CollSeq *pColl;
81893 assert( argc>1 );
81894 mask = sqlite3_user_data(context)==0 ? 0 : -1;
81895 pColl = sqlite3GetFuncCollSeq(context);
81896 assert( pColl );
81897 assert( mask==-1 || mask==0 );
81898 iBest = 0;
81899 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
81900 for(i=1; i<argc; i++){
81901 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
81902 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
81903 testcase( mask==0 );
81904 iBest = i;
81907 sqlite3_result_value(context, argv[iBest]);
81911 ** Return the type of the argument.
81913 static void typeofFunc(
81914 sqlite3_context *context,
81915 int NotUsed,
81916 sqlite3_value **argv
81918 const char *z = 0;
81919 UNUSED_PARAMETER(NotUsed);
81920 switch( sqlite3_value_type(argv[0]) ){
81921 case SQLITE_INTEGER: z = "integer"; break;
81922 case SQLITE_TEXT: z = "text"; break;
81923 case SQLITE_FLOAT: z = "real"; break;
81924 case SQLITE_BLOB: z = "blob"; break;
81925 default: z = "null"; break;
81927 sqlite3_result_text(context, z, -1, SQLITE_STATIC);
81932 ** Implementation of the length() function
81934 static void lengthFunc(
81935 sqlite3_context *context,
81936 int argc,
81937 sqlite3_value **argv
81939 int len;
81941 assert( argc==1 );
81942 UNUSED_PARAMETER(argc);
81943 switch( sqlite3_value_type(argv[0]) ){
81944 case SQLITE_BLOB:
81945 case SQLITE_INTEGER:
81946 case SQLITE_FLOAT: {
81947 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
81948 break;
81950 case SQLITE_TEXT: {
81951 const unsigned char *z = sqlite3_value_text(argv[0]);
81952 if( z==0 ) return;
81953 len = 0;
81954 while( *z ){
81955 len++;
81956 SQLITE_SKIP_UTF8(z);
81958 sqlite3_result_int(context, len);
81959 break;
81961 default: {
81962 sqlite3_result_null(context);
81963 break;
81969 ** Implementation of the abs() function.
81971 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
81972 ** the numeric argument X.
81974 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
81975 assert( argc==1 );
81976 UNUSED_PARAMETER(argc);
81977 switch( sqlite3_value_type(argv[0]) ){
81978 case SQLITE_INTEGER: {
81979 i64 iVal = sqlite3_value_int64(argv[0]);
81980 if( iVal<0 ){
81981 if( (iVal<<1)==0 ){
81982 /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
81983 ** abs(X) throws an integer overflow error since there is no
81984 ** equivalent positive 64-bit two complement value. */
81985 sqlite3_result_error(context, "integer overflow", -1);
81986 return;
81988 iVal = -iVal;
81990 sqlite3_result_int64(context, iVal);
81991 break;
81993 case SQLITE_NULL: {
81994 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
81995 sqlite3_result_null(context);
81996 break;
81998 default: {
81999 /* Because sqlite3_value_double() returns 0.0 if the argument is not
82000 ** something that can be converted into a number, we have:
82001 ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
82002 ** cannot be converted to a numeric value.
82004 double rVal = sqlite3_value_double(argv[0]);
82005 if( rVal<0 ) rVal = -rVal;
82006 sqlite3_result_double(context, rVal);
82007 break;
82013 ** Implementation of the substr() function.
82015 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
82016 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
82017 ** of x. If x is text, then we actually count UTF-8 characters.
82018 ** If x is a blob, then we count bytes.
82020 ** If p1 is negative, then we begin abs(p1) from the end of x[].
82022 ** If p2 is negative, return the p2 characters preceeding p1.
82024 static void substrFunc(
82025 sqlite3_context *context,
82026 int argc,
82027 sqlite3_value **argv
82029 const unsigned char *z;
82030 const unsigned char *z2;
82031 int len;
82032 int p0type;
82033 i64 p1, p2;
82034 int negP2 = 0;
82036 assert( argc==3 || argc==2 );
82037 if( sqlite3_value_type(argv[1])==SQLITE_NULL
82038 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
82040 return;
82042 p0type = sqlite3_value_type(argv[0]);
82043 p1 = sqlite3_value_int(argv[1]);
82044 if( p0type==SQLITE_BLOB ){
82045 len = sqlite3_value_bytes(argv[0]);
82046 z = sqlite3_value_blob(argv[0]);
82047 if( z==0 ) return;
82048 assert( len==sqlite3_value_bytes(argv[0]) );
82049 }else{
82050 z = sqlite3_value_text(argv[0]);
82051 if( z==0 ) return;
82052 len = 0;
82053 if( p1<0 ){
82054 for(z2=z; *z2; len++){
82055 SQLITE_SKIP_UTF8(z2);
82059 if( argc==3 ){
82060 p2 = sqlite3_value_int(argv[2]);
82061 if( p2<0 ){
82062 p2 = -p2;
82063 negP2 = 1;
82065 }else{
82066 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
82068 if( p1<0 ){
82069 p1 += len;
82070 if( p1<0 ){
82071 p2 += p1;
82072 if( p2<0 ) p2 = 0;
82073 p1 = 0;
82075 }else if( p1>0 ){
82076 p1--;
82077 }else if( p2>0 ){
82078 p2--;
82080 if( negP2 ){
82081 p1 -= p2;
82082 if( p1<0 ){
82083 p2 += p1;
82084 p1 = 0;
82087 assert( p1>=0 && p2>=0 );
82088 if( p0type!=SQLITE_BLOB ){
82089 while( *z && p1 ){
82090 SQLITE_SKIP_UTF8(z);
82091 p1--;
82093 for(z2=z; *z2 && p2; p2--){
82094 SQLITE_SKIP_UTF8(z2);
82096 sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
82097 }else{
82098 if( p1+p2>len ){
82099 p2 = len-p1;
82100 if( p2<0 ) p2 = 0;
82102 sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
82107 ** Implementation of the round() function
82109 #ifndef SQLITE_OMIT_FLOATING_POINT
82110 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82111 int n = 0;
82112 double r;
82113 char *zBuf;
82114 assert( argc==1 || argc==2 );
82115 if( argc==2 ){
82116 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
82117 n = sqlite3_value_int(argv[1]);
82118 if( n>30 ) n = 30;
82119 if( n<0 ) n = 0;
82121 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
82122 r = sqlite3_value_double(argv[0]);
82123 /* If Y==0 and X will fit in a 64-bit int,
82124 ** handle the rounding directly,
82125 ** otherwise use printf.
82127 if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
82128 r = (double)((sqlite_int64)(r+0.5));
82129 }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
82130 r = -(double)((sqlite_int64)((-r)+0.5));
82131 }else{
82132 zBuf = sqlite3_mprintf("%.*f",n,r);
82133 if( zBuf==0 ){
82134 sqlite3_result_error_nomem(context);
82135 return;
82137 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
82138 sqlite3_free(zBuf);
82140 sqlite3_result_double(context, r);
82142 #endif
82145 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
82146 ** allocation fails, call sqlite3_result_error_nomem() to notify
82147 ** the database handle that malloc() has failed and return NULL.
82148 ** If nByte is larger than the maximum string or blob length, then
82149 ** raise an SQLITE_TOOBIG exception and return NULL.
82151 static void *contextMalloc(sqlite3_context *context, i64 nByte){
82152 char *z;
82153 sqlite3 *db = sqlite3_context_db_handle(context);
82154 assert( nByte>0 );
82155 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
82156 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
82157 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82158 sqlite3_result_error_toobig(context);
82159 z = 0;
82160 }else{
82161 z = sqlite3Malloc((int)nByte);
82162 if( !z ){
82163 sqlite3_result_error_nomem(context);
82166 return z;
82170 ** Implementation of the upper() and lower() SQL functions.
82172 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82173 char *z1;
82174 const char *z2;
82175 int i, n;
82176 UNUSED_PARAMETER(argc);
82177 z2 = (char*)sqlite3_value_text(argv[0]);
82178 n = sqlite3_value_bytes(argv[0]);
82179 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
82180 assert( z2==(char*)sqlite3_value_text(argv[0]) );
82181 if( z2 ){
82182 z1 = contextMalloc(context, ((i64)n)+1);
82183 if( z1 ){
82184 memcpy(z1, z2, n+1);
82185 for(i=0; z1[i]; i++){
82186 z1[i] = (char)sqlite3Toupper(z1[i]);
82188 sqlite3_result_text(context, z1, -1, sqlite3_free);
82192 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82193 u8 *z1;
82194 const char *z2;
82195 int i, n;
82196 UNUSED_PARAMETER(argc);
82197 z2 = (char*)sqlite3_value_text(argv[0]);
82198 n = sqlite3_value_bytes(argv[0]);
82199 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
82200 assert( z2==(char*)sqlite3_value_text(argv[0]) );
82201 if( z2 ){
82202 z1 = contextMalloc(context, ((i64)n)+1);
82203 if( z1 ){
82204 memcpy(z1, z2, n+1);
82205 for(i=0; z1[i]; i++){
82206 z1[i] = sqlite3Tolower(z1[i]);
82208 sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
82214 #if 0 /* This function is never used. */
82216 ** The COALESCE() and IFNULL() functions used to be implemented as shown
82217 ** here. But now they are implemented as VDBE code so that unused arguments
82218 ** do not have to be computed. This legacy implementation is retained as
82219 ** comment.
82222 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
82223 ** All three do the same thing. They return the first non-NULL
82224 ** argument.
82226 static void ifnullFunc(
82227 sqlite3_context *context,
82228 int argc,
82229 sqlite3_value **argv
82231 int i;
82232 for(i=0; i<argc; i++){
82233 if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
82234 sqlite3_result_value(context, argv[i]);
82235 break;
82239 #endif /* NOT USED */
82240 #define ifnullFunc versionFunc /* Substitute function - never called */
82243 ** Implementation of random(). Return a random integer.
82245 static void randomFunc(
82246 sqlite3_context *context,
82247 int NotUsed,
82248 sqlite3_value **NotUsed2
82250 sqlite_int64 r;
82251 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82252 sqlite3_randomness(sizeof(r), &r);
82253 if( r<0 ){
82254 /* We need to prevent a random number of 0x8000000000000000
82255 ** (or -9223372036854775808) since when you do abs() of that
82256 ** number of you get the same value back again. To do this
82257 ** in a way that is testable, mask the sign bit off of negative
82258 ** values, resulting in a positive value. Then take the
82259 ** 2s complement of that positive value. The end result can
82260 ** therefore be no less than -9223372036854775807.
82262 r = -(r ^ (((sqlite3_int64)1)<<63));
82264 sqlite3_result_int64(context, r);
82268 ** Implementation of randomblob(N). Return a random blob
82269 ** that is N bytes long.
82271 static void randomBlob(
82272 sqlite3_context *context,
82273 int argc,
82274 sqlite3_value **argv
82276 int n;
82277 unsigned char *p;
82278 assert( argc==1 );
82279 UNUSED_PARAMETER(argc);
82280 n = sqlite3_value_int(argv[0]);
82281 if( n<1 ){
82282 n = 1;
82284 p = contextMalloc(context, n);
82285 if( p ){
82286 sqlite3_randomness(n, p);
82287 sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
82292 ** Implementation of the last_insert_rowid() SQL function. The return
82293 ** value is the same as the sqlite3_last_insert_rowid() API function.
82295 static void last_insert_rowid(
82296 sqlite3_context *context,
82297 int NotUsed,
82298 sqlite3_value **NotUsed2
82300 sqlite3 *db = sqlite3_context_db_handle(context);
82301 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82302 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
82303 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
82304 ** function. */
82305 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
82309 ** Implementation of the changes() SQL function.
82311 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
82312 ** around the sqlite3_changes() C/C++ function and hence follows the same
82313 ** rules for counting changes.
82315 static void changes(
82316 sqlite3_context *context,
82317 int NotUsed,
82318 sqlite3_value **NotUsed2
82320 sqlite3 *db = sqlite3_context_db_handle(context);
82321 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82322 sqlite3_result_int(context, sqlite3_changes(db));
82326 ** Implementation of the total_changes() SQL function. The return value is
82327 ** the same as the sqlite3_total_changes() API function.
82329 static void total_changes(
82330 sqlite3_context *context,
82331 int NotUsed,
82332 sqlite3_value **NotUsed2
82334 sqlite3 *db = sqlite3_context_db_handle(context);
82335 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82336 /* IMP: R-52756-41993 This function is a wrapper around the
82337 ** sqlite3_total_changes() C/C++ interface. */
82338 sqlite3_result_int(context, sqlite3_total_changes(db));
82342 ** A structure defining how to do GLOB-style comparisons.
82344 struct compareInfo {
82345 u8 matchAll;
82346 u8 matchOne;
82347 u8 matchSet;
82348 u8 noCase;
82352 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
82353 ** character is exactly one byte in size. Also, all characters are
82354 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
82355 ** whereas only characters less than 0x80 do in ASCII.
82357 #if defined(SQLITE_EBCDIC)
82358 # define sqlite3Utf8Read(A,C) (*(A++))
82359 # define GlogUpperToLower(A) A = sqlite3UpperToLower[A]
82360 #else
82361 # define GlogUpperToLower(A) if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
82362 #endif
82364 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
82365 /* The correct SQL-92 behavior is for the LIKE operator to ignore
82366 ** case. Thus 'a' LIKE 'A' would be true. */
82367 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
82368 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
82369 ** is case sensitive causing 'a' LIKE 'A' to be false */
82370 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
82373 ** Compare two UTF-8 strings for equality where the first string can
82374 ** potentially be a "glob" expression. Return true (1) if they
82375 ** are the same and false (0) if they are different.
82377 ** Globbing rules:
82379 ** '*' Matches any sequence of zero or more characters.
82381 ** '?' Matches exactly one character.
82383 ** [...] Matches one character from the enclosed list of
82384 ** characters.
82386 ** [^...] Matches one character not in the enclosed list.
82388 ** With the [...] and [^...] matching, a ']' character can be included
82389 ** in the list by making it the first character after '[' or '^'. A
82390 ** range of characters can be specified using '-'. Example:
82391 ** "[a-z]" matches any single lower-case letter. To match a '-', make
82392 ** it the last character in the list.
82394 ** This routine is usually quick, but can be N**2 in the worst case.
82396 ** Hints: to match '*' or '?', put them in "[]". Like this:
82398 ** abc[*]xyz Matches "abc*xyz" only
82400 static int patternCompare(
82401 const u8 *zPattern, /* The glob pattern */
82402 const u8 *zString, /* The string to compare against the glob */
82403 const struct compareInfo *pInfo, /* Information about how to do the compare */
82404 const int esc /* The escape character */
82406 int c, c2;
82407 int invert;
82408 int seen;
82409 u8 matchOne = pInfo->matchOne;
82410 u8 matchAll = pInfo->matchAll;
82411 u8 matchSet = pInfo->matchSet;
82412 u8 noCase = pInfo->noCase;
82413 int prevEscape = 0; /* True if the previous character was 'escape' */
82415 while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
82416 if( !prevEscape && c==matchAll ){
82417 while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
82418 || c == matchOne ){
82419 if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
82420 return 0;
82423 if( c==0 ){
82424 return 1;
82425 }else if( c==esc ){
82426 c = sqlite3Utf8Read(zPattern, &zPattern);
82427 if( c==0 ){
82428 return 0;
82430 }else if( c==matchSet ){
82431 assert( esc==0 ); /* This is GLOB, not LIKE */
82432 assert( matchSet<0x80 ); /* '[' is a single-byte character */
82433 while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
82434 SQLITE_SKIP_UTF8(zString);
82436 return *zString!=0;
82438 while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
82439 if( noCase ){
82440 GlogUpperToLower(c2);
82441 GlogUpperToLower(c);
82442 while( c2 != 0 && c2 != c ){
82443 c2 = sqlite3Utf8Read(zString, &zString);
82444 GlogUpperToLower(c2);
82446 }else{
82447 while( c2 != 0 && c2 != c ){
82448 c2 = sqlite3Utf8Read(zString, &zString);
82451 if( c2==0 ) return 0;
82452 if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
82454 return 0;
82455 }else if( !prevEscape && c==matchOne ){
82456 if( sqlite3Utf8Read(zString, &zString)==0 ){
82457 return 0;
82459 }else if( c==matchSet ){
82460 int prior_c = 0;
82461 assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
82462 seen = 0;
82463 invert = 0;
82464 c = sqlite3Utf8Read(zString, &zString);
82465 if( c==0 ) return 0;
82466 c2 = sqlite3Utf8Read(zPattern, &zPattern);
82467 if( c2=='^' ){
82468 invert = 1;
82469 c2 = sqlite3Utf8Read(zPattern, &zPattern);
82471 if( c2==']' ){
82472 if( c==']' ) seen = 1;
82473 c2 = sqlite3Utf8Read(zPattern, &zPattern);
82475 while( c2 && c2!=']' ){
82476 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
82477 c2 = sqlite3Utf8Read(zPattern, &zPattern);
82478 if( c>=prior_c && c<=c2 ) seen = 1;
82479 prior_c = 0;
82480 }else{
82481 if( c==c2 ){
82482 seen = 1;
82484 prior_c = c2;
82486 c2 = sqlite3Utf8Read(zPattern, &zPattern);
82488 if( c2==0 || (seen ^ invert)==0 ){
82489 return 0;
82491 }else if( esc==c && !prevEscape ){
82492 prevEscape = 1;
82493 }else{
82494 c2 = sqlite3Utf8Read(zString, &zString);
82495 if( noCase ){
82496 GlogUpperToLower(c);
82497 GlogUpperToLower(c2);
82499 if( c!=c2 ){
82500 return 0;
82502 prevEscape = 0;
82505 return *zString==0;
82509 ** Count the number of times that the LIKE operator (or GLOB which is
82510 ** just a variation of LIKE) gets called. This is used for testing
82511 ** only.
82513 #ifdef SQLITE_TEST
82514 SQLITE_API int sqlite3_like_count = 0;
82515 #endif
82519 ** Implementation of the like() SQL function. This function implements
82520 ** the build-in LIKE operator. The first argument to the function is the
82521 ** pattern and the second argument is the string. So, the SQL statements:
82523 ** A LIKE B
82525 ** is implemented as like(B,A).
82527 ** This same function (with a different compareInfo structure) computes
82528 ** the GLOB operator.
82530 static void likeFunc(
82531 sqlite3_context *context,
82532 int argc,
82533 sqlite3_value **argv
82535 const unsigned char *zA, *zB;
82536 int escape = 0;
82537 int nPat;
82538 sqlite3 *db = sqlite3_context_db_handle(context);
82540 zB = sqlite3_value_text(argv[0]);
82541 zA = sqlite3_value_text(argv[1]);
82543 /* Limit the length of the LIKE or GLOB pattern to avoid problems
82544 ** of deep recursion and N*N behavior in patternCompare().
82546 nPat = sqlite3_value_bytes(argv[0]);
82547 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
82548 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
82549 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
82550 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
82551 return;
82553 assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
82555 if( argc==3 ){
82556 /* The escape character string must consist of a single UTF-8 character.
82557 ** Otherwise, return an error.
82559 const unsigned char *zEsc = sqlite3_value_text(argv[2]);
82560 if( zEsc==0 ) return;
82561 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
82562 sqlite3_result_error(context,
82563 "ESCAPE expression must be a single character", -1);
82564 return;
82566 escape = sqlite3Utf8Read(zEsc, &zEsc);
82568 if( zA && zB ){
82569 struct compareInfo *pInfo = sqlite3_user_data(context);
82570 #ifdef SQLITE_TEST
82571 sqlite3_like_count++;
82572 #endif
82574 sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
82579 ** Implementation of the NULLIF(x,y) function. The result is the first
82580 ** argument if the arguments are different. The result is NULL if the
82581 ** arguments are equal to each other.
82583 static void nullifFunc(
82584 sqlite3_context *context,
82585 int NotUsed,
82586 sqlite3_value **argv
82588 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
82589 UNUSED_PARAMETER(NotUsed);
82590 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
82591 sqlite3_result_value(context, argv[0]);
82596 ** Implementation of the sqlite_version() function. The result is the version
82597 ** of the SQLite library that is running.
82599 static void versionFunc(
82600 sqlite3_context *context,
82601 int NotUsed,
82602 sqlite3_value **NotUsed2
82604 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82605 /* IMP: R-48699-48617 This function is an SQL wrapper around the
82606 ** sqlite3_libversion() C-interface. */
82607 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
82611 ** Implementation of the sqlite_source_id() function. The result is a string
82612 ** that identifies the particular version of the source code used to build
82613 ** SQLite.
82615 static void sourceidFunc(
82616 sqlite3_context *context,
82617 int NotUsed,
82618 sqlite3_value **NotUsed2
82620 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82621 /* IMP: R-24470-31136 This function is an SQL wrapper around the
82622 ** sqlite3_sourceid() C interface. */
82623 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
82627 ** Implementation of the sqlite_compileoption_used() function.
82628 ** The result is an integer that identifies if the compiler option
82629 ** was used to build SQLite.
82631 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
82632 static void compileoptionusedFunc(
82633 sqlite3_context *context,
82634 int argc,
82635 sqlite3_value **argv
82637 const char *zOptName;
82638 assert( argc==1 );
82639 UNUSED_PARAMETER(argc);
82640 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
82641 ** function is a wrapper around the sqlite3_compileoption_used() C/C++
82642 ** function.
82644 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
82645 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
82648 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
82651 ** Implementation of the sqlite_compileoption_get() function.
82652 ** The result is a string that identifies the compiler options
82653 ** used to build SQLite.
82655 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
82656 static void compileoptiongetFunc(
82657 sqlite3_context *context,
82658 int argc,
82659 sqlite3_value **argv
82661 int n;
82662 assert( argc==1 );
82663 UNUSED_PARAMETER(argc);
82664 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
82665 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
82667 n = sqlite3_value_int(argv[0]);
82668 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
82670 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
82672 /* Array for converting from half-bytes (nybbles) into ASCII hex
82673 ** digits. */
82674 static const char hexdigits[] = {
82675 '0', '1', '2', '3', '4', '5', '6', '7',
82676 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
82680 ** EXPERIMENTAL - This is not an official function. The interface may
82681 ** change. This function may disappear. Do not write code that depends
82682 ** on this function.
82684 ** Implementation of the QUOTE() function. This function takes a single
82685 ** argument. If the argument is numeric, the return value is the same as
82686 ** the argument. If the argument is NULL, the return value is the string
82687 ** "NULL". Otherwise, the argument is enclosed in single quotes with
82688 ** single-quote escapes.
82690 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82691 assert( argc==1 );
82692 UNUSED_PARAMETER(argc);
82693 switch( sqlite3_value_type(argv[0]) ){
82694 case SQLITE_INTEGER:
82695 case SQLITE_FLOAT: {
82696 sqlite3_result_value(context, argv[0]);
82697 break;
82699 case SQLITE_BLOB: {
82700 char *zText = 0;
82701 char const *zBlob = sqlite3_value_blob(argv[0]);
82702 int nBlob = sqlite3_value_bytes(argv[0]);
82703 assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
82704 zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
82705 if( zText ){
82706 int i;
82707 for(i=0; i<nBlob; i++){
82708 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
82709 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
82711 zText[(nBlob*2)+2] = '\'';
82712 zText[(nBlob*2)+3] = '\0';
82713 zText[0] = 'X';
82714 zText[1] = '\'';
82715 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
82716 sqlite3_free(zText);
82718 break;
82720 case SQLITE_TEXT: {
82721 int i,j;
82722 u64 n;
82723 const unsigned char *zArg = sqlite3_value_text(argv[0]);
82724 char *z;
82726 if( zArg==0 ) return;
82727 for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
82728 z = contextMalloc(context, ((i64)i)+((i64)n)+3);
82729 if( z ){
82730 z[0] = '\'';
82731 for(i=0, j=1; zArg[i]; i++){
82732 z[j++] = zArg[i];
82733 if( zArg[i]=='\'' ){
82734 z[j++] = '\'';
82737 z[j++] = '\'';
82738 z[j] = 0;
82739 sqlite3_result_text(context, z, j, sqlite3_free);
82741 break;
82743 default: {
82744 assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
82745 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
82746 break;
82752 ** The hex() function. Interpret the argument as a blob. Return
82753 ** a hexadecimal rendering as text.
82755 static void hexFunc(
82756 sqlite3_context *context,
82757 int argc,
82758 sqlite3_value **argv
82760 int i, n;
82761 const unsigned char *pBlob;
82762 char *zHex, *z;
82763 assert( argc==1 );
82764 UNUSED_PARAMETER(argc);
82765 pBlob = sqlite3_value_blob(argv[0]);
82766 n = sqlite3_value_bytes(argv[0]);
82767 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
82768 z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
82769 if( zHex ){
82770 for(i=0; i<n; i++, pBlob++){
82771 unsigned char c = *pBlob;
82772 *(z++) = hexdigits[(c>>4)&0xf];
82773 *(z++) = hexdigits[c&0xf];
82775 *z = 0;
82776 sqlite3_result_text(context, zHex, n*2, sqlite3_free);
82781 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
82783 static void zeroblobFunc(
82784 sqlite3_context *context,
82785 int argc,
82786 sqlite3_value **argv
82788 i64 n;
82789 sqlite3 *db = sqlite3_context_db_handle(context);
82790 assert( argc==1 );
82791 UNUSED_PARAMETER(argc);
82792 n = sqlite3_value_int64(argv[0]);
82793 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
82794 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
82795 if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82796 sqlite3_result_error_toobig(context);
82797 }else{
82798 sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
82803 ** The replace() function. Three arguments are all strings: call
82804 ** them A, B, and C. The result is also a string which is derived
82805 ** from A by replacing every occurance of B with C. The match
82806 ** must be exact. Collating sequences are not used.
82808 static void replaceFunc(
82809 sqlite3_context *context,
82810 int argc,
82811 sqlite3_value **argv
82813 const unsigned char *zStr; /* The input string A */
82814 const unsigned char *zPattern; /* The pattern string B */
82815 const unsigned char *zRep; /* The replacement string C */
82816 unsigned char *zOut; /* The output */
82817 int nStr; /* Size of zStr */
82818 int nPattern; /* Size of zPattern */
82819 int nRep; /* Size of zRep */
82820 i64 nOut; /* Maximum size of zOut */
82821 int loopLimit; /* Last zStr[] that might match zPattern[] */
82822 int i, j; /* Loop counters */
82824 assert( argc==3 );
82825 UNUSED_PARAMETER(argc);
82826 zStr = sqlite3_value_text(argv[0]);
82827 if( zStr==0 ) return;
82828 nStr = sqlite3_value_bytes(argv[0]);
82829 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
82830 zPattern = sqlite3_value_text(argv[1]);
82831 if( zPattern==0 ){
82832 assert( sqlite3_value_type(argv[1])==SQLITE_NULL
82833 || sqlite3_context_db_handle(context)->mallocFailed );
82834 return;
82836 if( zPattern[0]==0 ){
82837 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
82838 sqlite3_result_value(context, argv[0]);
82839 return;
82841 nPattern = sqlite3_value_bytes(argv[1]);
82842 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
82843 zRep = sqlite3_value_text(argv[2]);
82844 if( zRep==0 ) return;
82845 nRep = sqlite3_value_bytes(argv[2]);
82846 assert( zRep==sqlite3_value_text(argv[2]) );
82847 nOut = nStr + 1;
82848 assert( nOut<SQLITE_MAX_LENGTH );
82849 zOut = contextMalloc(context, (i64)nOut);
82850 if( zOut==0 ){
82851 return;
82853 loopLimit = nStr - nPattern;
82854 for(i=j=0; i<=loopLimit; i++){
82855 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
82856 zOut[j++] = zStr[i];
82857 }else{
82858 u8 *zOld;
82859 sqlite3 *db = sqlite3_context_db_handle(context);
82860 nOut += nRep - nPattern;
82861 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
82862 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
82863 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82864 sqlite3_result_error_toobig(context);
82865 sqlite3_free(zOut);
82866 return;
82868 zOld = zOut;
82869 zOut = sqlite3_realloc(zOut, (int)nOut);
82870 if( zOut==0 ){
82871 sqlite3_result_error_nomem(context);
82872 sqlite3_free(zOld);
82873 return;
82875 memcpy(&zOut[j], zRep, nRep);
82876 j += nRep;
82877 i += nPattern-1;
82880 assert( j+nStr-i+1==nOut );
82881 memcpy(&zOut[j], &zStr[i], nStr-i);
82882 j += nStr - i;
82883 assert( j<=nOut );
82884 zOut[j] = 0;
82885 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
82889 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
82890 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
82892 static void trimFunc(
82893 sqlite3_context *context,
82894 int argc,
82895 sqlite3_value **argv
82897 const unsigned char *zIn; /* Input string */
82898 const unsigned char *zCharSet; /* Set of characters to trim */
82899 int nIn; /* Number of bytes in input */
82900 int flags; /* 1: trimleft 2: trimright 3: trim */
82901 int i; /* Loop counter */
82902 unsigned char *aLen = 0; /* Length of each character in zCharSet */
82903 unsigned char **azChar = 0; /* Individual characters in zCharSet */
82904 int nChar; /* Number of characters in zCharSet */
82906 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
82907 return;
82909 zIn = sqlite3_value_text(argv[0]);
82910 if( zIn==0 ) return;
82911 nIn = sqlite3_value_bytes(argv[0]);
82912 assert( zIn==sqlite3_value_text(argv[0]) );
82913 if( argc==1 ){
82914 static const unsigned char lenOne[] = { 1 };
82915 static unsigned char * const azOne[] = { (u8*)" " };
82916 nChar = 1;
82917 aLen = (u8*)lenOne;
82918 azChar = (unsigned char **)azOne;
82919 zCharSet = 0;
82920 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
82921 return;
82922 }else{
82923 const unsigned char *z;
82924 for(z=zCharSet, nChar=0; *z; nChar++){
82925 SQLITE_SKIP_UTF8(z);
82927 if( nChar>0 ){
82928 azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
82929 if( azChar==0 ){
82930 return;
82932 aLen = (unsigned char*)&azChar[nChar];
82933 for(z=zCharSet, nChar=0; *z; nChar++){
82934 azChar[nChar] = (unsigned char *)z;
82935 SQLITE_SKIP_UTF8(z);
82936 aLen[nChar] = (u8)(z - azChar[nChar]);
82940 if( nChar>0 ){
82941 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
82942 if( flags & 1 ){
82943 while( nIn>0 ){
82944 int len = 0;
82945 for(i=0; i<nChar; i++){
82946 len = aLen[i];
82947 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
82949 if( i>=nChar ) break;
82950 zIn += len;
82951 nIn -= len;
82954 if( flags & 2 ){
82955 while( nIn>0 ){
82956 int len = 0;
82957 for(i=0; i<nChar; i++){
82958 len = aLen[i];
82959 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
82961 if( i>=nChar ) break;
82962 nIn -= len;
82965 if( zCharSet ){
82966 sqlite3_free((void*)azChar);
82969 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
82973 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
82974 ** is only available if the SQLITE_SOUNDEX compile-time option is used
82975 ** when SQLite is built.
82977 #ifdef SQLITE_SOUNDEX
82979 ** Compute the soundex encoding of a word.
82981 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
82982 ** soundex encoding of the string X.
82984 static void soundexFunc(
82985 sqlite3_context *context,
82986 int argc,
82987 sqlite3_value **argv
82989 char zResult[8];
82990 const u8 *zIn;
82991 int i, j;
82992 static const unsigned char iCode[] = {
82993 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82994 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82995 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82996 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82997 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
82998 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
82999 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
83000 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
83002 assert( argc==1 );
83003 zIn = (u8*)sqlite3_value_text(argv[0]);
83004 if( zIn==0 ) zIn = (u8*)"";
83005 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
83006 if( zIn[i] ){
83007 u8 prevcode = iCode[zIn[i]&0x7f];
83008 zResult[0] = sqlite3Toupper(zIn[i]);
83009 for(j=1; j<4 && zIn[i]; i++){
83010 int code = iCode[zIn[i]&0x7f];
83011 if( code>0 ){
83012 if( code!=prevcode ){
83013 prevcode = code;
83014 zResult[j++] = code + '0';
83016 }else{
83017 prevcode = 0;
83020 while( j<4 ){
83021 zResult[j++] = '0';
83023 zResult[j] = 0;
83024 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
83025 }else{
83026 /* IMP: R-64894-50321 The string "?000" is returned if the argument
83027 ** is NULL or contains no ASCII alphabetic characters. */
83028 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
83031 #endif /* SQLITE_SOUNDEX */
83033 #ifndef SQLITE_OMIT_LOAD_EXTENSION
83035 ** A function that loads a shared-library extension then returns NULL.
83037 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
83038 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
83039 const char *zProc;
83040 sqlite3 *db = sqlite3_context_db_handle(context);
83041 char *zErrMsg = 0;
83043 if( argc==2 ){
83044 zProc = (const char *)sqlite3_value_text(argv[1]);
83045 }else{
83046 zProc = 0;
83048 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
83049 sqlite3_result_error(context, zErrMsg, -1);
83050 sqlite3_free(zErrMsg);
83053 #endif
83057 ** An instance of the following structure holds the context of a
83058 ** sum() or avg() aggregate computation.
83060 typedef struct SumCtx SumCtx;
83061 struct SumCtx {
83062 double rSum; /* Floating point sum */
83063 i64 iSum; /* Integer sum */
83064 i64 cnt; /* Number of elements summed */
83065 u8 overflow; /* True if integer overflow seen */
83066 u8 approx; /* True if non-integer value was input to the sum */
83070 ** Routines used to compute the sum, average, and total.
83072 ** The SUM() function follows the (broken) SQL standard which means
83073 ** that it returns NULL if it sums over no inputs. TOTAL returns
83074 ** 0.0 in that case. In addition, TOTAL always returns a float where
83075 ** SUM might return an integer if it never encounters a floating point
83076 ** value. TOTAL never fails, but SUM might through an exception if
83077 ** it overflows an integer.
83079 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
83080 SumCtx *p;
83081 int type;
83082 assert( argc==1 );
83083 UNUSED_PARAMETER(argc);
83084 p = sqlite3_aggregate_context(context, sizeof(*p));
83085 type = sqlite3_value_numeric_type(argv[0]);
83086 if( p && type!=SQLITE_NULL ){
83087 p->cnt++;
83088 if( type==SQLITE_INTEGER ){
83089 i64 v = sqlite3_value_int64(argv[0]);
83090 p->rSum += v;
83091 if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
83092 p->overflow = 1;
83094 }else{
83095 p->rSum += sqlite3_value_double(argv[0]);
83096 p->approx = 1;
83100 static void sumFinalize(sqlite3_context *context){
83101 SumCtx *p;
83102 p = sqlite3_aggregate_context(context, 0);
83103 if( p && p->cnt>0 ){
83104 if( p->overflow ){
83105 sqlite3_result_error(context,"integer overflow",-1);
83106 }else if( p->approx ){
83107 sqlite3_result_double(context, p->rSum);
83108 }else{
83109 sqlite3_result_int64(context, p->iSum);
83113 static void avgFinalize(sqlite3_context *context){
83114 SumCtx *p;
83115 p = sqlite3_aggregate_context(context, 0);
83116 if( p && p->cnt>0 ){
83117 sqlite3_result_double(context, p->rSum/(double)p->cnt);
83120 static void totalFinalize(sqlite3_context *context){
83121 SumCtx *p;
83122 p = sqlite3_aggregate_context(context, 0);
83123 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
83124 sqlite3_result_double(context, p ? p->rSum : (double)0);
83128 ** The following structure keeps track of state information for the
83129 ** count() aggregate function.
83131 typedef struct CountCtx CountCtx;
83132 struct CountCtx {
83133 i64 n;
83137 ** Routines to implement the count() aggregate function.
83139 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
83140 CountCtx *p;
83141 p = sqlite3_aggregate_context(context, sizeof(*p));
83142 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
83143 p->n++;
83146 #ifndef SQLITE_OMIT_DEPRECATED
83147 /* The sqlite3_aggregate_count() function is deprecated. But just to make
83148 ** sure it still operates correctly, verify that its count agrees with our
83149 ** internal count when using count(*) and when the total count can be
83150 ** expressed as a 32-bit integer. */
83151 assert( argc==1 || p==0 || p->n>0x7fffffff
83152 || p->n==sqlite3_aggregate_count(context) );
83153 #endif
83155 static void countFinalize(sqlite3_context *context){
83156 CountCtx *p;
83157 p = sqlite3_aggregate_context(context, 0);
83158 sqlite3_result_int64(context, p ? p->n : 0);
83162 ** Routines to implement min() and max() aggregate functions.
83164 static void minmaxStep(
83165 sqlite3_context *context,
83166 int NotUsed,
83167 sqlite3_value **argv
83169 Mem *pArg = (Mem *)argv[0];
83170 Mem *pBest;
83171 UNUSED_PARAMETER(NotUsed);
83173 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
83174 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
83175 if( !pBest ) return;
83177 if( pBest->flags ){
83178 int max;
83179 int cmp;
83180 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
83181 /* This step function is used for both the min() and max() aggregates,
83182 ** the only difference between the two being that the sense of the
83183 ** comparison is inverted. For the max() aggregate, the
83184 ** sqlite3_user_data() function returns (void *)-1. For min() it
83185 ** returns (void *)db, where db is the sqlite3* database pointer.
83186 ** Therefore the next statement sets variable 'max' to 1 for the max()
83187 ** aggregate, or 0 for min().
83189 max = sqlite3_user_data(context)!=0;
83190 cmp = sqlite3MemCompare(pBest, pArg, pColl);
83191 if( (max && cmp<0) || (!max && cmp>0) ){
83192 sqlite3VdbeMemCopy(pBest, pArg);
83194 }else{
83195 sqlite3VdbeMemCopy(pBest, pArg);
83198 static void minMaxFinalize(sqlite3_context *context){
83199 sqlite3_value *pRes;
83200 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
83201 if( pRes ){
83202 if( ALWAYS(pRes->flags) ){
83203 sqlite3_result_value(context, pRes);
83205 sqlite3VdbeMemRelease(pRes);
83210 ** group_concat(EXPR, ?SEPARATOR?)
83212 static void groupConcatStep(
83213 sqlite3_context *context,
83214 int argc,
83215 sqlite3_value **argv
83217 const char *zVal;
83218 StrAccum *pAccum;
83219 const char *zSep;
83220 int nVal, nSep;
83221 assert( argc==1 || argc==2 );
83222 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
83223 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
83225 if( pAccum ){
83226 sqlite3 *db = sqlite3_context_db_handle(context);
83227 int firstTerm = pAccum->useMalloc==0;
83228 pAccum->useMalloc = 2;
83229 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
83230 if( !firstTerm ){
83231 if( argc==2 ){
83232 zSep = (char*)sqlite3_value_text(argv[1]);
83233 nSep = sqlite3_value_bytes(argv[1]);
83234 }else{
83235 zSep = ",";
83236 nSep = 1;
83238 sqlite3StrAccumAppend(pAccum, zSep, nSep);
83240 zVal = (char*)sqlite3_value_text(argv[0]);
83241 nVal = sqlite3_value_bytes(argv[0]);
83242 sqlite3StrAccumAppend(pAccum, zVal, nVal);
83245 static void groupConcatFinalize(sqlite3_context *context){
83246 StrAccum *pAccum;
83247 pAccum = sqlite3_aggregate_context(context, 0);
83248 if( pAccum ){
83249 if( pAccum->tooBig ){
83250 sqlite3_result_error_toobig(context);
83251 }else if( pAccum->mallocFailed ){
83252 sqlite3_result_error_nomem(context);
83253 }else{
83254 sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
83255 sqlite3_free);
83261 ** This routine does per-connection function registration. Most
83262 ** of the built-in functions above are part of the global function set.
83263 ** This routine only deals with those that are not global.
83265 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
83266 int rc = sqlite3_overload_function(db, "MATCH", 2);
83267 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
83268 if( rc==SQLITE_NOMEM ){
83269 db->mallocFailed = 1;
83274 ** Set the LIKEOPT flag on the 2-argument function with the given name.
83276 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
83277 FuncDef *pDef;
83278 pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
83279 2, SQLITE_UTF8, 0);
83280 if( ALWAYS(pDef) ){
83281 pDef->flags = flagVal;
83286 ** Register the built-in LIKE and GLOB functions. The caseSensitive
83287 ** parameter determines whether or not the LIKE operator is case
83288 ** sensitive. GLOB is always case sensitive.
83290 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
83291 struct compareInfo *pInfo;
83292 if( caseSensitive ){
83293 pInfo = (struct compareInfo*)&likeInfoAlt;
83294 }else{
83295 pInfo = (struct compareInfo*)&likeInfoNorm;
83297 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83298 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83299 sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
83300 (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
83301 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
83302 setLikeOptFlag(db, "like",
83303 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
83307 ** pExpr points to an expression which implements a function. If
83308 ** it is appropriate to apply the LIKE optimization to that function
83309 ** then set aWc[0] through aWc[2] to the wildcard characters and
83310 ** return TRUE. If the function is not a LIKE-style function then
83311 ** return FALSE.
83313 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
83314 FuncDef *pDef;
83315 if( pExpr->op!=TK_FUNCTION
83316 || !pExpr->x.pList
83317 || pExpr->x.pList->nExpr!=2
83319 return 0;
83321 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
83322 pDef = sqlite3FindFunction(db, pExpr->u.zToken,
83323 sqlite3Strlen30(pExpr->u.zToken),
83324 2, SQLITE_UTF8, 0);
83325 if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
83326 return 0;
83329 /* The memcpy() statement assumes that the wildcard characters are
83330 ** the first three statements in the compareInfo structure. The
83331 ** asserts() that follow verify that assumption
83333 memcpy(aWc, pDef->pUserData, 3);
83334 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
83335 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
83336 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
83337 *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
83338 return 1;
83342 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
83343 ** to the global function hash table. This occurs at start-time (as
83344 ** a consequence of calling sqlite3_initialize()).
83346 ** After this routine runs
83348 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
83350 ** The following array holds FuncDef structures for all of the functions
83351 ** defined in this file.
83353 ** The array cannot be constant since changes are made to the
83354 ** FuncDef.pHash elements at start-time. The elements of this array
83355 ** are read-only after initialization is complete.
83357 static SQLITE_WSD FuncDef aBuiltinFunc[] = {
83358 FUNCTION(ltrim, 1, 1, 0, trimFunc ),
83359 FUNCTION(ltrim, 2, 1, 0, trimFunc ),
83360 FUNCTION(rtrim, 1, 2, 0, trimFunc ),
83361 FUNCTION(rtrim, 2, 2, 0, trimFunc ),
83362 FUNCTION(trim, 1, 3, 0, trimFunc ),
83363 FUNCTION(trim, 2, 3, 0, trimFunc ),
83364 FUNCTION(min, -1, 0, 1, minmaxFunc ),
83365 FUNCTION(min, 0, 0, 1, 0 ),
83366 AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
83367 FUNCTION(max, -1, 1, 1, minmaxFunc ),
83368 FUNCTION(max, 0, 1, 1, 0 ),
83369 AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
83370 FUNCTION(typeof, 1, 0, 0, typeofFunc ),
83371 FUNCTION(length, 1, 0, 0, lengthFunc ),
83372 FUNCTION(substr, 2, 0, 0, substrFunc ),
83373 FUNCTION(substr, 3, 0, 0, substrFunc ),
83374 FUNCTION(abs, 1, 0, 0, absFunc ),
83375 #ifndef SQLITE_OMIT_FLOATING_POINT
83376 FUNCTION(round, 1, 0, 0, roundFunc ),
83377 FUNCTION(round, 2, 0, 0, roundFunc ),
83378 #endif
83379 FUNCTION(upper, 1, 0, 0, upperFunc ),
83380 FUNCTION(lower, 1, 0, 0, lowerFunc ),
83381 FUNCTION(coalesce, 1, 0, 0, 0 ),
83382 FUNCTION(coalesce, 0, 0, 0, 0 ),
83383 /* FUNCTION(coalesce, -1, 0, 0, ifnullFunc ), */
83384 {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
83385 FUNCTION(hex, 1, 0, 0, hexFunc ),
83386 /* FUNCTION(ifnull, 2, 0, 0, ifnullFunc ), */
83387 {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
83388 FUNCTION(random, 0, 0, 0, randomFunc ),
83389 FUNCTION(randomblob, 1, 0, 0, randomBlob ),
83390 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
83391 FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
83392 FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
83393 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
83394 FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
83395 FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
83396 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
83397 FUNCTION(quote, 1, 0, 0, quoteFunc ),
83398 FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
83399 FUNCTION(changes, 0, 0, 0, changes ),
83400 FUNCTION(total_changes, 0, 0, 0, total_changes ),
83401 FUNCTION(replace, 3, 0, 0, replaceFunc ),
83402 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
83403 #ifdef SQLITE_SOUNDEX
83404 FUNCTION(soundex, 1, 0, 0, soundexFunc ),
83405 #endif
83406 #ifndef SQLITE_OMIT_LOAD_EXTENSION
83407 FUNCTION(load_extension, 1, 0, 0, loadExt ),
83408 FUNCTION(load_extension, 2, 0, 0, loadExt ),
83409 #endif
83410 AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
83411 AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
83412 AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
83413 /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
83414 {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
83415 AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
83416 AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
83417 AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
83419 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83420 #ifdef SQLITE_CASE_SENSITIVE_LIKE
83421 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83422 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83423 #else
83424 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
83425 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
83426 #endif
83429 int i;
83430 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
83431 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
83433 for(i=0; i<ArraySize(aBuiltinFunc); i++){
83434 sqlite3FuncDefInsert(pHash, &aFunc[i]);
83436 sqlite3RegisterDateTimeFunctions();
83437 #ifndef SQLITE_OMIT_ALTERTABLE
83438 sqlite3AlterFunctions();
83439 #endif
83442 /************** End of func.c ************************************************/
83443 /************** Begin file fkey.c ********************************************/
83446 ** The author disclaims copyright to this source code. In place of
83447 ** a legal notice, here is a blessing:
83449 ** May you do good and not evil.
83450 ** May you find forgiveness for yourself and forgive others.
83451 ** May you share freely, never taking more than you give.
83453 *************************************************************************
83454 ** This file contains code used by the compiler to add foreign key
83455 ** support to compiled SQL statements.
83458 #ifndef SQLITE_OMIT_FOREIGN_KEY
83459 #ifndef SQLITE_OMIT_TRIGGER
83462 ** Deferred and Immediate FKs
83463 ** --------------------------
83465 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
83466 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
83467 ** is returned and the current statement transaction rolled back. If a
83468 ** deferred foreign key constraint is violated, no action is taken
83469 ** immediately. However if the application attempts to commit the
83470 ** transaction before fixing the constraint violation, the attempt fails.
83472 ** Deferred constraints are implemented using a simple counter associated
83473 ** with the database handle. The counter is set to zero each time a
83474 ** database transaction is opened. Each time a statement is executed
83475 ** that causes a foreign key violation, the counter is incremented. Each
83476 ** time a statement is executed that removes an existing violation from
83477 ** the database, the counter is decremented. When the transaction is
83478 ** committed, the commit fails if the current value of the counter is
83479 ** greater than zero. This scheme has two big drawbacks:
83481 ** * When a commit fails due to a deferred foreign key constraint,
83482 ** there is no way to tell which foreign constraint is not satisfied,
83483 ** or which row it is not satisfied for.
83485 ** * If the database contains foreign key violations when the
83486 ** transaction is opened, this may cause the mechanism to malfunction.
83488 ** Despite these problems, this approach is adopted as it seems simpler
83489 ** than the alternatives.
83491 ** INSERT operations:
83493 ** I.1) For each FK for which the table is the child table, search
83494 ** the parent table for a match. If none is found increment the
83495 ** constraint counter.
83497 ** I.2) For each FK for which the table is the parent table,
83498 ** search the child table for rows that correspond to the new
83499 ** row in the parent table. Decrement the counter for each row
83500 ** found (as the constraint is now satisfied).
83502 ** DELETE operations:
83504 ** D.1) For each FK for which the table is the child table,
83505 ** search the parent table for a row that corresponds to the
83506 ** deleted row in the child table. If such a row is not found,
83507 ** decrement the counter.
83509 ** D.2) For each FK for which the table is the parent table, search
83510 ** the child table for rows that correspond to the deleted row
83511 ** in the parent table. For each found increment the counter.
83513 ** UPDATE operations:
83515 ** An UPDATE command requires that all 4 steps above are taken, but only
83516 ** for FK constraints for which the affected columns are actually
83517 ** modified (values must be compared at runtime).
83519 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
83520 ** This simplifies the implementation a bit.
83522 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
83523 ** resolution is considered to delete rows before the new row is inserted.
83524 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
83525 ** is thrown, even if the FK constraint would be satisfied after the new
83526 ** row is inserted.
83528 ** Immediate constraints are usually handled similarly. The only difference
83529 ** is that the counter used is stored as part of each individual statement
83530 ** object (struct Vdbe). If, after the statement has run, its immediate
83531 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
83532 ** and the statement transaction is rolled back. An exception is an INSERT
83533 ** statement that inserts a single row only (no triggers). In this case,
83534 ** instead of using a counter, an exception is thrown immediately if the
83535 ** INSERT violates a foreign key constraint. This is necessary as such
83536 ** an INSERT does not open a statement transaction.
83538 ** TODO: How should dropping a table be handled? How should renaming a
83539 ** table be handled?
83542 ** Query API Notes
83543 ** ---------------
83545 ** Before coding an UPDATE or DELETE row operation, the code-generator
83546 ** for those two operations needs to know whether or not the operation
83547 ** requires any FK processing and, if so, which columns of the original
83548 ** row are required by the FK processing VDBE code (i.e. if FKs were
83549 ** implemented using triggers, which of the old.* columns would be
83550 ** accessed). No information is required by the code-generator before
83551 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
83552 ** generation code to query for this information are:
83554 ** sqlite3FkRequired() - Test to see if FK processing is required.
83555 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
83558 ** Externally accessible module functions
83559 ** --------------------------------------
83561 ** sqlite3FkCheck() - Check for foreign key violations.
83562 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
83563 ** sqlite3FkDelete() - Delete an FKey structure.
83567 ** VDBE Calling Convention
83568 ** -----------------------
83570 ** Example:
83572 ** For the following INSERT statement:
83574 ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
83575 ** INSERT INTO t1 VALUES(1, 2, 3.1);
83577 ** Register (x): 2 (type integer)
83578 ** Register (x+1): 1 (type integer)
83579 ** Register (x+2): NULL (type NULL)
83580 ** Register (x+3): 3.1 (type real)
83584 ** A foreign key constraint requires that the key columns in the parent
83585 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
83586 ** Given that pParent is the parent table for foreign key constraint pFKey,
83587 ** search the schema a unique index on the parent key columns.
83589 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
83590 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
83591 ** is set to point to the unique index.
83593 ** If the parent key consists of a single column (the foreign key constraint
83594 ** is not a composite foreign key), output variable *paiCol is set to NULL.
83595 ** Otherwise, it is set to point to an allocated array of size N, where
83596 ** N is the number of columns in the parent key. The first element of the
83597 ** array is the index of the child table column that is mapped by the FK
83598 ** constraint to the parent table column stored in the left-most column
83599 ** of index *ppIdx. The second element of the array is the index of the
83600 ** child table column that corresponds to the second left-most column of
83601 ** *ppIdx, and so on.
83603 ** If the required index cannot be found, either because:
83605 ** 1) The named parent key columns do not exist, or
83607 ** 2) The named parent key columns do exist, but are not subject to a
83608 ** UNIQUE or PRIMARY KEY constraint, or
83610 ** 3) No parent key columns were provided explicitly as part of the
83611 ** foreign key definition, and the parent table does not have a
83612 ** PRIMARY KEY, or
83614 ** 4) No parent key columns were provided explicitly as part of the
83615 ** foreign key definition, and the PRIMARY KEY of the parent table
83616 ** consists of a a different number of columns to the child key in
83617 ** the child table.
83619 ** then non-zero is returned, and a "foreign key mismatch" error loaded
83620 ** into pParse. If an OOM error occurs, non-zero is returned and the
83621 ** pParse->db->mallocFailed flag is set.
83623 static int locateFkeyIndex(
83624 Parse *pParse, /* Parse context to store any error in */
83625 Table *pParent, /* Parent table of FK constraint pFKey */
83626 FKey *pFKey, /* Foreign key to find index for */
83627 Index **ppIdx, /* OUT: Unique index on parent table */
83628 int **paiCol /* OUT: Map of index columns in pFKey */
83630 Index *pIdx = 0; /* Value to return via *ppIdx */
83631 int *aiCol = 0; /* Value to return via *paiCol */
83632 int nCol = pFKey->nCol; /* Number of columns in parent key */
83633 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
83635 /* The caller is responsible for zeroing output parameters. */
83636 assert( ppIdx && *ppIdx==0 );
83637 assert( !paiCol || *paiCol==0 );
83638 assert( pParse );
83640 /* If this is a non-composite (single column) foreign key, check if it
83641 ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
83642 ** and *paiCol set to zero and return early.
83644 ** Otherwise, for a composite foreign key (more than one column), allocate
83645 ** space for the aiCol array (returned via output parameter *paiCol).
83646 ** Non-composite foreign keys do not require the aiCol array.
83648 if( nCol==1 ){
83649 /* The FK maps to the IPK if any of the following are true:
83651 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
83652 ** mapped to the primary key of table pParent, or
83653 ** 2) The FK is explicitly mapped to a column declared as INTEGER
83654 ** PRIMARY KEY.
83656 if( pParent->iPKey>=0 ){
83657 if( !zKey ) return 0;
83658 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
83660 }else if( paiCol ){
83661 assert( nCol>1 );
83662 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
83663 if( !aiCol ) return 1;
83664 *paiCol = aiCol;
83667 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
83668 if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
83669 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
83670 ** of columns. If each indexed column corresponds to a foreign key
83671 ** column of pFKey, then this index is a winner. */
83673 if( zKey==0 ){
83674 /* If zKey is NULL, then this foreign key is implicitly mapped to
83675 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
83676 ** identified by the test (Index.autoIndex==2). */
83677 if( pIdx->autoIndex==2 ){
83678 if( aiCol ){
83679 int i;
83680 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
83682 break;
83684 }else{
83685 /* If zKey is non-NULL, then this foreign key was declared to
83686 ** map to an explicit list of columns in table pParent. Check if this
83687 ** index matches those columns. Also, check that the index uses
83688 ** the default collation sequences for each column. */
83689 int i, j;
83690 for(i=0; i<nCol; i++){
83691 int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
83692 char *zDfltColl; /* Def. collation for column */
83693 char *zIdxCol; /* Name of indexed column */
83695 /* If the index uses a collation sequence that is different from
83696 ** the default collation sequence for the column, this index is
83697 ** unusable. Bail out early in this case. */
83698 zDfltColl = pParent->aCol[iCol].zColl;
83699 if( !zDfltColl ){
83700 zDfltColl = "BINARY";
83702 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
83704 zIdxCol = pParent->aCol[iCol].zName;
83705 for(j=0; j<nCol; j++){
83706 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
83707 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
83708 break;
83711 if( j==nCol ) break;
83713 if( i==nCol ) break; /* pIdx is usable */
83718 if( !pIdx ){
83719 if( !pParse->disableTriggers ){
83720 sqlite3ErrorMsg(pParse, "foreign key mismatch");
83722 sqlite3DbFree(pParse->db, aiCol);
83723 return 1;
83726 *ppIdx = pIdx;
83727 return 0;
83731 ** This function is called when a row is inserted into or deleted from the
83732 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
83733 ** on the child table of pFKey, this function is invoked twice for each row
83734 ** affected - once to "delete" the old row, and then again to "insert" the
83735 ** new row.
83737 ** Each time it is called, this function generates VDBE code to locate the
83738 ** row in the parent table that corresponds to the row being inserted into
83739 ** or deleted from the child table. If the parent row can be found, no
83740 ** special action is taken. Otherwise, if the parent row can *not* be
83741 ** found in the parent table:
83743 ** Operation | FK type | Action taken
83744 ** --------------------------------------------------------------------------
83745 ** INSERT immediate Increment the "immediate constraint counter".
83747 ** DELETE immediate Decrement the "immediate constraint counter".
83749 ** INSERT deferred Increment the "deferred constraint counter".
83751 ** DELETE deferred Decrement the "deferred constraint counter".
83753 ** These operations are identified in the comment at the top of this file
83754 ** (fkey.c) as "I.1" and "D.1".
83756 static void fkLookupParent(
83757 Parse *pParse, /* Parse context */
83758 int iDb, /* Index of database housing pTab */
83759 Table *pTab, /* Parent table of FK pFKey */
83760 Index *pIdx, /* Unique index on parent key columns in pTab */
83761 FKey *pFKey, /* Foreign key constraint */
83762 int *aiCol, /* Map from parent key columns to child table columns */
83763 int regData, /* Address of array containing child table row */
83764 int nIncr, /* Increment constraint counter by this */
83765 int isIgnore /* If true, pretend pTab contains all NULL values */
83767 int i; /* Iterator variable */
83768 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
83769 int iCur = pParse->nTab - 1; /* Cursor number to use */
83770 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
83772 /* If nIncr is less than zero, then check at runtime if there are any
83773 ** outstanding constraints to resolve. If there are not, there is no need
83774 ** to check if deleting this row resolves any outstanding violations.
83776 ** Check if any of the key columns in the child table row are NULL. If
83777 ** any are, then the constraint is considered satisfied. No need to
83778 ** search for a matching row in the parent table. */
83779 if( nIncr<0 ){
83780 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
83782 for(i=0; i<pFKey->nCol; i++){
83783 int iReg = aiCol[i] + regData + 1;
83784 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
83787 if( isIgnore==0 ){
83788 if( pIdx==0 ){
83789 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
83790 ** column of the parent table (table pTab). */
83791 int iMustBeInt; /* Address of MustBeInt instruction */
83792 int regTemp = sqlite3GetTempReg(pParse);
83794 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
83795 ** apply the affinity of the parent key). If this fails, then there
83796 ** is no matching parent key. Before using MustBeInt, make a copy of
83797 ** the value. Otherwise, the value inserted into the child key column
83798 ** will have INTEGER affinity applied to it, which may not be correct. */
83799 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
83800 iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
83802 /* If the parent table is the same as the child table, and we are about
83803 ** to increment the constraint-counter (i.e. this is an INSERT operation),
83804 ** then check if the row being inserted matches itself. If so, do not
83805 ** increment the constraint-counter. */
83806 if( pTab==pFKey->pFrom && nIncr==1 ){
83807 sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
83810 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
83811 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
83812 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
83813 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
83814 sqlite3VdbeJumpHere(v, iMustBeInt);
83815 sqlite3ReleaseTempReg(pParse, regTemp);
83816 }else{
83817 int nCol = pFKey->nCol;
83818 int regTemp = sqlite3GetTempRange(pParse, nCol);
83819 int regRec = sqlite3GetTempReg(pParse);
83820 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
83822 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
83823 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
83824 for(i=0; i<nCol; i++){
83825 sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
83828 /* If the parent table is the same as the child table, and we are about
83829 ** to increment the constraint-counter (i.e. this is an INSERT operation),
83830 ** then check if the row being inserted matches itself. If so, do not
83831 ** increment the constraint-counter. */
83832 if( pTab==pFKey->pFrom && nIncr==1 ){
83833 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
83834 for(i=0; i<nCol; i++){
83835 int iChild = aiCol[i]+1+regData;
83836 int iParent = pIdx->aiColumn[i]+1+regData;
83837 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
83839 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
83842 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
83843 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
83844 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
83846 sqlite3ReleaseTempReg(pParse, regRec);
83847 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
83851 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
83852 /* Special case: If this is an INSERT statement that will insert exactly
83853 ** one row into the table, raise a constraint immediately instead of
83854 ** incrementing a counter. This is necessary as the VM code is being
83855 ** generated for will not open a statement transaction. */
83856 assert( nIncr==1 );
83857 sqlite3HaltConstraint(
83858 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
83860 }else{
83861 if( nIncr>0 && pFKey->isDeferred==0 ){
83862 sqlite3ParseToplevel(pParse)->mayAbort = 1;
83864 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
83867 sqlite3VdbeResolveLabel(v, iOk);
83868 sqlite3VdbeAddOp1(v, OP_Close, iCur);
83872 ** This function is called to generate code executed when a row is deleted
83873 ** from the parent table of foreign key constraint pFKey and, if pFKey is
83874 ** deferred, when a row is inserted into the same table. When generating
83875 ** code for an SQL UPDATE operation, this function may be called twice -
83876 ** once to "delete" the old row and once to "insert" the new row.
83878 ** The code generated by this function scans through the rows in the child
83879 ** table that correspond to the parent table row being deleted or inserted.
83880 ** For each child row found, one of the following actions is taken:
83882 ** Operation | FK type | Action taken
83883 ** --------------------------------------------------------------------------
83884 ** DELETE immediate Increment the "immediate constraint counter".
83885 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
83886 ** throw a "foreign key constraint failed" exception.
83888 ** INSERT immediate Decrement the "immediate constraint counter".
83890 ** DELETE deferred Increment the "deferred constraint counter".
83891 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
83892 ** throw a "foreign key constraint failed" exception.
83894 ** INSERT deferred Decrement the "deferred constraint counter".
83896 ** These operations are identified in the comment at the top of this file
83897 ** (fkey.c) as "I.2" and "D.2".
83899 static void fkScanChildren(
83900 Parse *pParse, /* Parse context */
83901 SrcList *pSrc, /* SrcList containing the table to scan */
83902 Table *pTab,
83903 Index *pIdx, /* Foreign key index */
83904 FKey *pFKey, /* Foreign key relationship */
83905 int *aiCol, /* Map from pIdx cols to child table cols */
83906 int regData, /* Referenced table data starts here */
83907 int nIncr /* Amount to increment deferred counter by */
83909 sqlite3 *db = pParse->db; /* Database handle */
83910 int i; /* Iterator variable */
83911 Expr *pWhere = 0; /* WHERE clause to scan with */
83912 NameContext sNameContext; /* Context used to resolve WHERE clause */
83913 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
83914 int iFkIfZero = 0; /* Address of OP_FkIfZero */
83915 Vdbe *v = sqlite3GetVdbe(pParse);
83917 assert( !pIdx || pIdx->pTable==pTab );
83919 if( nIncr<0 ){
83920 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
83923 /* Create an Expr object representing an SQL expression like:
83925 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
83927 ** The collation sequence used for the comparison should be that of
83928 ** the parent key columns. The affinity of the parent key column should
83929 ** be applied to each child key value before the comparison takes place.
83931 for(i=0; i<pFKey->nCol; i++){
83932 Expr *pLeft; /* Value from parent table row */
83933 Expr *pRight; /* Column ref to child table */
83934 Expr *pEq; /* Expression (pLeft = pRight) */
83935 int iCol; /* Index of column in child table */
83936 const char *zCol; /* Name of column in child table */
83938 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
83939 if( pLeft ){
83940 /* Set the collation sequence and affinity of the LHS of each TK_EQ
83941 ** expression to the parent key column defaults. */
83942 if( pIdx ){
83943 Column *pCol;
83944 iCol = pIdx->aiColumn[i];
83945 pCol = &pTab->aCol[iCol];
83946 if( pTab->iPKey==iCol ) iCol = -1;
83947 pLeft->iTable = regData+iCol+1;
83948 pLeft->affinity = pCol->affinity;
83949 pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
83950 }else{
83951 pLeft->iTable = regData;
83952 pLeft->affinity = SQLITE_AFF_INTEGER;
83955 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
83956 assert( iCol>=0 );
83957 zCol = pFKey->pFrom->aCol[iCol].zName;
83958 pRight = sqlite3Expr(db, TK_ID, zCol);
83959 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
83960 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
83963 /* If the child table is the same as the parent table, and this scan
83964 ** is taking place as part of a DELETE operation (operation D.2), omit the
83965 ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
83966 ** clause, where $rowid is the rowid of the row being deleted. */
83967 if( pTab==pFKey->pFrom && nIncr>0 ){
83968 Expr *pEq; /* Expression (pLeft = pRight) */
83969 Expr *pLeft; /* Value from parent table row */
83970 Expr *pRight; /* Column ref to child table */
83971 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
83972 pRight = sqlite3Expr(db, TK_COLUMN, 0);
83973 if( pLeft && pRight ){
83974 pLeft->iTable = regData;
83975 pLeft->affinity = SQLITE_AFF_INTEGER;
83976 pRight->iTable = pSrc->a[0].iCursor;
83977 pRight->iColumn = -1;
83979 pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
83980 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
83983 /* Resolve the references in the WHERE clause. */
83984 memset(&sNameContext, 0, sizeof(NameContext));
83985 sNameContext.pSrcList = pSrc;
83986 sNameContext.pParse = pParse;
83987 sqlite3ResolveExprNames(&sNameContext, pWhere);
83989 /* Create VDBE to loop through the entries in pSrc that match the WHERE
83990 ** clause. If the constraint is not deferred, throw an exception for
83991 ** each row found. Otherwise, for deferred constraints, increment the
83992 ** deferred constraint counter by nIncr for each row selected. */
83993 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
83994 if( nIncr>0 && pFKey->isDeferred==0 ){
83995 sqlite3ParseToplevel(pParse)->mayAbort = 1;
83997 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
83998 if( pWInfo ){
83999 sqlite3WhereEnd(pWInfo);
84002 /* Clean up the WHERE clause constructed above. */
84003 sqlite3ExprDelete(db, pWhere);
84004 if( iFkIfZero ){
84005 sqlite3VdbeJumpHere(v, iFkIfZero);
84010 ** This function returns a pointer to the head of a linked list of FK
84011 ** constraints for which table pTab is the parent table. For example,
84012 ** given the following schema:
84014 ** CREATE TABLE t1(a PRIMARY KEY);
84015 ** CREATE TABLE t2(b REFERENCES t1(a);
84017 ** Calling this function with table "t1" as an argument returns a pointer
84018 ** to the FKey structure representing the foreign key constraint on table
84019 ** "t2". Calling this function with "t2" as the argument would return a
84020 ** NULL pointer (as there are no FK constraints for which t2 is the parent
84021 ** table).
84023 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
84024 int nName = sqlite3Strlen30(pTab->zName);
84025 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
84029 ** The second argument is a Trigger structure allocated by the
84030 ** fkActionTrigger() routine. This function deletes the Trigger structure
84031 ** and all of its sub-components.
84033 ** The Trigger structure or any of its sub-components may be allocated from
84034 ** the lookaside buffer belonging to database handle dbMem.
84036 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
84037 if( p ){
84038 TriggerStep *pStep = p->step_list;
84039 sqlite3ExprDelete(dbMem, pStep->pWhere);
84040 sqlite3ExprListDelete(dbMem, pStep->pExprList);
84041 sqlite3SelectDelete(dbMem, pStep->pSelect);
84042 sqlite3ExprDelete(dbMem, p->pWhen);
84043 sqlite3DbFree(dbMem, p);
84048 ** This function is called to generate code that runs when table pTab is
84049 ** being dropped from the database. The SrcList passed as the second argument
84050 ** to this function contains a single entry guaranteed to resolve to
84051 ** table pTab.
84053 ** Normally, no code is required. However, if either
84055 ** (a) The table is the parent table of a FK constraint, or
84056 ** (b) The table is the child table of a deferred FK constraint and it is
84057 ** determined at runtime that there are outstanding deferred FK
84058 ** constraint violations in the database,
84060 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
84061 ** the table from the database. Triggers are disabled while running this
84062 ** DELETE, but foreign key actions are not.
84064 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
84065 sqlite3 *db = pParse->db;
84066 if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
84067 int iSkip = 0;
84068 Vdbe *v = sqlite3GetVdbe(pParse);
84070 assert( v ); /* VDBE has already been allocated */
84071 if( sqlite3FkReferences(pTab)==0 ){
84072 /* Search for a deferred foreign key constraint for which this table
84073 ** is the child table. If one cannot be found, return without
84074 ** generating any VDBE code. If one can be found, then jump over
84075 ** the entire DELETE if there are no outstanding deferred constraints
84076 ** when this statement is run. */
84077 FKey *p;
84078 for(p=pTab->pFKey; p; p=p->pNextFrom){
84079 if( p->isDeferred ) break;
84081 if( !p ) return;
84082 iSkip = sqlite3VdbeMakeLabel(v);
84083 sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
84086 pParse->disableTriggers = 1;
84087 sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
84088 pParse->disableTriggers = 0;
84090 /* If the DELETE has generated immediate foreign key constraint
84091 ** violations, halt the VDBE and return an error at this point, before
84092 ** any modifications to the schema are made. This is because statement
84093 ** transactions are not able to rollback schema changes. */
84094 sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
84095 sqlite3HaltConstraint(
84096 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
84099 if( iSkip ){
84100 sqlite3VdbeResolveLabel(v, iSkip);
84106 ** This function is called when inserting, deleting or updating a row of
84107 ** table pTab to generate VDBE code to perform foreign key constraint
84108 ** processing for the operation.
84110 ** For a DELETE operation, parameter regOld is passed the index of the
84111 ** first register in an array of (pTab->nCol+1) registers containing the
84112 ** rowid of the row being deleted, followed by each of the column values
84113 ** of the row being deleted, from left to right. Parameter regNew is passed
84114 ** zero in this case.
84116 ** For an INSERT operation, regOld is passed zero and regNew is passed the
84117 ** first register of an array of (pTab->nCol+1) registers containing the new
84118 ** row data.
84120 ** For an UPDATE operation, this function is called twice. Once before
84121 ** the original record is deleted from the table using the calling convention
84122 ** described for DELETE. Then again after the original record is deleted
84123 ** but before the new record is inserted using the INSERT convention.
84125 SQLITE_PRIVATE void sqlite3FkCheck(
84126 Parse *pParse, /* Parse context */
84127 Table *pTab, /* Row is being deleted from this table */
84128 int regOld, /* Previous row data is stored here */
84129 int regNew /* New row data is stored here */
84131 sqlite3 *db = pParse->db; /* Database handle */
84132 FKey *pFKey; /* Used to iterate through FKs */
84133 int iDb; /* Index of database containing pTab */
84134 const char *zDb; /* Name of database containing pTab */
84135 int isIgnoreErrors = pParse->disableTriggers;
84137 /* Exactly one of regOld and regNew should be non-zero. */
84138 assert( (regOld==0)!=(regNew==0) );
84140 /* If foreign-keys are disabled, this function is a no-op. */
84141 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
84143 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84144 zDb = db->aDb[iDb].zName;
84146 /* Loop through all the foreign key constraints for which pTab is the
84147 ** child table (the table that the foreign key definition is part of). */
84148 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
84149 Table *pTo; /* Parent table of foreign key pFKey */
84150 Index *pIdx = 0; /* Index on key columns in pTo */
84151 int *aiFree = 0;
84152 int *aiCol;
84153 int iCol;
84154 int i;
84155 int isIgnore = 0;
84157 /* Find the parent table of this foreign key. Also find a unique index
84158 ** on the parent key columns in the parent table. If either of these
84159 ** schema items cannot be located, set an error in pParse and return
84160 ** early. */
84161 if( pParse->disableTriggers ){
84162 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
84163 }else{
84164 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
84166 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
84167 if( !isIgnoreErrors || db->mallocFailed ) return;
84168 continue;
84170 assert( pFKey->nCol==1 || (aiFree && pIdx) );
84172 if( aiFree ){
84173 aiCol = aiFree;
84174 }else{
84175 iCol = pFKey->aCol[0].iFrom;
84176 aiCol = &iCol;
84178 for(i=0; i<pFKey->nCol; i++){
84179 if( aiCol[i]==pTab->iPKey ){
84180 aiCol[i] = -1;
84182 #ifndef SQLITE_OMIT_AUTHORIZATION
84183 /* Request permission to read the parent key columns. If the
84184 ** authorization callback returns SQLITE_IGNORE, behave as if any
84185 ** values read from the parent table are NULL. */
84186 if( db->xAuth ){
84187 int rcauth;
84188 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
84189 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
84190 isIgnore = (rcauth==SQLITE_IGNORE);
84192 #endif
84195 /* Take a shared-cache advisory read-lock on the parent table. Allocate
84196 ** a cursor to use to search the unique index on the parent key columns
84197 ** in the parent table. */
84198 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
84199 pParse->nTab++;
84201 if( regOld!=0 ){
84202 /* A row is being removed from the child table. Search for the parent.
84203 ** If the parent does not exist, removing the child row resolves an
84204 ** outstanding foreign key constraint violation. */
84205 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
84207 if( regNew!=0 ){
84208 /* A row is being added to the child table. If a parent row cannot
84209 ** be found, adding the child row has violated the FK constraint. */
84210 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
84213 sqlite3DbFree(db, aiFree);
84216 /* Loop through all the foreign key constraints that refer to this table */
84217 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
84218 Index *pIdx = 0; /* Foreign key index for pFKey */
84219 SrcList *pSrc;
84220 int *aiCol = 0;
84222 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
84223 assert( regOld==0 && regNew!=0 );
84224 /* Inserting a single row into a parent table cannot cause an immediate
84225 ** foreign key violation. So do nothing in this case. */
84226 continue;
84229 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
84230 if( !isIgnoreErrors || db->mallocFailed ) return;
84231 continue;
84233 assert( aiCol || pFKey->nCol==1 );
84235 /* Create a SrcList structure containing a single table (the table
84236 ** the foreign key that refers to this table is attached to). This
84237 ** is required for the sqlite3WhereXXX() interface. */
84238 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
84239 if( pSrc ){
84240 struct SrcList_item *pItem = pSrc->a;
84241 pItem->pTab = pFKey->pFrom;
84242 pItem->zName = pFKey->pFrom->zName;
84243 pItem->pTab->nRef++;
84244 pItem->iCursor = pParse->nTab++;
84246 if( regNew!=0 ){
84247 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
84249 if( regOld!=0 ){
84250 /* If there is a RESTRICT action configured for the current operation
84251 ** on the parent table of this FK, then throw an exception
84252 ** immediately if the FK constraint is violated, even if this is a
84253 ** deferred trigger. That's what RESTRICT means. To defer checking
84254 ** the constraint, the FK should specify NO ACTION (represented
84255 ** using OE_None). NO ACTION is the default. */
84256 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
84258 pItem->zName = 0;
84259 sqlite3SrcListDelete(db, pSrc);
84261 sqlite3DbFree(db, aiCol);
84265 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
84268 ** This function is called before generating code to update or delete a
84269 ** row contained in table pTab.
84271 SQLITE_PRIVATE u32 sqlite3FkOldmask(
84272 Parse *pParse, /* Parse context */
84273 Table *pTab /* Table being modified */
84275 u32 mask = 0;
84276 if( pParse->db->flags&SQLITE_ForeignKeys ){
84277 FKey *p;
84278 int i;
84279 for(p=pTab->pFKey; p; p=p->pNextFrom){
84280 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
84282 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
84283 Index *pIdx = 0;
84284 locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
84285 if( pIdx ){
84286 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
84290 return mask;
84294 ** This function is called before generating code to update or delete a
84295 ** row contained in table pTab. If the operation is a DELETE, then
84296 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
84297 ** to an array of size N, where N is the number of columns in table pTab.
84298 ** If the i'th column is not modified by the UPDATE, then the corresponding
84299 ** entry in the aChange[] array is set to -1. If the column is modified,
84300 ** the value is 0 or greater. Parameter chngRowid is set to true if the
84301 ** UPDATE statement modifies the rowid fields of the table.
84303 ** If any foreign key processing will be required, this function returns
84304 ** true. If there is no foreign key related processing, this function
84305 ** returns false.
84307 SQLITE_PRIVATE int sqlite3FkRequired(
84308 Parse *pParse, /* Parse context */
84309 Table *pTab, /* Table being modified */
84310 int *aChange, /* Non-NULL for UPDATE operations */
84311 int chngRowid /* True for UPDATE that affects rowid */
84313 if( pParse->db->flags&SQLITE_ForeignKeys ){
84314 if( !aChange ){
84315 /* A DELETE operation. Foreign key processing is required if the
84316 ** table in question is either the child or parent table for any
84317 ** foreign key constraint. */
84318 return (sqlite3FkReferences(pTab) || pTab->pFKey);
84319 }else{
84320 /* This is an UPDATE. Foreign key processing is only required if the
84321 ** operation modifies one or more child or parent key columns. */
84322 int i;
84323 FKey *p;
84325 /* Check if any child key columns are being modified. */
84326 for(p=pTab->pFKey; p; p=p->pNextFrom){
84327 for(i=0; i<p->nCol; i++){
84328 int iChildKey = p->aCol[i].iFrom;
84329 if( aChange[iChildKey]>=0 ) return 1;
84330 if( iChildKey==pTab->iPKey && chngRowid ) return 1;
84334 /* Check if any parent key columns are being modified. */
84335 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
84336 for(i=0; i<p->nCol; i++){
84337 char *zKey = p->aCol[i].zCol;
84338 int iKey;
84339 for(iKey=0; iKey<pTab->nCol; iKey++){
84340 Column *pCol = &pTab->aCol[iKey];
84341 if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
84342 if( aChange[iKey]>=0 ) return 1;
84343 if( iKey==pTab->iPKey && chngRowid ) return 1;
84350 return 0;
84354 ** This function is called when an UPDATE or DELETE operation is being
84355 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
84356 ** If the current operation is an UPDATE, then the pChanges parameter is
84357 ** passed a pointer to the list of columns being modified. If it is a
84358 ** DELETE, pChanges is passed a NULL pointer.
84360 ** It returns a pointer to a Trigger structure containing a trigger
84361 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
84362 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
84363 ** returned (these actions require no special handling by the triggers
84364 ** sub-system, code for them is created by fkScanChildren()).
84366 ** For example, if pFKey is the foreign key and pTab is table "p" in
84367 ** the following schema:
84369 ** CREATE TABLE p(pk PRIMARY KEY);
84370 ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
84372 ** then the returned trigger structure is equivalent to:
84374 ** CREATE TRIGGER ... DELETE ON p BEGIN
84375 ** DELETE FROM c WHERE ck = old.pk;
84376 ** END;
84378 ** The returned pointer is cached as part of the foreign key object. It
84379 ** is eventually freed along with the rest of the foreign key object by
84380 ** sqlite3FkDelete().
84382 static Trigger *fkActionTrigger(
84383 Parse *pParse, /* Parse context */
84384 Table *pTab, /* Table being updated or deleted from */
84385 FKey *pFKey, /* Foreign key to get action for */
84386 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
84388 sqlite3 *db = pParse->db; /* Database handle */
84389 int action; /* One of OE_None, OE_Cascade etc. */
84390 Trigger *pTrigger; /* Trigger definition to return */
84391 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
84393 action = pFKey->aAction[iAction];
84394 pTrigger = pFKey->apTrigger[iAction];
84396 if( action!=OE_None && !pTrigger ){
84397 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
84398 char const *zFrom; /* Name of child table */
84399 int nFrom; /* Length in bytes of zFrom */
84400 Index *pIdx = 0; /* Parent key index for this FK */
84401 int *aiCol = 0; /* child table cols -> parent key cols */
84402 TriggerStep *pStep = 0; /* First (only) step of trigger program */
84403 Expr *pWhere = 0; /* WHERE clause of trigger step */
84404 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
84405 Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
84406 int i; /* Iterator variable */
84407 Expr *pWhen = 0; /* WHEN clause for the trigger */
84409 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
84410 assert( aiCol || pFKey->nCol==1 );
84412 for(i=0; i<pFKey->nCol; i++){
84413 Token tOld = { "old", 3 }; /* Literal "old" token */
84414 Token tNew = { "new", 3 }; /* Literal "new" token */
84415 Token tFromCol; /* Name of column in child table */
84416 Token tToCol; /* Name of column in parent table */
84417 int iFromCol; /* Idx of column in child table */
84418 Expr *pEq; /* tFromCol = OLD.tToCol */
84420 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
84421 assert( iFromCol>=0 );
84422 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
84423 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
84425 tToCol.n = sqlite3Strlen30(tToCol.z);
84426 tFromCol.n = sqlite3Strlen30(tFromCol.z);
84428 /* Create the expression "OLD.zToCol = zFromCol". It is important
84429 ** that the "OLD.zToCol" term is on the LHS of the = operator, so
84430 ** that the affinity and collation sequence associated with the
84431 ** parent table are used for the comparison. */
84432 pEq = sqlite3PExpr(pParse, TK_EQ,
84433 sqlite3PExpr(pParse, TK_DOT,
84434 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84435 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84436 , 0),
84437 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
84438 , 0);
84439 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
84441 /* For ON UPDATE, construct the next term of the WHEN clause.
84442 ** The final WHEN clause will be like this:
84444 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
84446 if( pChanges ){
84447 pEq = sqlite3PExpr(pParse, TK_IS,
84448 sqlite3PExpr(pParse, TK_DOT,
84449 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84450 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84452 sqlite3PExpr(pParse, TK_DOT,
84453 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84454 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84457 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
84460 if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
84461 Expr *pNew;
84462 if( action==OE_Cascade ){
84463 pNew = sqlite3PExpr(pParse, TK_DOT,
84464 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84465 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84466 , 0);
84467 }else if( action==OE_SetDflt ){
84468 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
84469 if( pDflt ){
84470 pNew = sqlite3ExprDup(db, pDflt, 0);
84471 }else{
84472 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84474 }else{
84475 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84477 pList = sqlite3ExprListAppend(pParse, pList, pNew);
84478 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
84481 sqlite3DbFree(db, aiCol);
84483 zFrom = pFKey->pFrom->zName;
84484 nFrom = sqlite3Strlen30(zFrom);
84486 if( action==OE_Restrict ){
84487 Token tFrom;
84488 Expr *pRaise;
84490 tFrom.z = zFrom;
84491 tFrom.n = nFrom;
84492 pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
84493 if( pRaise ){
84494 pRaise->affinity = OE_Abort;
84496 pSelect = sqlite3SelectNew(pParse,
84497 sqlite3ExprListAppend(pParse, 0, pRaise),
84498 sqlite3SrcListAppend(db, 0, &tFrom, 0),
84499 pWhere,
84500 0, 0, 0, 0, 0, 0
84502 pWhere = 0;
84505 /* Disable lookaside memory allocation */
84506 enableLookaside = db->lookaside.bEnabled;
84507 db->lookaside.bEnabled = 0;
84509 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
84510 sizeof(Trigger) + /* struct Trigger */
84511 sizeof(TriggerStep) + /* Single step in trigger program */
84512 nFrom + 1 /* Space for pStep->target.z */
84514 if( pTrigger ){
84515 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
84516 pStep->target.z = (char *)&pStep[1];
84517 pStep->target.n = nFrom;
84518 memcpy((char *)pStep->target.z, zFrom, nFrom);
84520 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
84521 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
84522 pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
84523 if( pWhen ){
84524 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
84525 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
84529 /* Re-enable the lookaside buffer, if it was disabled earlier. */
84530 db->lookaside.bEnabled = enableLookaside;
84532 sqlite3ExprDelete(db, pWhere);
84533 sqlite3ExprDelete(db, pWhen);
84534 sqlite3ExprListDelete(db, pList);
84535 sqlite3SelectDelete(db, pSelect);
84536 if( db->mallocFailed==1 ){
84537 fkTriggerDelete(db, pTrigger);
84538 return 0;
84541 switch( action ){
84542 case OE_Restrict:
84543 pStep->op = TK_SELECT;
84544 break;
84545 case OE_Cascade:
84546 if( !pChanges ){
84547 pStep->op = TK_DELETE;
84548 break;
84550 default:
84551 pStep->op = TK_UPDATE;
84553 pStep->pTrig = pTrigger;
84554 pTrigger->pSchema = pTab->pSchema;
84555 pTrigger->pTabSchema = pTab->pSchema;
84556 pFKey->apTrigger[iAction] = pTrigger;
84557 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
84560 return pTrigger;
84564 ** This function is called when deleting or updating a row to implement
84565 ** any required CASCADE, SET NULL or SET DEFAULT actions.
84567 SQLITE_PRIVATE void sqlite3FkActions(
84568 Parse *pParse, /* Parse context */
84569 Table *pTab, /* Table being updated or deleted from */
84570 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
84571 int regOld /* Address of array containing old row */
84573 /* If foreign-key support is enabled, iterate through all FKs that
84574 ** refer to table pTab. If there is an action associated with the FK
84575 ** for this operation (either update or delete), invoke the associated
84576 ** trigger sub-program. */
84577 if( pParse->db->flags&SQLITE_ForeignKeys ){
84578 FKey *pFKey; /* Iterator variable */
84579 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
84580 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
84581 if( pAction ){
84582 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
84588 #endif /* ifndef SQLITE_OMIT_TRIGGER */
84591 ** Free all memory associated with foreign key definitions attached to
84592 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
84593 ** hash table.
84595 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
84596 FKey *pFKey; /* Iterator variable */
84597 FKey *pNext; /* Copy of pFKey->pNextFrom */
84599 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
84600 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
84602 /* Remove the FK from the fkeyHash hash table. */
84603 if( !db || db->pnBytesFreed==0 ){
84604 if( pFKey->pPrevTo ){
84605 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
84606 }else{
84607 void *p = (void *)pFKey->pNextTo;
84608 const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
84609 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
84611 if( pFKey->pNextTo ){
84612 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
84616 /* EV: R-30323-21917 Each foreign key constraint in SQLite is
84617 ** classified as either immediate or deferred.
84619 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
84621 /* Delete any triggers created to implement actions for this FK. */
84622 #ifndef SQLITE_OMIT_TRIGGER
84623 fkTriggerDelete(db, pFKey->apTrigger[0]);
84624 fkTriggerDelete(db, pFKey->apTrigger[1]);
84625 #endif
84627 pNext = pFKey->pNextFrom;
84628 sqlite3DbFree(db, pFKey);
84631 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
84633 /************** End of fkey.c ************************************************/
84634 /************** Begin file insert.c ******************************************/
84636 ** 2001 September 15
84638 ** The author disclaims copyright to this source code. In place of
84639 ** a legal notice, here is a blessing:
84641 ** May you do good and not evil.
84642 ** May you find forgiveness for yourself and forgive others.
84643 ** May you share freely, never taking more than you give.
84645 *************************************************************************
84646 ** This file contains C code routines that are called by the parser
84647 ** to handle INSERT statements in SQLite.
84651 ** Generate code that will open a table for reading.
84653 SQLITE_PRIVATE void sqlite3OpenTable(
84654 Parse *p, /* Generate code into this VDBE */
84655 int iCur, /* The cursor number of the table */
84656 int iDb, /* The database index in sqlite3.aDb[] */
84657 Table *pTab, /* The table to be opened */
84658 int opcode /* OP_OpenRead or OP_OpenWrite */
84660 Vdbe *v;
84661 if( IsVirtual(pTab) ) return;
84662 v = sqlite3GetVdbe(p);
84663 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
84664 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
84665 sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
84666 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
84667 VdbeComment((v, "%s", pTab->zName));
84671 ** Return a pointer to the column affinity string associated with index
84672 ** pIdx. A column affinity string has one character for each column in
84673 ** the table, according to the affinity of the column:
84675 ** Character Column affinity
84676 ** ------------------------------
84677 ** 'a' TEXT
84678 ** 'b' NONE
84679 ** 'c' NUMERIC
84680 ** 'd' INTEGER
84681 ** 'e' REAL
84683 ** An extra 'b' is appended to the end of the string to cover the
84684 ** rowid that appears as the last column in every index.
84686 ** Memory for the buffer containing the column index affinity string
84687 ** is managed along with the rest of the Index structure. It will be
84688 ** released when sqlite3DeleteIndex() is called.
84690 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
84691 if( !pIdx->zColAff ){
84692 /* The first time a column affinity string for a particular index is
84693 ** required, it is allocated and populated here. It is then stored as
84694 ** a member of the Index structure for subsequent use.
84696 ** The column affinity string will eventually be deleted by
84697 ** sqliteDeleteIndex() when the Index structure itself is cleaned
84698 ** up.
84700 int n;
84701 Table *pTab = pIdx->pTable;
84702 sqlite3 *db = sqlite3VdbeDb(v);
84703 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
84704 if( !pIdx->zColAff ){
84705 db->mallocFailed = 1;
84706 return 0;
84708 for(n=0; n<pIdx->nColumn; n++){
84709 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
84711 pIdx->zColAff[n++] = SQLITE_AFF_NONE;
84712 pIdx->zColAff[n] = 0;
84715 return pIdx->zColAff;
84719 ** Set P4 of the most recently inserted opcode to a column affinity
84720 ** string for table pTab. A column affinity string has one character
84721 ** for each column indexed by the index, according to the affinity of the
84722 ** column:
84724 ** Character Column affinity
84725 ** ------------------------------
84726 ** 'a' TEXT
84727 ** 'b' NONE
84728 ** 'c' NUMERIC
84729 ** 'd' INTEGER
84730 ** 'e' REAL
84732 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
84733 /* The first time a column affinity string for a particular table
84734 ** is required, it is allocated and populated here. It is then
84735 ** stored as a member of the Table structure for subsequent use.
84737 ** The column affinity string will eventually be deleted by
84738 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
84740 if( !pTab->zColAff ){
84741 char *zColAff;
84742 int i;
84743 sqlite3 *db = sqlite3VdbeDb(v);
84745 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
84746 if( !zColAff ){
84747 db->mallocFailed = 1;
84748 return;
84751 for(i=0; i<pTab->nCol; i++){
84752 zColAff[i] = pTab->aCol[i].affinity;
84754 zColAff[pTab->nCol] = '\0';
84756 pTab->zColAff = zColAff;
84759 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
84763 ** Return non-zero if the table pTab in database iDb or any of its indices
84764 ** have been opened at any point in the VDBE program beginning at location
84765 ** iStartAddr throught the end of the program. This is used to see if
84766 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
84767 ** run without using temporary table for the results of the SELECT.
84769 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
84770 Vdbe *v = sqlite3GetVdbe(p);
84771 int i;
84772 int iEnd = sqlite3VdbeCurrentAddr(v);
84773 #ifndef SQLITE_OMIT_VIRTUALTABLE
84774 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
84775 #endif
84777 for(i=iStartAddr; i<iEnd; i++){
84778 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
84779 assert( pOp!=0 );
84780 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
84781 Index *pIndex;
84782 int tnum = pOp->p2;
84783 if( tnum==pTab->tnum ){
84784 return 1;
84786 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84787 if( tnum==pIndex->tnum ){
84788 return 1;
84792 #ifndef SQLITE_OMIT_VIRTUALTABLE
84793 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
84794 assert( pOp->p4.pVtab!=0 );
84795 assert( pOp->p4type==P4_VTAB );
84796 return 1;
84798 #endif
84800 return 0;
84803 #ifndef SQLITE_OMIT_AUTOINCREMENT
84805 ** Locate or create an AutoincInfo structure associated with table pTab
84806 ** which is in database iDb. Return the register number for the register
84807 ** that holds the maximum rowid.
84809 ** There is at most one AutoincInfo structure per table even if the
84810 ** same table is autoincremented multiple times due to inserts within
84811 ** triggers. A new AutoincInfo structure is created if this is the
84812 ** first use of table pTab. On 2nd and subsequent uses, the original
84813 ** AutoincInfo structure is used.
84815 ** Three memory locations are allocated:
84817 ** (1) Register to hold the name of the pTab table.
84818 ** (2) Register to hold the maximum ROWID of pTab.
84819 ** (3) Register to hold the rowid in sqlite_sequence of pTab
84821 ** The 2nd register is the one that is returned. That is all the
84822 ** insert routine needs to know about.
84824 static int autoIncBegin(
84825 Parse *pParse, /* Parsing context */
84826 int iDb, /* Index of the database holding pTab */
84827 Table *pTab /* The table we are writing to */
84829 int memId = 0; /* Register holding maximum rowid */
84830 if( pTab->tabFlags & TF_Autoincrement ){
84831 Parse *pToplevel = sqlite3ParseToplevel(pParse);
84832 AutoincInfo *pInfo;
84834 pInfo = pToplevel->pAinc;
84835 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
84836 if( pInfo==0 ){
84837 pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
84838 if( pInfo==0 ) return 0;
84839 pInfo->pNext = pToplevel->pAinc;
84840 pToplevel->pAinc = pInfo;
84841 pInfo->pTab = pTab;
84842 pInfo->iDb = iDb;
84843 pToplevel->nMem++; /* Register to hold name of table */
84844 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
84845 pToplevel->nMem++; /* Rowid in sqlite_sequence */
84847 memId = pInfo->regCtr;
84849 return memId;
84853 ** This routine generates code that will initialize all of the
84854 ** register used by the autoincrement tracker.
84856 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
84857 AutoincInfo *p; /* Information about an AUTOINCREMENT */
84858 sqlite3 *db = pParse->db; /* The database connection */
84859 Db *pDb; /* Database only autoinc table */
84860 int memId; /* Register holding max rowid */
84861 int addr; /* A VDBE address */
84862 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
84864 /* This routine is never called during trigger-generation. It is
84865 ** only called from the top-level */
84866 assert( pParse->pTriggerTab==0 );
84867 assert( pParse==sqlite3ParseToplevel(pParse) );
84869 assert( v ); /* We failed long ago if this is not so */
84870 for(p = pParse->pAinc; p; p = p->pNext){
84871 pDb = &db->aDb[p->iDb];
84872 memId = p->regCtr;
84873 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
84874 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
84875 addr = sqlite3VdbeCurrentAddr(v);
84876 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
84877 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
84878 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
84879 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
84880 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
84881 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
84882 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
84883 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
84884 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
84885 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
84886 sqlite3VdbeAddOp0(v, OP_Close);
84891 ** Update the maximum rowid for an autoincrement calculation.
84893 ** This routine should be called when the top of the stack holds a
84894 ** new rowid that is about to be inserted. If that new rowid is
84895 ** larger than the maximum rowid in the memId memory cell, then the
84896 ** memory cell is updated. The stack is unchanged.
84898 static void autoIncStep(Parse *pParse, int memId, int regRowid){
84899 if( memId>0 ){
84900 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
84905 ** This routine generates the code needed to write autoincrement
84906 ** maximum rowid values back into the sqlite_sequence register.
84907 ** Every statement that might do an INSERT into an autoincrement
84908 ** table (either directly or through triggers) needs to call this
84909 ** routine just before the "exit" code.
84911 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
84912 AutoincInfo *p;
84913 Vdbe *v = pParse->pVdbe;
84914 sqlite3 *db = pParse->db;
84916 assert( v );
84917 for(p = pParse->pAinc; p; p = p->pNext){
84918 Db *pDb = &db->aDb[p->iDb];
84919 int j1, j2, j3, j4, j5;
84920 int iRec;
84921 int memId = p->regCtr;
84923 iRec = sqlite3GetTempReg(pParse);
84924 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
84925 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
84926 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
84927 j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
84928 j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
84929 j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
84930 sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
84931 sqlite3VdbeJumpHere(v, j2);
84932 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
84933 j5 = sqlite3VdbeAddOp0(v, OP_Goto);
84934 sqlite3VdbeJumpHere(v, j4);
84935 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
84936 sqlite3VdbeJumpHere(v, j1);
84937 sqlite3VdbeJumpHere(v, j5);
84938 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
84939 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
84940 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
84941 sqlite3VdbeAddOp0(v, OP_Close);
84942 sqlite3ReleaseTempReg(pParse, iRec);
84945 #else
84947 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
84948 ** above are all no-ops
84950 # define autoIncBegin(A,B,C) (0)
84951 # define autoIncStep(A,B,C)
84952 #endif /* SQLITE_OMIT_AUTOINCREMENT */
84955 /* Forward declaration */
84956 static int xferOptimization(
84957 Parse *pParse, /* Parser context */
84958 Table *pDest, /* The table we are inserting into */
84959 Select *pSelect, /* A SELECT statement to use as the data source */
84960 int onError, /* How to handle constraint errors */
84961 int iDbDest /* The database of pDest */
84965 ** This routine is call to handle SQL of the following forms:
84967 ** insert into TABLE (IDLIST) values(EXPRLIST)
84968 ** insert into TABLE (IDLIST) select
84970 ** The IDLIST following the table name is always optional. If omitted,
84971 ** then a list of all columns for the table is substituted. The IDLIST
84972 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
84974 ** The pList parameter holds EXPRLIST in the first form of the INSERT
84975 ** statement above, and pSelect is NULL. For the second form, pList is
84976 ** NULL and pSelect is a pointer to the select statement used to generate
84977 ** data for the insert.
84979 ** The code generated follows one of four templates. For a simple
84980 ** select with data coming from a VALUES clause, the code executes
84981 ** once straight down through. Pseudo-code follows (we call this
84982 ** the "1st template"):
84984 ** open write cursor to <table> and its indices
84985 ** puts VALUES clause expressions onto the stack
84986 ** write the resulting record into <table>
84987 ** cleanup
84989 ** The three remaining templates assume the statement is of the form
84991 ** INSERT INTO <table> SELECT ...
84993 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
84994 ** in other words if the SELECT pulls all columns from a single table
84995 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
84996 ** if <table2> and <table1> are distinct tables but have identical
84997 ** schemas, including all the same indices, then a special optimization
84998 ** is invoked that copies raw records from <table2> over to <table1>.
84999 ** See the xferOptimization() function for the implementation of this
85000 ** template. This is the 2nd template.
85002 ** open a write cursor to <table>
85003 ** open read cursor on <table2>
85004 ** transfer all records in <table2> over to <table>
85005 ** close cursors
85006 ** foreach index on <table>
85007 ** open a write cursor on the <table> index
85008 ** open a read cursor on the corresponding <table2> index
85009 ** transfer all records from the read to the write cursors
85010 ** close cursors
85011 ** end foreach
85013 ** The 3rd template is for when the second template does not apply
85014 ** and the SELECT clause does not read from <table> at any time.
85015 ** The generated code follows this template:
85017 ** EOF <- 0
85018 ** X <- A
85019 ** goto B
85020 ** A: setup for the SELECT
85021 ** loop over the rows in the SELECT
85022 ** load values into registers R..R+n
85023 ** yield X
85024 ** end loop
85025 ** cleanup after the SELECT
85026 ** EOF <- 1
85027 ** yield X
85028 ** goto A
85029 ** B: open write cursor to <table> and its indices
85030 ** C: yield X
85031 ** if EOF goto D
85032 ** insert the select result into <table> from R..R+n
85033 ** goto C
85034 ** D: cleanup
85036 ** The 4th template is used if the insert statement takes its
85037 ** values from a SELECT but the data is being inserted into a table
85038 ** that is also read as part of the SELECT. In the third form,
85039 ** we have to use a intermediate table to store the results of
85040 ** the select. The template is like this:
85042 ** EOF <- 0
85043 ** X <- A
85044 ** goto B
85045 ** A: setup for the SELECT
85046 ** loop over the tables in the SELECT
85047 ** load value into register R..R+n
85048 ** yield X
85049 ** end loop
85050 ** cleanup after the SELECT
85051 ** EOF <- 1
85052 ** yield X
85053 ** halt-error
85054 ** B: open temp table
85055 ** L: yield X
85056 ** if EOF goto M
85057 ** insert row from R..R+n into temp table
85058 ** goto L
85059 ** M: open write cursor to <table> and its indices
85060 ** rewind temp table
85061 ** C: loop over rows of intermediate table
85062 ** transfer values form intermediate table into <table>
85063 ** end loop
85064 ** D: cleanup
85066 SQLITE_PRIVATE void sqlite3Insert(
85067 Parse *pParse, /* Parser context */
85068 SrcList *pTabList, /* Name of table into which we are inserting */
85069 ExprList *pList, /* List of values to be inserted */
85070 Select *pSelect, /* A SELECT statement to use as the data source */
85071 IdList *pColumn, /* Column names corresponding to IDLIST. */
85072 int onError /* How to handle constraint errors */
85074 sqlite3 *db; /* The main database structure */
85075 Table *pTab; /* The table to insert into. aka TABLE */
85076 char *zTab; /* Name of the table into which we are inserting */
85077 const char *zDb; /* Name of the database holding this table */
85078 int i, j, idx; /* Loop counters */
85079 Vdbe *v; /* Generate code into this virtual machine */
85080 Index *pIdx; /* For looping over indices of the table */
85081 int nColumn; /* Number of columns in the data */
85082 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
85083 int baseCur = 0; /* VDBE Cursor number for pTab */
85084 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
85085 int endOfLoop; /* Label for the end of the insertion loop */
85086 int useTempTable = 0; /* Store SELECT results in intermediate table */
85087 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
85088 int addrInsTop = 0; /* Jump to label "D" */
85089 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
85090 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
85091 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
85092 int iDb; /* Index of database holding TABLE */
85093 Db *pDb; /* The database containing table being inserted into */
85094 int appendFlag = 0; /* True if the insert is likely to be an append */
85096 /* Register allocations */
85097 int regFromSelect = 0;/* Base register for data coming from SELECT */
85098 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
85099 int regRowCount = 0; /* Memory cell used for the row counter */
85100 int regIns; /* Block of regs holding rowid+data being inserted */
85101 int regRowid; /* registers holding insert rowid */
85102 int regData; /* register holding first column to insert */
85103 int regEof = 0; /* Register recording end of SELECT data */
85104 int *aRegIdx = 0; /* One register allocated to each index */
85106 #ifndef SQLITE_OMIT_TRIGGER
85107 int isView; /* True if attempting to insert into a view */
85108 Trigger *pTrigger; /* List of triggers on pTab, if required */
85109 int tmask; /* Mask of trigger times */
85110 #endif
85112 db = pParse->db;
85113 memset(&dest, 0, sizeof(dest));
85114 if( pParse->nErr || db->mallocFailed ){
85115 goto insert_cleanup;
85118 /* Locate the table into which we will be inserting new information.
85120 assert( pTabList->nSrc==1 );
85121 zTab = pTabList->a[0].zName;
85122 if( NEVER(zTab==0) ) goto insert_cleanup;
85123 pTab = sqlite3SrcListLookup(pParse, pTabList);
85124 if( pTab==0 ){
85125 goto insert_cleanup;
85127 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85128 assert( iDb<db->nDb );
85129 pDb = &db->aDb[iDb];
85130 zDb = pDb->zName;
85131 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
85132 goto insert_cleanup;
85135 /* Figure out if we have any triggers and if the table being
85136 ** inserted into is a view
85138 #ifndef SQLITE_OMIT_TRIGGER
85139 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
85140 isView = pTab->pSelect!=0;
85141 #else
85142 # define pTrigger 0
85143 # define tmask 0
85144 # define isView 0
85145 #endif
85146 #ifdef SQLITE_OMIT_VIEW
85147 # undef isView
85148 # define isView 0
85149 #endif
85150 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
85152 /* If pTab is really a view, make sure it has been initialized.
85153 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
85154 ** module table).
85156 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85157 goto insert_cleanup;
85160 /* Ensure that:
85161 * (a) the table is not read-only,
85162 * (b) that if it is a view then ON INSERT triggers exist
85164 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
85165 goto insert_cleanup;
85168 /* Allocate a VDBE
85170 v = sqlite3GetVdbe(pParse);
85171 if( v==0 ) goto insert_cleanup;
85172 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
85173 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
85175 #ifndef SQLITE_OMIT_XFER_OPT
85176 /* If the statement is of the form
85178 ** INSERT INTO <table1> SELECT * FROM <table2>;
85180 ** Then special optimizations can be applied that make the transfer
85181 ** very fast and which reduce fragmentation of indices.
85183 ** This is the 2nd template.
85185 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
85186 assert( !pTrigger );
85187 assert( pList==0 );
85188 goto insert_end;
85190 #endif /* SQLITE_OMIT_XFER_OPT */
85192 /* If this is an AUTOINCREMENT table, look up the sequence number in the
85193 ** sqlite_sequence table and store it in memory cell regAutoinc.
85195 regAutoinc = autoIncBegin(pParse, iDb, pTab);
85197 /* Figure out how many columns of data are supplied. If the data
85198 ** is coming from a SELECT statement, then generate a co-routine that
85199 ** produces a single row of the SELECT on each invocation. The
85200 ** co-routine is the common header to the 3rd and 4th templates.
85202 if( pSelect ){
85203 /* Data is coming from a SELECT. Generate code to implement that SELECT
85204 ** as a co-routine. The code is common to both the 3rd and 4th
85205 ** templates:
85207 ** EOF <- 0
85208 ** X <- A
85209 ** goto B
85210 ** A: setup for the SELECT
85211 ** loop over the tables in the SELECT
85212 ** load value into register R..R+n
85213 ** yield X
85214 ** end loop
85215 ** cleanup after the SELECT
85216 ** EOF <- 1
85217 ** yield X
85218 ** halt-error
85220 ** On each invocation of the co-routine, it puts a single row of the
85221 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
85222 ** (These output registers are allocated by sqlite3Select().) When
85223 ** the SELECT completes, it sets the EOF flag stored in regEof.
85225 int rc, j1;
85227 regEof = ++pParse->nMem;
85228 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
85229 VdbeComment((v, "SELECT eof flag"));
85230 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
85231 addrSelect = sqlite3VdbeCurrentAddr(v)+2;
85232 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
85233 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
85234 VdbeComment((v, "Jump over SELECT coroutine"));
85236 /* Resolve the expressions in the SELECT statement and execute it. */
85237 rc = sqlite3Select(pParse, pSelect, &dest);
85238 assert( pParse->nErr==0 || rc );
85239 if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
85240 goto insert_cleanup;
85242 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
85243 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
85244 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
85245 VdbeComment((v, "End of SELECT coroutine"));
85246 sqlite3VdbeJumpHere(v, j1); /* label B: */
85248 regFromSelect = dest.iMem;
85249 assert( pSelect->pEList );
85250 nColumn = pSelect->pEList->nExpr;
85251 assert( dest.nMem==nColumn );
85253 /* Set useTempTable to TRUE if the result of the SELECT statement
85254 ** should be written into a temporary table (template 4). Set to
85255 ** FALSE if each* row of the SELECT can be written directly into
85256 ** the destination table (template 3).
85258 ** A temp table must be used if the table being updated is also one
85259 ** of the tables being read by the SELECT statement. Also use a
85260 ** temp table in the case of row triggers.
85262 if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
85263 useTempTable = 1;
85266 if( useTempTable ){
85267 /* Invoke the coroutine to extract information from the SELECT
85268 ** and add it to a transient table srcTab. The code generated
85269 ** here is from the 4th template:
85271 ** B: open temp table
85272 ** L: yield X
85273 ** if EOF goto M
85274 ** insert row from R..R+n into temp table
85275 ** goto L
85276 ** M: ...
85278 int regRec; /* Register to hold packed record */
85279 int regTempRowid; /* Register to hold temp table ROWID */
85280 int addrTop; /* Label "L" */
85281 int addrIf; /* Address of jump to M */
85283 srcTab = pParse->nTab++;
85284 regRec = sqlite3GetTempReg(pParse);
85285 regTempRowid = sqlite3GetTempReg(pParse);
85286 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
85287 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85288 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
85289 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
85290 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
85291 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
85292 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
85293 sqlite3VdbeJumpHere(v, addrIf);
85294 sqlite3ReleaseTempReg(pParse, regRec);
85295 sqlite3ReleaseTempReg(pParse, regTempRowid);
85297 }else{
85298 /* This is the case if the data for the INSERT is coming from a VALUES
85299 ** clause
85301 NameContext sNC;
85302 memset(&sNC, 0, sizeof(sNC));
85303 sNC.pParse = pParse;
85304 srcTab = -1;
85305 assert( useTempTable==0 );
85306 nColumn = pList ? pList->nExpr : 0;
85307 for(i=0; i<nColumn; i++){
85308 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
85309 goto insert_cleanup;
85314 /* Make sure the number of columns in the source data matches the number
85315 ** of columns to be inserted into the table.
85317 if( IsVirtual(pTab) ){
85318 for(i=0; i<pTab->nCol; i++){
85319 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
85322 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
85323 sqlite3ErrorMsg(pParse,
85324 "table %S has %d columns but %d values were supplied",
85325 pTabList, 0, pTab->nCol-nHidden, nColumn);
85326 goto insert_cleanup;
85328 if( pColumn!=0 && nColumn!=pColumn->nId ){
85329 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
85330 goto insert_cleanup;
85333 /* If the INSERT statement included an IDLIST term, then make sure
85334 ** all elements of the IDLIST really are columns of the table and
85335 ** remember the column indices.
85337 ** If the table has an INTEGER PRIMARY KEY column and that column
85338 ** is named in the IDLIST, then record in the keyColumn variable
85339 ** the index into IDLIST of the primary key column. keyColumn is
85340 ** the index of the primary key as it appears in IDLIST, not as
85341 ** is appears in the original table. (The index of the primary
85342 ** key in the original table is pTab->iPKey.)
85344 if( pColumn ){
85345 for(i=0; i<pColumn->nId; i++){
85346 pColumn->a[i].idx = -1;
85348 for(i=0; i<pColumn->nId; i++){
85349 for(j=0; j<pTab->nCol; j++){
85350 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
85351 pColumn->a[i].idx = j;
85352 if( j==pTab->iPKey ){
85353 keyColumn = i;
85355 break;
85358 if( j>=pTab->nCol ){
85359 if( sqlite3IsRowid(pColumn->a[i].zName) ){
85360 keyColumn = i;
85361 }else{
85362 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
85363 pTabList, 0, pColumn->a[i].zName);
85364 pParse->checkSchema = 1;
85365 goto insert_cleanup;
85371 /* If there is no IDLIST term but the table has an integer primary
85372 ** key, the set the keyColumn variable to the primary key column index
85373 ** in the original table definition.
85375 if( pColumn==0 && nColumn>0 ){
85376 keyColumn = pTab->iPKey;
85379 /* Initialize the count of rows to be inserted
85381 if( db->flags & SQLITE_CountRows ){
85382 regRowCount = ++pParse->nMem;
85383 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
85386 /* If this is not a view, open the table and and all indices */
85387 if( !isView ){
85388 int nIdx;
85390 baseCur = pParse->nTab;
85391 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
85392 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
85393 if( aRegIdx==0 ){
85394 goto insert_cleanup;
85396 for(i=0; i<nIdx; i++){
85397 aRegIdx[i] = ++pParse->nMem;
85401 /* This is the top of the main insertion loop */
85402 if( useTempTable ){
85403 /* This block codes the top of loop only. The complete loop is the
85404 ** following pseudocode (template 4):
85406 ** rewind temp table
85407 ** C: loop over rows of intermediate table
85408 ** transfer values form intermediate table into <table>
85409 ** end loop
85410 ** D: ...
85412 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
85413 addrCont = sqlite3VdbeCurrentAddr(v);
85414 }else if( pSelect ){
85415 /* This block codes the top of loop only. The complete loop is the
85416 ** following pseudocode (template 3):
85418 ** C: yield X
85419 ** if EOF goto D
85420 ** insert the select result into <table> from R..R+n
85421 ** goto C
85422 ** D: ...
85424 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85425 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
85428 /* Allocate registers for holding the rowid of the new row,
85429 ** the content of the new row, and the assemblied row record.
85431 regRowid = regIns = pParse->nMem+1;
85432 pParse->nMem += pTab->nCol + 1;
85433 if( IsVirtual(pTab) ){
85434 regRowid++;
85435 pParse->nMem++;
85437 regData = regRowid+1;
85439 /* Run the BEFORE and INSTEAD OF triggers, if there are any
85441 endOfLoop = sqlite3VdbeMakeLabel(v);
85442 if( tmask & TRIGGER_BEFORE ){
85443 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
85445 /* build the NEW.* reference row. Note that if there is an INTEGER
85446 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
85447 ** translated into a unique ID for the row. But on a BEFORE trigger,
85448 ** we do not know what the unique ID will be (because the insert has
85449 ** not happened yet) so we substitute a rowid of -1
85451 if( keyColumn<0 ){
85452 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85453 }else{
85454 int j1;
85455 if( useTempTable ){
85456 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
85457 }else{
85458 assert( pSelect==0 ); /* Otherwise useTempTable is true */
85459 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
85461 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
85462 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85463 sqlite3VdbeJumpHere(v, j1);
85464 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
85467 /* Cannot have triggers on a virtual table. If it were possible,
85468 ** this block would have to account for hidden column.
85470 assert( !IsVirtual(pTab) );
85472 /* Create the new column data
85474 for(i=0; i<pTab->nCol; i++){
85475 if( pColumn==0 ){
85476 j = i;
85477 }else{
85478 for(j=0; j<pColumn->nId; j++){
85479 if( pColumn->a[j].idx==i ) break;
85482 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
85483 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
85484 }else if( useTempTable ){
85485 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
85486 }else{
85487 assert( pSelect==0 ); /* Otherwise useTempTable is true */
85488 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
85492 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
85493 ** do not attempt any conversions before assembling the record.
85494 ** If this is a real table, attempt conversions as required by the
85495 ** table column affinities.
85497 if( !isView ){
85498 sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
85499 sqlite3TableAffinityStr(v, pTab);
85502 /* Fire BEFORE or INSTEAD OF triggers */
85503 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
85504 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
85506 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
85509 /* Push the record number for the new entry onto the stack. The
85510 ** record number is a randomly generate integer created by NewRowid
85511 ** except when the table has an INTEGER PRIMARY KEY column, in which
85512 ** case the record number is the same as that column.
85514 if( !isView ){
85515 if( IsVirtual(pTab) ){
85516 /* The row that the VUpdate opcode will delete: none */
85517 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
85519 if( keyColumn>=0 ){
85520 if( useTempTable ){
85521 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
85522 }else if( pSelect ){
85523 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
85524 }else{
85525 VdbeOp *pOp;
85526 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
85527 pOp = sqlite3VdbeGetOp(v, -1);
85528 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
85529 appendFlag = 1;
85530 pOp->opcode = OP_NewRowid;
85531 pOp->p1 = baseCur;
85532 pOp->p2 = regRowid;
85533 pOp->p3 = regAutoinc;
85536 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
85537 ** to generate a unique primary key value.
85539 if( !appendFlag ){
85540 int j1;
85541 if( !IsVirtual(pTab) ){
85542 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
85543 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85544 sqlite3VdbeJumpHere(v, j1);
85545 }else{
85546 j1 = sqlite3VdbeCurrentAddr(v);
85547 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
85549 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
85551 }else if( IsVirtual(pTab) ){
85552 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
85553 }else{
85554 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85555 appendFlag = 1;
85557 autoIncStep(pParse, regAutoinc, regRowid);
85559 /* Push onto the stack, data for all columns of the new entry, beginning
85560 ** with the first column.
85562 nHidden = 0;
85563 for(i=0; i<pTab->nCol; i++){
85564 int iRegStore = regRowid+1+i;
85565 if( i==pTab->iPKey ){
85566 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
85567 ** Whenever this column is read, the record number will be substituted
85568 ** in its place. So will fill this column with a NULL to avoid
85569 ** taking up data space with information that will never be used. */
85570 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
85571 continue;
85573 if( pColumn==0 ){
85574 if( IsHiddenColumn(&pTab->aCol[i]) ){
85575 assert( IsVirtual(pTab) );
85576 j = -1;
85577 nHidden++;
85578 }else{
85579 j = i - nHidden;
85581 }else{
85582 for(j=0; j<pColumn->nId; j++){
85583 if( pColumn->a[j].idx==i ) break;
85586 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
85587 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
85588 }else if( useTempTable ){
85589 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
85590 }else if( pSelect ){
85591 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
85592 }else{
85593 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
85597 /* Generate code to check constraints and generate index keys and
85598 ** do the insertion.
85600 #ifndef SQLITE_OMIT_VIRTUALTABLE
85601 if( IsVirtual(pTab) ){
85602 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
85603 sqlite3VtabMakeWritable(pParse, pTab);
85604 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
85605 sqlite3MayAbort(pParse);
85606 }else
85607 #endif
85609 int isReplace; /* Set to true if constraints may cause a replace */
85610 sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
85611 keyColumn>=0, 0, onError, endOfLoop, &isReplace
85613 sqlite3FkCheck(pParse, pTab, 0, regIns);
85614 sqlite3CompleteInsertion(
85615 pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
85620 /* Update the count of rows that are inserted
85622 if( (db->flags & SQLITE_CountRows)!=0 ){
85623 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
85626 if( pTrigger ){
85627 /* Code AFTER triggers */
85628 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
85629 pTab, regData-2-pTab->nCol, onError, endOfLoop);
85632 /* The bottom of the main insertion loop, if the data source
85633 ** is a SELECT statement.
85635 sqlite3VdbeResolveLabel(v, endOfLoop);
85636 if( useTempTable ){
85637 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
85638 sqlite3VdbeJumpHere(v, addrInsTop);
85639 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
85640 }else if( pSelect ){
85641 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
85642 sqlite3VdbeJumpHere(v, addrInsTop);
85645 if( !IsVirtual(pTab) && !isView ){
85646 /* Close all tables opened */
85647 sqlite3VdbeAddOp1(v, OP_Close, baseCur);
85648 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
85649 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
85653 insert_end:
85654 /* Update the sqlite_sequence table by storing the content of the
85655 ** maximum rowid counter values recorded while inserting into
85656 ** autoincrement tables.
85658 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85659 sqlite3AutoincrementEnd(pParse);
85663 ** Return the number of rows inserted. If this routine is
85664 ** generating code because of a call to sqlite3NestedParse(), do not
85665 ** invoke the callback function.
85667 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85668 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
85669 sqlite3VdbeSetNumCols(v, 1);
85670 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
85673 insert_cleanup:
85674 sqlite3SrcListDelete(db, pTabList);
85675 sqlite3ExprListDelete(db, pList);
85676 sqlite3SelectDelete(db, pSelect);
85677 sqlite3IdListDelete(db, pColumn);
85678 sqlite3DbFree(db, aRegIdx);
85681 /* Make sure "isView" and other macros defined above are undefined. Otherwise
85682 ** thely may interfere with compilation of other functions in this file
85683 ** (or in another file, if this file becomes part of the amalgamation). */
85684 #ifdef isView
85685 #undef isView
85686 #endif
85687 #ifdef pTrigger
85688 #undef pTrigger
85689 #endif
85690 #ifdef tmask
85691 #undef tmask
85692 #endif
85696 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
85698 ** The input is a range of consecutive registers as follows:
85700 ** 1. The rowid of the row after the update.
85702 ** 2. The data in the first column of the entry after the update.
85704 ** i. Data from middle columns...
85706 ** N. The data in the last column of the entry after the update.
85708 ** The regRowid parameter is the index of the register containing (1).
85710 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
85711 ** the address of a register containing the rowid before the update takes
85712 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
85713 ** is false, indicating an INSERT statement, then a non-zero rowidChng
85714 ** indicates that the rowid was explicitly specified as part of the
85715 ** INSERT statement. If rowidChng is false, it means that the rowid is
85716 ** computed automatically in an insert or that the rowid value is not
85717 ** modified by an update.
85719 ** The code generated by this routine store new index entries into
85720 ** registers identified by aRegIdx[]. No index entry is created for
85721 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
85722 ** the same as the order of indices on the linked list of indices
85723 ** attached to the table.
85725 ** This routine also generates code to check constraints. NOT NULL,
85726 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
85727 ** then the appropriate action is performed. There are five possible
85728 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
85730 ** Constraint type Action What Happens
85731 ** --------------- ---------- ----------------------------------------
85732 ** any ROLLBACK The current transaction is rolled back and
85733 ** sqlite3_exec() returns immediately with a
85734 ** return code of SQLITE_CONSTRAINT.
85736 ** any ABORT Back out changes from the current command
85737 ** only (do not do a complete rollback) then
85738 ** cause sqlite3_exec() to return immediately
85739 ** with SQLITE_CONSTRAINT.
85741 ** any FAIL Sqlite_exec() returns immediately with a
85742 ** return code of SQLITE_CONSTRAINT. The
85743 ** transaction is not rolled back and any
85744 ** prior changes are retained.
85746 ** any IGNORE The record number and data is popped from
85747 ** the stack and there is an immediate jump
85748 ** to label ignoreDest.
85750 ** NOT NULL REPLACE The NULL value is replace by the default
85751 ** value for that column. If the default value
85752 ** is NULL, the action is the same as ABORT.
85754 ** UNIQUE REPLACE The other row that conflicts with the row
85755 ** being inserted is removed.
85757 ** CHECK REPLACE Illegal. The results in an exception.
85759 ** Which action to take is determined by the overrideError parameter.
85760 ** Or if overrideError==OE_Default, then the pParse->onError parameter
85761 ** is used. Or if pParse->onError==OE_Default then the onError value
85762 ** for the constraint is used.
85764 ** The calling routine must open a read/write cursor for pTab with
85765 ** cursor number "baseCur". All indices of pTab must also have open
85766 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
85767 ** Except, if there is no possibility of a REPLACE action then
85768 ** cursors do not need to be open for indices where aRegIdx[i]==0.
85770 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
85771 Parse *pParse, /* The parser context */
85772 Table *pTab, /* the table into which we are inserting */
85773 int baseCur, /* Index of a read/write cursor pointing at pTab */
85774 int regRowid, /* Index of the range of input registers */
85775 int *aRegIdx, /* Register used by each index. 0 for unused indices */
85776 int rowidChng, /* True if the rowid might collide with existing entry */
85777 int isUpdate, /* True for UPDATE, False for INSERT */
85778 int overrideError, /* Override onError to this if not OE_Default */
85779 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
85780 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
85782 int i; /* loop counter */
85783 Vdbe *v; /* VDBE under constrution */
85784 int nCol; /* Number of columns */
85785 int onError; /* Conflict resolution strategy */
85786 int j1; /* Addresss of jump instruction */
85787 int j2 = 0, j3; /* Addresses of jump instructions */
85788 int regData; /* Register containing first data column */
85789 int iCur; /* Table cursor number */
85790 Index *pIdx; /* Pointer to one of the indices */
85791 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
85792 int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
85794 v = sqlite3GetVdbe(pParse);
85795 assert( v!=0 );
85796 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
85797 nCol = pTab->nCol;
85798 regData = regRowid + 1;
85800 /* Test all NOT NULL constraints.
85802 for(i=0; i<nCol; i++){
85803 if( i==pTab->iPKey ){
85804 continue;
85806 onError = pTab->aCol[i].notNull;
85807 if( onError==OE_None ) continue;
85808 if( overrideError!=OE_Default ){
85809 onError = overrideError;
85810 }else if( onError==OE_Default ){
85811 onError = OE_Abort;
85813 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
85814 onError = OE_Abort;
85816 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
85817 || onError==OE_Ignore || onError==OE_Replace );
85818 switch( onError ){
85819 case OE_Abort:
85820 sqlite3MayAbort(pParse);
85821 case OE_Rollback:
85822 case OE_Fail: {
85823 char *zMsg;
85824 sqlite3VdbeAddOp3(v, OP_HaltIfNull,
85825 SQLITE_CONSTRAINT, onError, regData+i);
85826 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
85827 pTab->zName, pTab->aCol[i].zName);
85828 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
85829 break;
85831 case OE_Ignore: {
85832 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
85833 break;
85835 default: {
85836 assert( onError==OE_Replace );
85837 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
85838 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
85839 sqlite3VdbeJumpHere(v, j1);
85840 break;
85845 /* Test all CHECK constraints
85847 #ifndef SQLITE_OMIT_CHECK
85848 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
85849 int allOk = sqlite3VdbeMakeLabel(v);
85850 pParse->ckBase = regData;
85851 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
85852 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
85853 if( onError==OE_Ignore ){
85854 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85855 }else{
85856 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
85857 sqlite3HaltConstraint(pParse, onError, 0, 0);
85859 sqlite3VdbeResolveLabel(v, allOk);
85861 #endif /* !defined(SQLITE_OMIT_CHECK) */
85863 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
85864 ** of the new record does not previously exist. Except, if this
85865 ** is an UPDATE and the primary key is not changing, that is OK.
85867 if( rowidChng ){
85868 onError = pTab->keyConf;
85869 if( overrideError!=OE_Default ){
85870 onError = overrideError;
85871 }else if( onError==OE_Default ){
85872 onError = OE_Abort;
85875 if( isUpdate ){
85876 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
85878 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
85879 switch( onError ){
85880 default: {
85881 onError = OE_Abort;
85882 /* Fall thru into the next case */
85884 case OE_Rollback:
85885 case OE_Abort:
85886 case OE_Fail: {
85887 sqlite3HaltConstraint(
85888 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
85889 break;
85891 case OE_Replace: {
85892 /* If there are DELETE triggers on this table and the
85893 ** recursive-triggers flag is set, call GenerateRowDelete() to
85894 ** remove the conflicting row from the the table. This will fire
85895 ** the triggers and remove both the table and index b-tree entries.
85897 ** Otherwise, if there are no triggers or the recursive-triggers
85898 ** flag is not set, but the table has one or more indexes, call
85899 ** GenerateRowIndexDelete(). This removes the index b-tree entries
85900 ** only. The table b-tree entry will be replaced by the new entry
85901 ** when it is inserted.
85903 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
85904 ** also invoke MultiWrite() to indicate that this VDBE may require
85905 ** statement rollback (if the statement is aborted after the delete
85906 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
85907 ** but being more selective here allows statements like:
85909 ** REPLACE INTO t(rowid) VALUES($newrowid)
85911 ** to run without a statement journal if there are no indexes on the
85912 ** table.
85914 Trigger *pTrigger = 0;
85915 if( pParse->db->flags&SQLITE_RecTriggers ){
85916 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85918 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
85919 sqlite3MultiWrite(pParse);
85920 sqlite3GenerateRowDelete(
85921 pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
85923 }else if( pTab->pIndex ){
85924 sqlite3MultiWrite(pParse);
85925 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
85927 seenReplace = 1;
85928 break;
85930 case OE_Ignore: {
85931 assert( seenReplace==0 );
85932 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85933 break;
85936 sqlite3VdbeJumpHere(v, j3);
85937 if( isUpdate ){
85938 sqlite3VdbeJumpHere(v, j2);
85942 /* Test all UNIQUE constraints by creating entries for each UNIQUE
85943 ** index and making sure that duplicate entries do not already exist.
85944 ** Add the new records to the indices as we go.
85946 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
85947 int regIdx;
85948 int regR;
85950 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
85952 /* Create a key for accessing the index entry */
85953 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
85954 for(i=0; i<pIdx->nColumn; i++){
85955 int idx = pIdx->aiColumn[i];
85956 if( idx==pTab->iPKey ){
85957 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
85958 }else{
85959 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
85962 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
85963 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
85964 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
85965 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
85967 /* Find out what action to take in case there is an indexing conflict */
85968 onError = pIdx->onError;
85969 if( onError==OE_None ){
85970 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
85971 continue; /* pIdx is not a UNIQUE index */
85973 if( overrideError!=OE_Default ){
85974 onError = overrideError;
85975 }else if( onError==OE_Default ){
85976 onError = OE_Abort;
85978 if( seenReplace ){
85979 if( onError==OE_Ignore ) onError = OE_Replace;
85980 else if( onError==OE_Fail ) onError = OE_Abort;
85983 /* Check to see if the new index entry will be unique */
85984 regR = sqlite3GetTempReg(pParse);
85985 sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
85986 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
85987 regR, SQLITE_INT_TO_PTR(regIdx),
85988 P4_INT32);
85989 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
85991 /* Generate code that executes if the new index entry is not unique */
85992 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
85993 || onError==OE_Ignore || onError==OE_Replace );
85994 switch( onError ){
85995 case OE_Rollback:
85996 case OE_Abort:
85997 case OE_Fail: {
85998 int j;
85999 StrAccum errMsg;
86000 const char *zSep;
86001 char *zErr;
86003 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
86004 errMsg.db = pParse->db;
86005 zSep = pIdx->nColumn>1 ? "columns " : "column ";
86006 for(j=0; j<pIdx->nColumn; j++){
86007 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
86008 sqlite3StrAccumAppend(&errMsg, zSep, -1);
86009 zSep = ", ";
86010 sqlite3StrAccumAppend(&errMsg, zCol, -1);
86012 sqlite3StrAccumAppend(&errMsg,
86013 pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
86014 zErr = sqlite3StrAccumFinish(&errMsg);
86015 sqlite3HaltConstraint(pParse, onError, zErr, 0);
86016 sqlite3DbFree(errMsg.db, zErr);
86017 break;
86019 case OE_Ignore: {
86020 assert( seenReplace==0 );
86021 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
86022 break;
86024 default: {
86025 Trigger *pTrigger = 0;
86026 assert( onError==OE_Replace );
86027 sqlite3MultiWrite(pParse);
86028 if( pParse->db->flags&SQLITE_RecTriggers ){
86029 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
86031 sqlite3GenerateRowDelete(
86032 pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
86034 seenReplace = 1;
86035 break;
86038 sqlite3VdbeJumpHere(v, j3);
86039 sqlite3ReleaseTempReg(pParse, regR);
86042 if( pbMayReplace ){
86043 *pbMayReplace = seenReplace;
86048 ** This routine generates code to finish the INSERT or UPDATE operation
86049 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
86050 ** A consecutive range of registers starting at regRowid contains the
86051 ** rowid and the content to be inserted.
86053 ** The arguments to this routine should be the same as the first six
86054 ** arguments to sqlite3GenerateConstraintChecks.
86056 SQLITE_PRIVATE void sqlite3CompleteInsertion(
86057 Parse *pParse, /* The parser context */
86058 Table *pTab, /* the table into which we are inserting */
86059 int baseCur, /* Index of a read/write cursor pointing at pTab */
86060 int regRowid, /* Range of content */
86061 int *aRegIdx, /* Register used by each index. 0 for unused indices */
86062 int isUpdate, /* True for UPDATE, False for INSERT */
86063 int appendBias, /* True if this is likely to be an append */
86064 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
86066 int i;
86067 Vdbe *v;
86068 int nIdx;
86069 Index *pIdx;
86070 u8 pik_flags;
86071 int regData;
86072 int regRec;
86074 v = sqlite3GetVdbe(pParse);
86075 assert( v!=0 );
86076 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
86077 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
86078 for(i=nIdx-1; i>=0; i--){
86079 if( aRegIdx[i]==0 ) continue;
86080 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
86081 if( useSeekResult ){
86082 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
86085 regData = regRowid + 1;
86086 regRec = sqlite3GetTempReg(pParse);
86087 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
86088 sqlite3TableAffinityStr(v, pTab);
86089 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
86090 if( pParse->nested ){
86091 pik_flags = 0;
86092 }else{
86093 pik_flags = OPFLAG_NCHANGE;
86094 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
86096 if( appendBias ){
86097 pik_flags |= OPFLAG_APPEND;
86099 if( useSeekResult ){
86100 pik_flags |= OPFLAG_USESEEKRESULT;
86102 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
86103 if( !pParse->nested ){
86104 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
86106 sqlite3VdbeChangeP5(v, pik_flags);
86110 ** Generate code that will open cursors for a table and for all
86111 ** indices of that table. The "baseCur" parameter is the cursor number used
86112 ** for the table. Indices are opened on subsequent cursors.
86114 ** Return the number of indices on the table.
86116 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
86117 Parse *pParse, /* Parsing context */
86118 Table *pTab, /* Table to be opened */
86119 int baseCur, /* Cursor number assigned to the table */
86120 int op /* OP_OpenRead or OP_OpenWrite */
86122 int i;
86123 int iDb;
86124 Index *pIdx;
86125 Vdbe *v;
86127 if( IsVirtual(pTab) ) return 0;
86128 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
86129 v = sqlite3GetVdbe(pParse);
86130 assert( v!=0 );
86131 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
86132 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
86133 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
86134 assert( pIdx->pSchema==pTab->pSchema );
86135 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
86136 (char*)pKey, P4_KEYINFO_HANDOFF);
86137 VdbeComment((v, "%s", pIdx->zName));
86139 if( pParse->nTab<baseCur+i ){
86140 pParse->nTab = baseCur+i;
86142 return i-1;
86146 #ifdef SQLITE_TEST
86148 ** The following global variable is incremented whenever the
86149 ** transfer optimization is used. This is used for testing
86150 ** purposes only - to make sure the transfer optimization really
86151 ** is happening when it is suppose to.
86153 SQLITE_API int sqlite3_xferopt_count;
86154 #endif /* SQLITE_TEST */
86157 #ifndef SQLITE_OMIT_XFER_OPT
86159 ** Check to collation names to see if they are compatible.
86161 static int xferCompatibleCollation(const char *z1, const char *z2){
86162 if( z1==0 ){
86163 return z2==0;
86165 if( z2==0 ){
86166 return 0;
86168 return sqlite3StrICmp(z1, z2)==0;
86173 ** Check to see if index pSrc is compatible as a source of data
86174 ** for index pDest in an insert transfer optimization. The rules
86175 ** for a compatible index:
86177 ** * The index is over the same set of columns
86178 ** * The same DESC and ASC markings occurs on all columns
86179 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
86180 ** * The same collating sequence on each column
86182 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
86183 int i;
86184 assert( pDest && pSrc );
86185 assert( pDest->pTable!=pSrc->pTable );
86186 if( pDest->nColumn!=pSrc->nColumn ){
86187 return 0; /* Different number of columns */
86189 if( pDest->onError!=pSrc->onError ){
86190 return 0; /* Different conflict resolution strategies */
86192 for(i=0; i<pSrc->nColumn; i++){
86193 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
86194 return 0; /* Different columns indexed */
86196 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
86197 return 0; /* Different sort orders */
86199 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
86200 return 0; /* Different collating sequences */
86204 /* If no test above fails then the indices must be compatible */
86205 return 1;
86209 ** Attempt the transfer optimization on INSERTs of the form
86211 ** INSERT INTO tab1 SELECT * FROM tab2;
86213 ** This optimization is only attempted if
86215 ** (1) tab1 and tab2 have identical schemas including all the
86216 ** same indices and constraints
86218 ** (2) tab1 and tab2 are different tables
86220 ** (3) There must be no triggers on tab1
86222 ** (4) The result set of the SELECT statement is "*"
86224 ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
86225 ** or LIMIT clause.
86227 ** (6) The SELECT statement is a simple (not a compound) select that
86228 ** contains only tab2 in its FROM clause
86230 ** This method for implementing the INSERT transfers raw records from
86231 ** tab2 over to tab1. The columns are not decoded. Raw records from
86232 ** the indices of tab2 are transfered to tab1 as well. In so doing,
86233 ** the resulting tab1 has much less fragmentation.
86235 ** This routine returns TRUE if the optimization is attempted. If any
86236 ** of the conditions above fail so that the optimization should not
86237 ** be attempted, then this routine returns FALSE.
86239 static int xferOptimization(
86240 Parse *pParse, /* Parser context */
86241 Table *pDest, /* The table we are inserting into */
86242 Select *pSelect, /* A SELECT statement to use as the data source */
86243 int onError, /* How to handle constraint errors */
86244 int iDbDest /* The database of pDest */
86246 ExprList *pEList; /* The result set of the SELECT */
86247 Table *pSrc; /* The table in the FROM clause of SELECT */
86248 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
86249 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
86250 int i; /* Loop counter */
86251 int iDbSrc; /* The database of pSrc */
86252 int iSrc, iDest; /* Cursors from source and destination */
86253 int addr1, addr2; /* Loop addresses */
86254 int emptyDestTest; /* Address of test for empty pDest */
86255 int emptySrcTest; /* Address of test for empty pSrc */
86256 Vdbe *v; /* The VDBE we are building */
86257 KeyInfo *pKey; /* Key information for an index */
86258 int regAutoinc; /* Memory register used by AUTOINC */
86259 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
86260 int regData, regRowid; /* Registers holding data and rowid */
86262 if( pSelect==0 ){
86263 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
86265 if( sqlite3TriggerList(pParse, pDest) ){
86266 return 0; /* tab1 must not have triggers */
86268 #ifndef SQLITE_OMIT_VIRTUALTABLE
86269 if( pDest->tabFlags & TF_Virtual ){
86270 return 0; /* tab1 must not be a virtual table */
86272 #endif
86273 if( onError==OE_Default ){
86274 onError = OE_Abort;
86276 if( onError!=OE_Abort && onError!=OE_Rollback ){
86277 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
86279 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
86280 if( pSelect->pSrc->nSrc!=1 ){
86281 return 0; /* FROM clause must have exactly one term */
86283 if( pSelect->pSrc->a[0].pSelect ){
86284 return 0; /* FROM clause cannot contain a subquery */
86286 if( pSelect->pWhere ){
86287 return 0; /* SELECT may not have a WHERE clause */
86289 if( pSelect->pOrderBy ){
86290 return 0; /* SELECT may not have an ORDER BY clause */
86292 /* Do not need to test for a HAVING clause. If HAVING is present but
86293 ** there is no ORDER BY, we will get an error. */
86294 if( pSelect->pGroupBy ){
86295 return 0; /* SELECT may not have a GROUP BY clause */
86297 if( pSelect->pLimit ){
86298 return 0; /* SELECT may not have a LIMIT clause */
86300 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
86301 if( pSelect->pPrior ){
86302 return 0; /* SELECT may not be a compound query */
86304 if( pSelect->selFlags & SF_Distinct ){
86305 return 0; /* SELECT may not be DISTINCT */
86307 pEList = pSelect->pEList;
86308 assert( pEList!=0 );
86309 if( pEList->nExpr!=1 ){
86310 return 0; /* The result set must have exactly one column */
86312 assert( pEList->a[0].pExpr );
86313 if( pEList->a[0].pExpr->op!=TK_ALL ){
86314 return 0; /* The result set must be the special operator "*" */
86317 /* At this point we have established that the statement is of the
86318 ** correct syntactic form to participate in this optimization. Now
86319 ** we have to check the semantics.
86321 pItem = pSelect->pSrc->a;
86322 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
86323 if( pSrc==0 ){
86324 return 0; /* FROM clause does not contain a real table */
86326 if( pSrc==pDest ){
86327 return 0; /* tab1 and tab2 may not be the same table */
86329 #ifndef SQLITE_OMIT_VIRTUALTABLE
86330 if( pSrc->tabFlags & TF_Virtual ){
86331 return 0; /* tab2 must not be a virtual table */
86333 #endif
86334 if( pSrc->pSelect ){
86335 return 0; /* tab2 may not be a view */
86337 if( pDest->nCol!=pSrc->nCol ){
86338 return 0; /* Number of columns must be the same in tab1 and tab2 */
86340 if( pDest->iPKey!=pSrc->iPKey ){
86341 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
86343 for(i=0; i<pDest->nCol; i++){
86344 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
86345 return 0; /* Affinity must be the same on all columns */
86347 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
86348 return 0; /* Collating sequence must be the same on all columns */
86350 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
86351 return 0; /* tab2 must be NOT NULL if tab1 is */
86354 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86355 if( pDestIdx->onError!=OE_None ){
86356 destHasUniqueIdx = 1;
86358 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
86359 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86361 if( pSrcIdx==0 ){
86362 return 0; /* pDestIdx has no corresponding index in pSrc */
86365 #ifndef SQLITE_OMIT_CHECK
86366 if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
86367 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
86369 #endif
86371 /* If we get this far, it means either:
86373 ** * We can always do the transfer if the table contains an
86374 ** an integer primary key
86376 ** * We can conditionally do the transfer if the destination
86377 ** table is empty.
86379 #ifdef SQLITE_TEST
86380 sqlite3_xferopt_count++;
86381 #endif
86382 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
86383 v = sqlite3GetVdbe(pParse);
86384 sqlite3CodeVerifySchema(pParse, iDbSrc);
86385 iSrc = pParse->nTab++;
86386 iDest = pParse->nTab++;
86387 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
86388 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
86389 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
86390 /* If tables do not have an INTEGER PRIMARY KEY and there
86391 ** are indices to be copied and the destination is not empty,
86392 ** we have to disallow the transfer optimization because the
86393 ** the rowids might change which will mess up indexing.
86395 ** Or if the destination has a UNIQUE index and is not empty,
86396 ** we also disallow the transfer optimization because we cannot
86397 ** insure that all entries in the union of DEST and SRC will be
86398 ** unique.
86400 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
86401 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
86402 sqlite3VdbeJumpHere(v, addr1);
86403 }else{
86404 emptyDestTest = 0;
86406 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
86407 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86408 regData = sqlite3GetTempReg(pParse);
86409 regRowid = sqlite3GetTempReg(pParse);
86410 if( pDest->iPKey>=0 ){
86411 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86412 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
86413 sqlite3HaltConstraint(
86414 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
86415 sqlite3VdbeJumpHere(v, addr2);
86416 autoIncStep(pParse, regAutoinc, regRowid);
86417 }else if( pDest->pIndex==0 ){
86418 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
86419 }else{
86420 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86421 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
86423 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
86424 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
86425 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
86426 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
86427 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
86428 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86429 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
86430 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86432 assert( pSrcIdx );
86433 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86434 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86435 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
86436 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
86437 (char*)pKey, P4_KEYINFO_HANDOFF);
86438 VdbeComment((v, "%s", pSrcIdx->zName));
86439 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
86440 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
86441 (char*)pKey, P4_KEYINFO_HANDOFF);
86442 VdbeComment((v, "%s", pDestIdx->zName));
86443 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86444 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
86445 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
86446 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
86447 sqlite3VdbeJumpHere(v, addr1);
86449 sqlite3VdbeJumpHere(v, emptySrcTest);
86450 sqlite3ReleaseTempReg(pParse, regRowid);
86451 sqlite3ReleaseTempReg(pParse, regData);
86452 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86453 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86454 if( emptyDestTest ){
86455 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
86456 sqlite3VdbeJumpHere(v, emptyDestTest);
86457 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86458 return 0;
86459 }else{
86460 return 1;
86463 #endif /* SQLITE_OMIT_XFER_OPT */
86465 /************** End of insert.c **********************************************/
86466 /************** Begin file legacy.c ******************************************/
86468 ** 2001 September 15
86470 ** The author disclaims copyright to this source code. In place of
86471 ** a legal notice, here is a blessing:
86473 ** May you do good and not evil.
86474 ** May you find forgiveness for yourself and forgive others.
86475 ** May you share freely, never taking more than you give.
86477 *************************************************************************
86478 ** Main file for the SQLite library. The routines in this file
86479 ** implement the programmer interface to the library. Routines in
86480 ** other files are for internal use by SQLite and should not be
86481 ** accessed by users of the library.
86486 ** Execute SQL code. Return one of the SQLITE_ success/failure
86487 ** codes. Also write an error message into memory obtained from
86488 ** malloc() and make *pzErrMsg point to that message.
86490 ** If the SQL is a query, then for each row in the query result
86491 ** the xCallback() function is called. pArg becomes the first
86492 ** argument to xCallback(). If xCallback=NULL then no callback
86493 ** is invoked, even for queries.
86495 SQLITE_API int sqlite3_exec(
86496 sqlite3 *db, /* The database on which the SQL executes */
86497 const char *zSql, /* The SQL to be executed */
86498 sqlite3_callback xCallback, /* Invoke this callback routine */
86499 void *pArg, /* First argument to xCallback() */
86500 char **pzErrMsg /* Write error messages here */
86502 int rc = SQLITE_OK; /* Return code */
86503 const char *zLeftover; /* Tail of unprocessed SQL */
86504 sqlite3_stmt *pStmt = 0; /* The current SQL statement */
86505 char **azCols = 0; /* Names of result columns */
86506 int nRetry = 0; /* Number of retry attempts */
86507 int callbackIsInit; /* True if callback data is initialized */
86509 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
86510 if( zSql==0 ) zSql = "";
86512 sqlite3_mutex_enter(db->mutex);
86513 sqlite3Error(db, SQLITE_OK, 0);
86514 while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
86515 int nCol;
86516 char **azVals = 0;
86518 pStmt = 0;
86519 rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
86520 assert( rc==SQLITE_OK || pStmt==0 );
86521 if( rc!=SQLITE_OK ){
86522 continue;
86524 if( !pStmt ){
86525 /* this happens for a comment or white-space */
86526 zSql = zLeftover;
86527 continue;
86530 callbackIsInit = 0;
86531 nCol = sqlite3_column_count(pStmt);
86533 while( 1 ){
86534 int i;
86535 rc = sqlite3_step(pStmt);
86537 /* Invoke the callback function if required */
86538 if( xCallback && (SQLITE_ROW==rc ||
86539 (SQLITE_DONE==rc && !callbackIsInit
86540 && db->flags&SQLITE_NullCallback)) ){
86541 if( !callbackIsInit ){
86542 azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
86543 if( azCols==0 ){
86544 goto exec_out;
86546 for(i=0; i<nCol; i++){
86547 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
86548 /* sqlite3VdbeSetColName() installs column names as UTF8
86549 ** strings so there is no way for sqlite3_column_name() to fail. */
86550 assert( azCols[i]!=0 );
86552 callbackIsInit = 1;
86554 if( rc==SQLITE_ROW ){
86555 azVals = &azCols[nCol];
86556 for(i=0; i<nCol; i++){
86557 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
86558 if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
86559 db->mallocFailed = 1;
86560 goto exec_out;
86564 if( xCallback(pArg, nCol, azVals, azCols) ){
86565 rc = SQLITE_ABORT;
86566 sqlite3VdbeFinalize((Vdbe *)pStmt);
86567 pStmt = 0;
86568 sqlite3Error(db, SQLITE_ABORT, 0);
86569 goto exec_out;
86573 if( rc!=SQLITE_ROW ){
86574 rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
86575 pStmt = 0;
86576 if( rc!=SQLITE_SCHEMA ){
86577 nRetry = 0;
86578 zSql = zLeftover;
86579 while( sqlite3Isspace(zSql[0]) ) zSql++;
86581 break;
86585 sqlite3DbFree(db, azCols);
86586 azCols = 0;
86589 exec_out:
86590 if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
86591 sqlite3DbFree(db, azCols);
86593 rc = sqlite3ApiExit(db, rc);
86594 if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
86595 int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
86596 *pzErrMsg = sqlite3Malloc(nErrMsg);
86597 if( *pzErrMsg ){
86598 memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
86599 }else{
86600 rc = SQLITE_NOMEM;
86601 sqlite3Error(db, SQLITE_NOMEM, 0);
86603 }else if( pzErrMsg ){
86604 *pzErrMsg = 0;
86607 assert( (rc&db->errMask)==rc );
86608 sqlite3_mutex_leave(db->mutex);
86609 return rc;
86612 /************** End of legacy.c **********************************************/
86613 /************** Begin file loadext.c *****************************************/
86615 ** 2006 June 7
86617 ** The author disclaims copyright to this source code. In place of
86618 ** a legal notice, here is a blessing:
86620 ** May you do good and not evil.
86621 ** May you find forgiveness for yourself and forgive others.
86622 ** May you share freely, never taking more than you give.
86624 *************************************************************************
86625 ** This file contains code used to dynamically load extensions into
86626 ** the SQLite library.
86629 #ifndef SQLITE_CORE
86630 #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
86631 #endif
86632 /************** Include sqlite3ext.h in the middle of loadext.c **************/
86633 /************** Begin file sqlite3ext.h **************************************/
86635 ** 2006 June 7
86637 ** The author disclaims copyright to this source code. In place of
86638 ** a legal notice, here is a blessing:
86640 ** May you do good and not evil.
86641 ** May you find forgiveness for yourself and forgive others.
86642 ** May you share freely, never taking more than you give.
86644 *************************************************************************
86645 ** This header file defines the SQLite interface for use by
86646 ** shared libraries that want to be imported as extensions into
86647 ** an SQLite instance. Shared libraries that intend to be loaded
86648 ** as extensions by SQLite should #include this file instead of
86649 ** sqlite3.h.
86651 #ifndef _SQLITE3EXT_H_
86652 #define _SQLITE3EXT_H_
86654 typedef struct sqlite3_api_routines sqlite3_api_routines;
86657 ** The following structure holds pointers to all of the SQLite API
86658 ** routines.
86660 ** WARNING: In order to maintain backwards compatibility, add new
86661 ** interfaces to the end of this structure only. If you insert new
86662 ** interfaces in the middle of this structure, then older different
86663 ** versions of SQLite will not be able to load each others' shared
86664 ** libraries!
86666 struct sqlite3_api_routines {
86667 void * (*aggregate_context)(sqlite3_context*,int nBytes);
86668 int (*aggregate_count)(sqlite3_context*);
86669 int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
86670 int (*bind_double)(sqlite3_stmt*,int,double);
86671 int (*bind_int)(sqlite3_stmt*,int,int);
86672 int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
86673 int (*bind_null)(sqlite3_stmt*,int);
86674 int (*bind_parameter_count)(sqlite3_stmt*);
86675 int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
86676 const char * (*bind_parameter_name)(sqlite3_stmt*,int);
86677 int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
86678 int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
86679 int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
86680 int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
86681 int (*busy_timeout)(sqlite3*,int ms);
86682 int (*changes)(sqlite3*);
86683 int (*close)(sqlite3*);
86684 int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
86685 int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
86686 const void * (*column_blob)(sqlite3_stmt*,int iCol);
86687 int (*column_bytes)(sqlite3_stmt*,int iCol);
86688 int (*column_bytes16)(sqlite3_stmt*,int iCol);
86689 int (*column_count)(sqlite3_stmt*pStmt);
86690 const char * (*column_database_name)(sqlite3_stmt*,int);
86691 const void * (*column_database_name16)(sqlite3_stmt*,int);
86692 const char * (*column_decltype)(sqlite3_stmt*,int i);
86693 const void * (*column_decltype16)(sqlite3_stmt*,int);
86694 double (*column_double)(sqlite3_stmt*,int iCol);
86695 int (*column_int)(sqlite3_stmt*,int iCol);
86696 sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
86697 const char * (*column_name)(sqlite3_stmt*,int);
86698 const void * (*column_name16)(sqlite3_stmt*,int);
86699 const char * (*column_origin_name)(sqlite3_stmt*,int);
86700 const void * (*column_origin_name16)(sqlite3_stmt*,int);
86701 const char * (*column_table_name)(sqlite3_stmt*,int);
86702 const void * (*column_table_name16)(sqlite3_stmt*,int);
86703 const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
86704 const void * (*column_text16)(sqlite3_stmt*,int iCol);
86705 int (*column_type)(sqlite3_stmt*,int iCol);
86706 sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
86707 void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
86708 int (*complete)(const char*sql);
86709 int (*complete16)(const void*sql);
86710 int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
86711 int (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
86712 int (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
86713 int (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
86714 int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
86715 int (*data_count)(sqlite3_stmt*pStmt);
86716 sqlite3 * (*db_handle)(sqlite3_stmt*);
86717 int (*declare_vtab)(sqlite3*,const char*);
86718 int (*enable_shared_cache)(int);
86719 int (*errcode)(sqlite3*db);
86720 const char * (*errmsg)(sqlite3*);
86721 const void * (*errmsg16)(sqlite3*);
86722 int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
86723 int (*expired)(sqlite3_stmt*);
86724 int (*finalize)(sqlite3_stmt*pStmt);
86725 void (*free)(void*);
86726 void (*free_table)(char**result);
86727 int (*get_autocommit)(sqlite3*);
86728 void * (*get_auxdata)(sqlite3_context*,int);
86729 int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
86730 int (*global_recover)(void);
86731 void (*interruptx)(sqlite3*);
86732 sqlite_int64 (*last_insert_rowid)(sqlite3*);
86733 const char * (*libversion)(void);
86734 int (*libversion_number)(void);
86735 void *(*malloc)(int);
86736 char * (*mprintf)(const char*,...);
86737 int (*open)(const char*,sqlite3**);
86738 int (*open16)(const void*,sqlite3**);
86739 int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
86740 int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
86741 void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
86742 void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
86743 void *(*realloc)(void*,int);
86744 int (*reset)(sqlite3_stmt*pStmt);
86745 void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
86746 void (*result_double)(sqlite3_context*,double);
86747 void (*result_error)(sqlite3_context*,const char*,int);
86748 void (*result_error16)(sqlite3_context*,const void*,int);
86749 void (*result_int)(sqlite3_context*,int);
86750 void (*result_int64)(sqlite3_context*,sqlite_int64);
86751 void (*result_null)(sqlite3_context*);
86752 void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
86753 void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
86754 void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
86755 void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
86756 void (*result_value)(sqlite3_context*,sqlite3_value*);
86757 void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
86758 int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
86759 void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
86760 char * (*snprintf)(int,char*,const char*,...);
86761 int (*step)(sqlite3_stmt*);
86762 int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
86763 void (*thread_cleanup)(void);
86764 int (*total_changes)(sqlite3*);
86765 void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
86766 int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
86767 void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
86768 void * (*user_data)(sqlite3_context*);
86769 const void * (*value_blob)(sqlite3_value*);
86770 int (*value_bytes)(sqlite3_value*);
86771 int (*value_bytes16)(sqlite3_value*);
86772 double (*value_double)(sqlite3_value*);
86773 int (*value_int)(sqlite3_value*);
86774 sqlite_int64 (*value_int64)(sqlite3_value*);
86775 int (*value_numeric_type)(sqlite3_value*);
86776 const unsigned char * (*value_text)(sqlite3_value*);
86777 const void * (*value_text16)(sqlite3_value*);
86778 const void * (*value_text16be)(sqlite3_value*);
86779 const void * (*value_text16le)(sqlite3_value*);
86780 int (*value_type)(sqlite3_value*);
86781 char *(*vmprintf)(const char*,va_list);
86782 /* Added ??? */
86783 int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
86784 /* Added by 3.3.13 */
86785 int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
86786 int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
86787 int (*clear_bindings)(sqlite3_stmt*);
86788 /* Added by 3.4.1 */
86789 int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
86790 /* Added by 3.5.0 */
86791 int (*bind_zeroblob)(sqlite3_stmt*,int,int);
86792 int (*blob_bytes)(sqlite3_blob*);
86793 int (*blob_close)(sqlite3_blob*);
86794 int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
86795 int (*blob_read)(sqlite3_blob*,void*,int,int);
86796 int (*blob_write)(sqlite3_blob*,const void*,int,int);
86797 int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
86798 int (*file_control)(sqlite3*,const char*,int,void*);
86799 sqlite3_int64 (*memory_highwater)(int);
86800 sqlite3_int64 (*memory_used)(void);
86801 sqlite3_mutex *(*mutex_alloc)(int);
86802 void (*mutex_enter)(sqlite3_mutex*);
86803 void (*mutex_free)(sqlite3_mutex*);
86804 void (*mutex_leave)(sqlite3_mutex*);
86805 int (*mutex_try)(sqlite3_mutex*);
86806 int (*open_v2)(const char*,sqlite3**,int,const char*);
86807 int (*release_memory)(int);
86808 void (*result_error_nomem)(sqlite3_context*);
86809 void (*result_error_toobig)(sqlite3_context*);
86810 int (*sleep)(int);
86811 void (*soft_heap_limit)(int);
86812 sqlite3_vfs *(*vfs_find)(const char*);
86813 int (*vfs_register)(sqlite3_vfs*,int);
86814 int (*vfs_unregister)(sqlite3_vfs*);
86815 int (*xthreadsafe)(void);
86816 void (*result_zeroblob)(sqlite3_context*,int);
86817 void (*result_error_code)(sqlite3_context*,int);
86818 int (*test_control)(int, ...);
86819 void (*randomness)(int,void*);
86820 sqlite3 *(*context_db_handle)(sqlite3_context*);
86821 int (*extended_result_codes)(sqlite3*,int);
86822 int (*limit)(sqlite3*,int,int);
86823 sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
86824 const char *(*sql)(sqlite3_stmt*);
86825 int (*status)(int,int*,int*,int);
86826 int (*backup_finish)(sqlite3_backup*);
86827 sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
86828 int (*backup_pagecount)(sqlite3_backup*);
86829 int (*backup_remaining)(sqlite3_backup*);
86830 int (*backup_step)(sqlite3_backup*,int);
86831 const char *(*compileoption_get)(int);
86832 int (*compileoption_used)(const char*);
86833 int (*create_function_v2)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*),void(*xDestroy)(void*));
86834 int (*db_config)(sqlite3*,int,...);
86835 sqlite3_mutex *(*db_mutex)(sqlite3*);
86836 int (*db_status)(sqlite3*,int,int*,int*,int);
86837 int (*extended_errcode)(sqlite3*);
86838 void (*log)(int,const char*,...);
86839 sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
86840 const char *(*sourceid)(void);
86841 int (*stmt_status)(sqlite3_stmt*,int,int);
86842 int (*strnicmp)(const char*,const char*,int);
86843 int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
86844 int (*wal_autocheckpoint)(sqlite3*,int);
86845 int (*wal_checkpoint)(sqlite3*,const char*);
86846 void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
86850 ** The following macros redefine the API routines so that they are
86851 ** redirected throught the global sqlite3_api structure.
86853 ** This header file is also used by the loadext.c source file
86854 ** (part of the main SQLite library - not an extension) so that
86855 ** it can get access to the sqlite3_api_routines structure
86856 ** definition. But the main library does not want to redefine
86857 ** the API. So the redefinition macros are only valid if the
86858 ** SQLITE_CORE macros is undefined.
86860 #ifndef SQLITE_CORE
86861 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
86862 #ifndef SQLITE_OMIT_DEPRECATED
86863 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
86864 #endif
86865 #define sqlite3_bind_blob sqlite3_api->bind_blob
86866 #define sqlite3_bind_double sqlite3_api->bind_double
86867 #define sqlite3_bind_int sqlite3_api->bind_int
86868 #define sqlite3_bind_int64 sqlite3_api->bind_int64
86869 #define sqlite3_bind_null sqlite3_api->bind_null
86870 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
86871 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
86872 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
86873 #define sqlite3_bind_text sqlite3_api->bind_text
86874 #define sqlite3_bind_text16 sqlite3_api->bind_text16
86875 #define sqlite3_bind_value sqlite3_api->bind_value
86876 #define sqlite3_busy_handler sqlite3_api->busy_handler
86877 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
86878 #define sqlite3_changes sqlite3_api->changes
86879 #define sqlite3_close sqlite3_api->close
86880 #define sqlite3_collation_needed sqlite3_api->collation_needed
86881 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
86882 #define sqlite3_column_blob sqlite3_api->column_blob
86883 #define sqlite3_column_bytes sqlite3_api->column_bytes
86884 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
86885 #define sqlite3_column_count sqlite3_api->column_count
86886 #define sqlite3_column_database_name sqlite3_api->column_database_name
86887 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
86888 #define sqlite3_column_decltype sqlite3_api->column_decltype
86889 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
86890 #define sqlite3_column_double sqlite3_api->column_double
86891 #define sqlite3_column_int sqlite3_api->column_int
86892 #define sqlite3_column_int64 sqlite3_api->column_int64
86893 #define sqlite3_column_name sqlite3_api->column_name
86894 #define sqlite3_column_name16 sqlite3_api->column_name16
86895 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
86896 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
86897 #define sqlite3_column_table_name sqlite3_api->column_table_name
86898 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
86899 #define sqlite3_column_text sqlite3_api->column_text
86900 #define sqlite3_column_text16 sqlite3_api->column_text16
86901 #define sqlite3_column_type sqlite3_api->column_type
86902 #define sqlite3_column_value sqlite3_api->column_value
86903 #define sqlite3_commit_hook sqlite3_api->commit_hook
86904 #define sqlite3_complete sqlite3_api->complete
86905 #define sqlite3_complete16 sqlite3_api->complete16
86906 #define sqlite3_create_collation sqlite3_api->create_collation
86907 #define sqlite3_create_collation16 sqlite3_api->create_collation16
86908 #define sqlite3_create_function sqlite3_api->create_function
86909 #define sqlite3_create_function16 sqlite3_api->create_function16
86910 #define sqlite3_create_module sqlite3_api->create_module
86911 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
86912 #define sqlite3_data_count sqlite3_api->data_count
86913 #define sqlite3_db_handle sqlite3_api->db_handle
86914 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
86915 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
86916 #define sqlite3_errcode sqlite3_api->errcode
86917 #define sqlite3_errmsg sqlite3_api->errmsg
86918 #define sqlite3_errmsg16 sqlite3_api->errmsg16
86919 #define sqlite3_exec sqlite3_api->exec
86920 #ifndef SQLITE_OMIT_DEPRECATED
86921 #define sqlite3_expired sqlite3_api->expired
86922 #endif
86923 #define sqlite3_finalize sqlite3_api->finalize
86924 #define sqlite3_free sqlite3_api->free
86925 #define sqlite3_free_table sqlite3_api->free_table
86926 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
86927 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
86928 #define sqlite3_get_table sqlite3_api->get_table
86929 #ifndef SQLITE_OMIT_DEPRECATED
86930 #define sqlite3_global_recover sqlite3_api->global_recover
86931 #endif
86932 #define sqlite3_interrupt sqlite3_api->interruptx
86933 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
86934 #define sqlite3_libversion sqlite3_api->libversion
86935 #define sqlite3_libversion_number sqlite3_api->libversion_number
86936 #define sqlite3_malloc sqlite3_api->malloc
86937 #define sqlite3_mprintf sqlite3_api->mprintf
86938 #define sqlite3_open sqlite3_api->open
86939 #define sqlite3_open16 sqlite3_api->open16
86940 #define sqlite3_prepare sqlite3_api->prepare
86941 #define sqlite3_prepare16 sqlite3_api->prepare16
86942 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
86943 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
86944 #define sqlite3_profile sqlite3_api->profile
86945 #define sqlite3_progress_handler sqlite3_api->progress_handler
86946 #define sqlite3_realloc sqlite3_api->realloc
86947 #define sqlite3_reset sqlite3_api->reset
86948 #define sqlite3_result_blob sqlite3_api->result_blob
86949 #define sqlite3_result_double sqlite3_api->result_double
86950 #define sqlite3_result_error sqlite3_api->result_error
86951 #define sqlite3_result_error16 sqlite3_api->result_error16
86952 #define sqlite3_result_int sqlite3_api->result_int
86953 #define sqlite3_result_int64 sqlite3_api->result_int64
86954 #define sqlite3_result_null sqlite3_api->result_null
86955 #define sqlite3_result_text sqlite3_api->result_text
86956 #define sqlite3_result_text16 sqlite3_api->result_text16
86957 #define sqlite3_result_text16be sqlite3_api->result_text16be
86958 #define sqlite3_result_text16le sqlite3_api->result_text16le
86959 #define sqlite3_result_value sqlite3_api->result_value
86960 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
86961 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
86962 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
86963 #define sqlite3_snprintf sqlite3_api->snprintf
86964 #define sqlite3_step sqlite3_api->step
86965 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
86966 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
86967 #define sqlite3_total_changes sqlite3_api->total_changes
86968 #define sqlite3_trace sqlite3_api->trace
86969 #ifndef SQLITE_OMIT_DEPRECATED
86970 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
86971 #endif
86972 #define sqlite3_update_hook sqlite3_api->update_hook
86973 #define sqlite3_user_data sqlite3_api->user_data
86974 #define sqlite3_value_blob sqlite3_api->value_blob
86975 #define sqlite3_value_bytes sqlite3_api->value_bytes
86976 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
86977 #define sqlite3_value_double sqlite3_api->value_double
86978 #define sqlite3_value_int sqlite3_api->value_int
86979 #define sqlite3_value_int64 sqlite3_api->value_int64
86980 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
86981 #define sqlite3_value_text sqlite3_api->value_text
86982 #define sqlite3_value_text16 sqlite3_api->value_text16
86983 #define sqlite3_value_text16be sqlite3_api->value_text16be
86984 #define sqlite3_value_text16le sqlite3_api->value_text16le
86985 #define sqlite3_value_type sqlite3_api->value_type
86986 #define sqlite3_vmprintf sqlite3_api->vmprintf
86987 #define sqlite3_overload_function sqlite3_api->overload_function
86988 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
86989 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
86990 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
86991 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
86992 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
86993 #define sqlite3_blob_close sqlite3_api->blob_close
86994 #define sqlite3_blob_open sqlite3_api->blob_open
86995 #define sqlite3_blob_read sqlite3_api->blob_read
86996 #define sqlite3_blob_write sqlite3_api->blob_write
86997 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
86998 #define sqlite3_file_control sqlite3_api->file_control
86999 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
87000 #define sqlite3_memory_used sqlite3_api->memory_used
87001 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
87002 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
87003 #define sqlite3_mutex_free sqlite3_api->mutex_free
87004 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
87005 #define sqlite3_mutex_try sqlite3_api->mutex_try
87006 #define sqlite3_open_v2 sqlite3_api->open_v2
87007 #define sqlite3_release_memory sqlite3_api->release_memory
87008 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
87009 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
87010 #define sqlite3_sleep sqlite3_api->sleep
87011 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
87012 #define sqlite3_vfs_find sqlite3_api->vfs_find
87013 #define sqlite3_vfs_register sqlite3_api->vfs_register
87014 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
87015 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
87016 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
87017 #define sqlite3_result_error_code sqlite3_api->result_error_code
87018 #define sqlite3_test_control sqlite3_api->test_control
87019 #define sqlite3_randomness sqlite3_api->randomness
87020 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
87021 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
87022 #define sqlite3_limit sqlite3_api->limit
87023 #define sqlite3_next_stmt sqlite3_api->next_stmt
87024 #define sqlite3_sql sqlite3_api->sql
87025 #define sqlite3_status sqlite3_api->status
87026 #define sqlite3_backup_finish sqlite3_api->backup_finish
87027 #define sqlite3_backup_init sqlite3_api->backup_init
87028 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
87029 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
87030 #define sqlite3_backup_step sqlite3_api->backup_step
87031 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
87032 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
87033 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
87034 #define sqlite3_db_config sqlite3_api->db_config
87035 #define sqlite3_db_mutex sqlite3_api->db_mutex
87036 #define sqlite3_db_status sqlite3_api->db_status
87037 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
87038 #define sqlite3_log sqlite3_api->log
87039 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
87040 #define sqlite3_sourceid sqlite3_api->sourceid
87041 #define sqlite3_stmt_status sqlite3_api->stmt_status
87042 #define sqlite3_strnicmp sqlite3_api->strnicmp
87043 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
87044 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
87045 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
87046 #define sqlite3_wal_hook sqlite3_api->wal_hook
87047 #endif /* SQLITE_CORE */
87049 #define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api = 0;
87050 #define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v;
87052 #endif /* _SQLITE3EXT_H_ */
87054 /************** End of sqlite3ext.h ******************************************/
87055 /************** Continuing where we left off in loadext.c ********************/
87057 #ifndef SQLITE_OMIT_LOAD_EXTENSION
87060 ** Some API routines are omitted when various features are
87061 ** excluded from a build of SQLite. Substitute a NULL pointer
87062 ** for any missing APIs.
87064 #ifndef SQLITE_ENABLE_COLUMN_METADATA
87065 # define sqlite3_column_database_name 0
87066 # define sqlite3_column_database_name16 0
87067 # define sqlite3_column_table_name 0
87068 # define sqlite3_column_table_name16 0
87069 # define sqlite3_column_origin_name 0
87070 # define sqlite3_column_origin_name16 0
87071 # define sqlite3_table_column_metadata 0
87072 #endif
87074 #ifdef SQLITE_OMIT_AUTHORIZATION
87075 # define sqlite3_set_authorizer 0
87076 #endif
87078 #ifdef SQLITE_OMIT_UTF16
87079 # define sqlite3_bind_text16 0
87080 # define sqlite3_collation_needed16 0
87081 # define sqlite3_column_decltype16 0
87082 # define sqlite3_column_name16 0
87083 # define sqlite3_column_text16 0
87084 # define sqlite3_complete16 0
87085 # define sqlite3_create_collation16 0
87086 # define sqlite3_create_function16 0
87087 # define sqlite3_errmsg16 0
87088 # define sqlite3_open16 0
87089 # define sqlite3_prepare16 0
87090 # define sqlite3_prepare16_v2 0
87091 # define sqlite3_result_error16 0
87092 # define sqlite3_result_text16 0
87093 # define sqlite3_result_text16be 0
87094 # define sqlite3_result_text16le 0
87095 # define sqlite3_value_text16 0
87096 # define sqlite3_value_text16be 0
87097 # define sqlite3_value_text16le 0
87098 # define sqlite3_column_database_name16 0
87099 # define sqlite3_column_table_name16 0
87100 # define sqlite3_column_origin_name16 0
87101 #endif
87103 #ifdef SQLITE_OMIT_COMPLETE
87104 # define sqlite3_complete 0
87105 # define sqlite3_complete16 0
87106 #endif
87108 #ifdef SQLITE_OMIT_DECLTYPE
87109 # define sqlite3_column_decltype16 0
87110 # define sqlite3_column_decltype 0
87111 #endif
87113 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
87114 # define sqlite3_progress_handler 0
87115 #endif
87117 #ifdef SQLITE_OMIT_VIRTUALTABLE
87118 # define sqlite3_create_module 0
87119 # define sqlite3_create_module_v2 0
87120 # define sqlite3_declare_vtab 0
87121 #endif
87123 #ifdef SQLITE_OMIT_SHARED_CACHE
87124 # define sqlite3_enable_shared_cache 0
87125 #endif
87127 #ifdef SQLITE_OMIT_TRACE
87128 # define sqlite3_profile 0
87129 # define sqlite3_trace 0
87130 #endif
87132 #ifdef SQLITE_OMIT_GET_TABLE
87133 # define sqlite3_free_table 0
87134 # define sqlite3_get_table 0
87135 #endif
87137 #ifdef SQLITE_OMIT_INCRBLOB
87138 #define sqlite3_bind_zeroblob 0
87139 #define sqlite3_blob_bytes 0
87140 #define sqlite3_blob_close 0
87141 #define sqlite3_blob_open 0
87142 #define sqlite3_blob_read 0
87143 #define sqlite3_blob_write 0
87144 #endif
87147 ** The following structure contains pointers to all SQLite API routines.
87148 ** A pointer to this structure is passed into extensions when they are
87149 ** loaded so that the extension can make calls back into the SQLite
87150 ** library.
87152 ** When adding new APIs, add them to the bottom of this structure
87153 ** in order to preserve backwards compatibility.
87155 ** Extensions that use newer APIs should first call the
87156 ** sqlite3_libversion_number() to make sure that the API they
87157 ** intend to use is supported by the library. Extensions should
87158 ** also check to make sure that the pointer to the function is
87159 ** not NULL before calling it.
87161 static const sqlite3_api_routines sqlite3Apis = {
87162 sqlite3_aggregate_context,
87163 #ifndef SQLITE_OMIT_DEPRECATED
87164 sqlite3_aggregate_count,
87165 #else
87167 #endif
87168 sqlite3_bind_blob,
87169 sqlite3_bind_double,
87170 sqlite3_bind_int,
87171 sqlite3_bind_int64,
87172 sqlite3_bind_null,
87173 sqlite3_bind_parameter_count,
87174 sqlite3_bind_parameter_index,
87175 sqlite3_bind_parameter_name,
87176 sqlite3_bind_text,
87177 sqlite3_bind_text16,
87178 sqlite3_bind_value,
87179 sqlite3_busy_handler,
87180 sqlite3_busy_timeout,
87181 sqlite3_changes,
87182 sqlite3_close,
87183 sqlite3_collation_needed,
87184 sqlite3_collation_needed16,
87185 sqlite3_column_blob,
87186 sqlite3_column_bytes,
87187 sqlite3_column_bytes16,
87188 sqlite3_column_count,
87189 sqlite3_column_database_name,
87190 sqlite3_column_database_name16,
87191 sqlite3_column_decltype,
87192 sqlite3_column_decltype16,
87193 sqlite3_column_double,
87194 sqlite3_column_int,
87195 sqlite3_column_int64,
87196 sqlite3_column_name,
87197 sqlite3_column_name16,
87198 sqlite3_column_origin_name,
87199 sqlite3_column_origin_name16,
87200 sqlite3_column_table_name,
87201 sqlite3_column_table_name16,
87202 sqlite3_column_text,
87203 sqlite3_column_text16,
87204 sqlite3_column_type,
87205 sqlite3_column_value,
87206 sqlite3_commit_hook,
87207 sqlite3_complete,
87208 sqlite3_complete16,
87209 sqlite3_create_collation,
87210 sqlite3_create_collation16,
87211 sqlite3_create_function,
87212 sqlite3_create_function16,
87213 sqlite3_create_module,
87214 sqlite3_data_count,
87215 sqlite3_db_handle,
87216 sqlite3_declare_vtab,
87217 sqlite3_enable_shared_cache,
87218 sqlite3_errcode,
87219 sqlite3_errmsg,
87220 sqlite3_errmsg16,
87221 sqlite3_exec,
87222 #ifndef SQLITE_OMIT_DEPRECATED
87223 sqlite3_expired,
87224 #else
87226 #endif
87227 sqlite3_finalize,
87228 sqlite3_free,
87229 sqlite3_free_table,
87230 sqlite3_get_autocommit,
87231 sqlite3_get_auxdata,
87232 sqlite3_get_table,
87233 0, /* Was sqlite3_global_recover(), but that function is deprecated */
87234 sqlite3_interrupt,
87235 sqlite3_last_insert_rowid,
87236 sqlite3_libversion,
87237 sqlite3_libversion_number,
87238 sqlite3_malloc,
87239 sqlite3_mprintf,
87240 sqlite3_open,
87241 sqlite3_open16,
87242 sqlite3_prepare,
87243 sqlite3_prepare16,
87244 sqlite3_profile,
87245 sqlite3_progress_handler,
87246 sqlite3_realloc,
87247 sqlite3_reset,
87248 sqlite3_result_blob,
87249 sqlite3_result_double,
87250 sqlite3_result_error,
87251 sqlite3_result_error16,
87252 sqlite3_result_int,
87253 sqlite3_result_int64,
87254 sqlite3_result_null,
87255 sqlite3_result_text,
87256 sqlite3_result_text16,
87257 sqlite3_result_text16be,
87258 sqlite3_result_text16le,
87259 sqlite3_result_value,
87260 sqlite3_rollback_hook,
87261 sqlite3_set_authorizer,
87262 sqlite3_set_auxdata,
87263 sqlite3_snprintf,
87264 sqlite3_step,
87265 sqlite3_table_column_metadata,
87266 #ifndef SQLITE_OMIT_DEPRECATED
87267 sqlite3_thread_cleanup,
87268 #else
87270 #endif
87271 sqlite3_total_changes,
87272 sqlite3_trace,
87273 #ifndef SQLITE_OMIT_DEPRECATED
87274 sqlite3_transfer_bindings,
87275 #else
87277 #endif
87278 sqlite3_update_hook,
87279 sqlite3_user_data,
87280 sqlite3_value_blob,
87281 sqlite3_value_bytes,
87282 sqlite3_value_bytes16,
87283 sqlite3_value_double,
87284 sqlite3_value_int,
87285 sqlite3_value_int64,
87286 sqlite3_value_numeric_type,
87287 sqlite3_value_text,
87288 sqlite3_value_text16,
87289 sqlite3_value_text16be,
87290 sqlite3_value_text16le,
87291 sqlite3_value_type,
87292 sqlite3_vmprintf,
87294 ** The original API set ends here. All extensions can call any
87295 ** of the APIs above provided that the pointer is not NULL. But
87296 ** before calling APIs that follow, extension should check the
87297 ** sqlite3_libversion_number() to make sure they are dealing with
87298 ** a library that is new enough to support that API.
87299 *************************************************************************
87301 sqlite3_overload_function,
87304 ** Added after 3.3.13
87306 sqlite3_prepare_v2,
87307 sqlite3_prepare16_v2,
87308 sqlite3_clear_bindings,
87311 ** Added for 3.4.1
87313 sqlite3_create_module_v2,
87316 ** Added for 3.5.0
87318 sqlite3_bind_zeroblob,
87319 sqlite3_blob_bytes,
87320 sqlite3_blob_close,
87321 sqlite3_blob_open,
87322 sqlite3_blob_read,
87323 sqlite3_blob_write,
87324 sqlite3_create_collation_v2,
87325 sqlite3_file_control,
87326 sqlite3_memory_highwater,
87327 sqlite3_memory_used,
87328 #ifdef SQLITE_MUTEX_OMIT
87334 #else
87335 sqlite3_mutex_alloc,
87336 sqlite3_mutex_enter,
87337 sqlite3_mutex_free,
87338 sqlite3_mutex_leave,
87339 sqlite3_mutex_try,
87340 #endif
87341 sqlite3_open_v2,
87342 sqlite3_release_memory,
87343 sqlite3_result_error_nomem,
87344 sqlite3_result_error_toobig,
87345 sqlite3_sleep,
87346 sqlite3_soft_heap_limit,
87347 sqlite3_vfs_find,
87348 sqlite3_vfs_register,
87349 sqlite3_vfs_unregister,
87352 ** Added for 3.5.8
87354 sqlite3_threadsafe,
87355 sqlite3_result_zeroblob,
87356 sqlite3_result_error_code,
87357 sqlite3_test_control,
87358 sqlite3_randomness,
87359 sqlite3_context_db_handle,
87362 ** Added for 3.6.0
87364 sqlite3_extended_result_codes,
87365 sqlite3_limit,
87366 sqlite3_next_stmt,
87367 sqlite3_sql,
87368 sqlite3_status,
87371 ** Added for 3.7.4
87373 sqlite3_backup_finish,
87374 sqlite3_backup_init,
87375 sqlite3_backup_pagecount,
87376 sqlite3_backup_remaining,
87377 sqlite3_backup_step,
87378 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87379 sqlite3_compileoption_get,
87380 sqlite3_compileoption_used,
87381 #else
87384 #endif
87385 sqlite3_create_function_v2,
87386 sqlite3_db_config,
87387 sqlite3_db_mutex,
87388 sqlite3_db_status,
87389 sqlite3_extended_errcode,
87390 sqlite3_log,
87391 sqlite3_soft_heap_limit64,
87392 sqlite3_sourceid,
87393 sqlite3_stmt_status,
87394 sqlite3_strnicmp,
87395 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
87396 sqlite3_unlock_notify,
87397 #else
87399 #endif
87400 #ifndef SQLITE_OMIT_WAL
87401 sqlite3_wal_autocheckpoint,
87402 sqlite3_wal_checkpoint,
87403 sqlite3_wal_hook,
87404 #else
87408 #endif
87412 ** Attempt to load an SQLite extension library contained in the file
87413 ** zFile. The entry point is zProc. zProc may be 0 in which case a
87414 ** default entry point name (sqlite3_extension_init) is used. Use
87415 ** of the default name is recommended.
87417 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
87419 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
87420 ** error message text. The calling function should free this memory
87421 ** by calling sqlite3DbFree(db, ).
87423 static int sqlite3LoadExtension(
87424 sqlite3 *db, /* Load the extension into this database connection */
87425 const char *zFile, /* Name of the shared library containing extension */
87426 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
87427 char **pzErrMsg /* Put error message here if not 0 */
87429 sqlite3_vfs *pVfs = db->pVfs;
87430 void *handle;
87431 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
87432 char *zErrmsg = 0;
87433 void **aHandle;
87434 const int nMsg = 300;
87436 if( pzErrMsg ) *pzErrMsg = 0;
87438 /* Ticket #1863. To avoid a creating security problems for older
87439 ** applications that relink against newer versions of SQLite, the
87440 ** ability to run load_extension is turned off by default. One
87441 ** must call sqlite3_enable_load_extension() to turn on extension
87442 ** loading. Otherwise you get the following error.
87444 if( (db->flags & SQLITE_LoadExtension)==0 ){
87445 if( pzErrMsg ){
87446 *pzErrMsg = sqlite3_mprintf("not authorized");
87448 return SQLITE_ERROR;
87451 if( zProc==0 ){
87452 zProc = "sqlite3_extension_init";
87455 handle = sqlite3OsDlOpen(pVfs, zFile);
87456 if( handle==0 ){
87457 if( pzErrMsg ){
87458 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87459 if( zErrmsg ){
87460 sqlite3_snprintf(nMsg, zErrmsg,
87461 "unable to open shared library [%s]", zFile);
87462 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87465 return SQLITE_ERROR;
87467 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
87468 sqlite3OsDlSym(pVfs, handle, zProc);
87469 if( xInit==0 ){
87470 if( pzErrMsg ){
87471 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87472 if( zErrmsg ){
87473 sqlite3_snprintf(nMsg, zErrmsg,
87474 "no entry point [%s] in shared library [%s]", zProc,zFile);
87475 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87477 sqlite3OsDlClose(pVfs, handle);
87479 return SQLITE_ERROR;
87480 }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
87481 if( pzErrMsg ){
87482 *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
87484 sqlite3_free(zErrmsg);
87485 sqlite3OsDlClose(pVfs, handle);
87486 return SQLITE_ERROR;
87489 /* Append the new shared library handle to the db->aExtension array. */
87490 aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
87491 if( aHandle==0 ){
87492 return SQLITE_NOMEM;
87494 if( db->nExtension>0 ){
87495 memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
87497 sqlite3DbFree(db, db->aExtension);
87498 db->aExtension = aHandle;
87500 db->aExtension[db->nExtension++] = handle;
87501 return SQLITE_OK;
87503 SQLITE_API int sqlite3_load_extension(
87504 sqlite3 *db, /* Load the extension into this database connection */
87505 const char *zFile, /* Name of the shared library containing extension */
87506 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
87507 char **pzErrMsg /* Put error message here if not 0 */
87509 int rc;
87510 sqlite3_mutex_enter(db->mutex);
87511 rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
87512 rc = sqlite3ApiExit(db, rc);
87513 sqlite3_mutex_leave(db->mutex);
87514 return rc;
87518 ** Call this routine when the database connection is closing in order
87519 ** to clean up loaded extensions
87521 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
87522 int i;
87523 assert( sqlite3_mutex_held(db->mutex) );
87524 for(i=0; i<db->nExtension; i++){
87525 sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
87527 sqlite3DbFree(db, db->aExtension);
87531 ** Enable or disable extension loading. Extension loading is disabled by
87532 ** default so as not to open security holes in older applications.
87534 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
87535 sqlite3_mutex_enter(db->mutex);
87536 if( onoff ){
87537 db->flags |= SQLITE_LoadExtension;
87538 }else{
87539 db->flags &= ~SQLITE_LoadExtension;
87541 sqlite3_mutex_leave(db->mutex);
87542 return SQLITE_OK;
87545 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
87548 ** The auto-extension code added regardless of whether or not extension
87549 ** loading is supported. We need a dummy sqlite3Apis pointer for that
87550 ** code if regular extension loading is not available. This is that
87551 ** dummy pointer.
87553 #ifdef SQLITE_OMIT_LOAD_EXTENSION
87554 static const sqlite3_api_routines sqlite3Apis = { 0 };
87555 #endif
87559 ** The following object holds the list of automatically loaded
87560 ** extensions.
87562 ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
87563 ** mutex must be held while accessing this list.
87565 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
87566 static SQLITE_WSD struct sqlite3AutoExtList {
87567 int nExt; /* Number of entries in aExt[] */
87568 void (**aExt)(void); /* Pointers to the extension init functions */
87569 } sqlite3Autoext = { 0, 0 };
87571 /* The "wsdAutoext" macro will resolve to the autoextension
87572 ** state vector. If writable static data is unsupported on the target,
87573 ** we have to locate the state vector at run-time. In the more common
87574 ** case where writable static data is supported, wsdStat can refer directly
87575 ** to the "sqlite3Autoext" state vector declared above.
87577 #ifdef SQLITE_OMIT_WSD
87578 # define wsdAutoextInit \
87579 sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
87580 # define wsdAutoext x[0]
87581 #else
87582 # define wsdAutoextInit
87583 # define wsdAutoext sqlite3Autoext
87584 #endif
87588 ** Register a statically linked extension that is automatically
87589 ** loaded by every new database connection.
87591 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
87592 int rc = SQLITE_OK;
87593 #ifndef SQLITE_OMIT_AUTOINIT
87594 rc = sqlite3_initialize();
87595 if( rc ){
87596 return rc;
87597 }else
87598 #endif
87600 int i;
87601 #if SQLITE_THREADSAFE
87602 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87603 #endif
87604 wsdAutoextInit;
87605 sqlite3_mutex_enter(mutex);
87606 for(i=0; i<wsdAutoext.nExt; i++){
87607 if( wsdAutoext.aExt[i]==xInit ) break;
87609 if( i==wsdAutoext.nExt ){
87610 int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
87611 void (**aNew)(void);
87612 aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
87613 if( aNew==0 ){
87614 rc = SQLITE_NOMEM;
87615 }else{
87616 wsdAutoext.aExt = aNew;
87617 wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
87618 wsdAutoext.nExt++;
87621 sqlite3_mutex_leave(mutex);
87622 assert( (rc&0xff)==rc );
87623 return rc;
87628 ** Reset the automatic extension loading mechanism.
87630 SQLITE_API void sqlite3_reset_auto_extension(void){
87631 #ifndef SQLITE_OMIT_AUTOINIT
87632 if( sqlite3_initialize()==SQLITE_OK )
87633 #endif
87635 #if SQLITE_THREADSAFE
87636 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87637 #endif
87638 wsdAutoextInit;
87639 sqlite3_mutex_enter(mutex);
87640 sqlite3_free(wsdAutoext.aExt);
87641 wsdAutoext.aExt = 0;
87642 wsdAutoext.nExt = 0;
87643 sqlite3_mutex_leave(mutex);
87648 ** Load all automatic extensions.
87650 ** If anything goes wrong, set an error in the database connection.
87652 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
87653 int i;
87654 int go = 1;
87655 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
87657 wsdAutoextInit;
87658 if( wsdAutoext.nExt==0 ){
87659 /* Common case: early out without every having to acquire a mutex */
87660 return;
87662 for(i=0; go; i++){
87663 char *zErrmsg;
87664 #if SQLITE_THREADSAFE
87665 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87666 #endif
87667 sqlite3_mutex_enter(mutex);
87668 if( i>=wsdAutoext.nExt ){
87669 xInit = 0;
87670 go = 0;
87671 }else{
87672 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
87673 wsdAutoext.aExt[i];
87675 sqlite3_mutex_leave(mutex);
87676 zErrmsg = 0;
87677 if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
87678 sqlite3Error(db, SQLITE_ERROR,
87679 "automatic extension loading failed: %s", zErrmsg);
87680 go = 0;
87682 sqlite3_free(zErrmsg);
87686 /************** End of loadext.c *********************************************/
87687 /************** Begin file pragma.c ******************************************/
87689 ** 2003 April 6
87691 ** The author disclaims copyright to this source code. In place of
87692 ** a legal notice, here is a blessing:
87694 ** May you do good and not evil.
87695 ** May you find forgiveness for yourself and forgive others.
87696 ** May you share freely, never taking more than you give.
87698 *************************************************************************
87699 ** This file contains code used to implement the PRAGMA command.
87702 /* Ignore this whole file if pragmas are disabled
87704 #if !defined(SQLITE_OMIT_PRAGMA)
87707 ** Interpret the given string as a safety level. Return 0 for OFF,
87708 ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
87709 ** unrecognized string argument.
87711 ** Note that the values returned are one less that the values that
87712 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
87713 ** to support legacy SQL code. The safety level used to be boolean
87714 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
87716 static u8 getSafetyLevel(const char *z){
87717 /* 123456789 123456789 */
87718 static const char zText[] = "onoffalseyestruefull";
87719 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
87720 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
87721 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
87722 int i, n;
87723 if( sqlite3Isdigit(*z) ){
87724 return (u8)sqlite3Atoi(z);
87726 n = sqlite3Strlen30(z);
87727 for(i=0; i<ArraySize(iLength); i++){
87728 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
87729 return iValue[i];
87732 return 1;
87736 ** Interpret the given string as a boolean value.
87738 static u8 getBoolean(const char *z){
87739 return getSafetyLevel(z)&1;
87743 ** Interpret the given string as a locking mode value.
87745 static int getLockingMode(const char *z){
87746 if( z ){
87747 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
87748 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
87750 return PAGER_LOCKINGMODE_QUERY;
87753 #ifndef SQLITE_OMIT_AUTOVACUUM
87755 ** Interpret the given string as an auto-vacuum mode value.
87757 ** The following strings, "none", "full" and "incremental" are
87758 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
87760 static int getAutoVacuum(const char *z){
87761 int i;
87762 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
87763 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
87764 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
87765 i = sqlite3Atoi(z);
87766 return (u8)((i>=0&&i<=2)?i:0);
87768 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
87770 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87772 ** Interpret the given string as a temp db location. Return 1 for file
87773 ** backed temporary databases, 2 for the Red-Black tree in memory database
87774 ** and 0 to use the compile-time default.
87776 static int getTempStore(const char *z){
87777 if( z[0]>='0' && z[0]<='2' ){
87778 return z[0] - '0';
87779 }else if( sqlite3StrICmp(z, "file")==0 ){
87780 return 1;
87781 }else if( sqlite3StrICmp(z, "memory")==0 ){
87782 return 2;
87783 }else{
87784 return 0;
87787 #endif /* SQLITE_PAGER_PRAGMAS */
87789 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87791 ** Invalidate temp storage, either when the temp storage is changed
87792 ** from default, or when 'file' and the temp_store_directory has changed
87794 static int invalidateTempStorage(Parse *pParse){
87795 sqlite3 *db = pParse->db;
87796 if( db->aDb[1].pBt!=0 ){
87797 if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
87798 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
87799 "from within a transaction");
87800 return SQLITE_ERROR;
87802 sqlite3BtreeClose(db->aDb[1].pBt);
87803 db->aDb[1].pBt = 0;
87804 sqlite3ResetInternalSchema(db, -1);
87806 return SQLITE_OK;
87808 #endif /* SQLITE_PAGER_PRAGMAS */
87810 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87812 ** If the TEMP database is open, close it and mark the database schema
87813 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
87814 ** or DEFAULT_TEMP_STORE pragmas.
87816 static int changeTempStorage(Parse *pParse, const char *zStorageType){
87817 int ts = getTempStore(zStorageType);
87818 sqlite3 *db = pParse->db;
87819 if( db->temp_store==ts ) return SQLITE_OK;
87820 if( invalidateTempStorage( pParse ) != SQLITE_OK ){
87821 return SQLITE_ERROR;
87823 db->temp_store = (u8)ts;
87824 return SQLITE_OK;
87826 #endif /* SQLITE_PAGER_PRAGMAS */
87829 ** Generate code to return a single integer value.
87831 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
87832 Vdbe *v = sqlite3GetVdbe(pParse);
87833 int mem = ++pParse->nMem;
87834 i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
87835 if( pI64 ){
87836 memcpy(pI64, &value, sizeof(value));
87838 sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
87839 sqlite3VdbeSetNumCols(v, 1);
87840 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
87841 sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
87844 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
87846 ** Check to see if zRight and zLeft refer to a pragma that queries
87847 ** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
87848 ** Also, implement the pragma.
87850 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
87851 static const struct sPragmaType {
87852 const char *zName; /* Name of the pragma */
87853 int mask; /* Mask for the db->flags value */
87854 } aPragma[] = {
87855 { "full_column_names", SQLITE_FullColNames },
87856 { "short_column_names", SQLITE_ShortColNames },
87857 { "count_changes", SQLITE_CountRows },
87858 { "empty_result_callbacks", SQLITE_NullCallback },
87859 { "legacy_file_format", SQLITE_LegacyFileFmt },
87860 { "fullfsync", SQLITE_FullFSync },
87861 { "checkpoint_fullfsync", SQLITE_CkptFullFSync },
87862 { "reverse_unordered_selects", SQLITE_ReverseOrder },
87863 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
87864 { "automatic_index", SQLITE_AutoIndex },
87865 #endif
87866 #ifdef SQLITE_DEBUG
87867 { "sql_trace", SQLITE_SqlTrace },
87868 { "vdbe_listing", SQLITE_VdbeListing },
87869 { "vdbe_trace", SQLITE_VdbeTrace },
87870 #endif
87871 #ifndef SQLITE_OMIT_CHECK
87872 { "ignore_check_constraints", SQLITE_IgnoreChecks },
87873 #endif
87874 /* The following is VERY experimental */
87875 { "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode },
87876 { "omit_readlock", SQLITE_NoReadlock },
87878 /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
87879 ** flag if there are any active statements. */
87880 { "read_uncommitted", SQLITE_ReadUncommitted },
87881 { "recursive_triggers", SQLITE_RecTriggers },
87883 /* This flag may only be set if both foreign-key and trigger support
87884 ** are present in the build. */
87885 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
87886 { "foreign_keys", SQLITE_ForeignKeys },
87887 #endif
87889 int i;
87890 const struct sPragmaType *p;
87891 for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
87892 if( sqlite3StrICmp(zLeft, p->zName)==0 ){
87893 sqlite3 *db = pParse->db;
87894 Vdbe *v;
87895 v = sqlite3GetVdbe(pParse);
87896 assert( v!=0 ); /* Already allocated by sqlite3Pragma() */
87897 if( ALWAYS(v) ){
87898 if( zRight==0 ){
87899 returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
87900 }else{
87901 int mask = p->mask; /* Mask of bits to set or clear. */
87902 if( db->autoCommit==0 ){
87903 /* Foreign key support may not be enabled or disabled while not
87904 ** in auto-commit mode. */
87905 mask &= ~(SQLITE_ForeignKeys);
87908 if( getBoolean(zRight) ){
87909 db->flags |= mask;
87910 }else{
87911 db->flags &= ~mask;
87914 /* Many of the flag-pragmas modify the code generated by the SQL
87915 ** compiler (eg. count_changes). So add an opcode to expire all
87916 ** compiled SQL statements after modifying a pragma value.
87918 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
87922 return 1;
87925 return 0;
87927 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
87930 ** Return a human-readable name for a constraint resolution action.
87932 #ifndef SQLITE_OMIT_FOREIGN_KEY
87933 static const char *actionName(u8 action){
87934 const char *zName;
87935 switch( action ){
87936 case OE_SetNull: zName = "SET NULL"; break;
87937 case OE_SetDflt: zName = "SET DEFAULT"; break;
87938 case OE_Cascade: zName = "CASCADE"; break;
87939 case OE_Restrict: zName = "RESTRICT"; break;
87940 default: zName = "NO ACTION";
87941 assert( action==OE_None ); break;
87943 return zName;
87945 #endif
87949 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
87950 ** defined in pager.h. This function returns the associated lowercase
87951 ** journal-mode name.
87953 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
87954 static char * const azModeName[] = {
87955 "delete", "persist", "off", "truncate", "memory"
87956 #ifndef SQLITE_OMIT_WAL
87957 , "wal"
87958 #endif
87960 assert( PAGER_JOURNALMODE_DELETE==0 );
87961 assert( PAGER_JOURNALMODE_PERSIST==1 );
87962 assert( PAGER_JOURNALMODE_OFF==2 );
87963 assert( PAGER_JOURNALMODE_TRUNCATE==3 );
87964 assert( PAGER_JOURNALMODE_MEMORY==4 );
87965 assert( PAGER_JOURNALMODE_WAL==5 );
87966 assert( eMode>=0 && eMode<=ArraySize(azModeName) );
87968 if( eMode==ArraySize(azModeName) ) return 0;
87969 return azModeName[eMode];
87973 ** Process a pragma statement.
87975 ** Pragmas are of this form:
87977 ** PRAGMA [database.]id [= value]
87979 ** The identifier might also be a string. The value is a string, and
87980 ** identifier, or a number. If minusFlag is true, then the value is
87981 ** a number that was preceded by a minus sign.
87983 ** If the left side is "database.id" then pId1 is the database name
87984 ** and pId2 is the id. If the left side is just "id" then pId1 is the
87985 ** id and pId2 is any empty string.
87987 SQLITE_PRIVATE void sqlite3Pragma(
87988 Parse *pParse,
87989 Token *pId1, /* First part of [database.]id field */
87990 Token *pId2, /* Second part of [database.]id field, or NULL */
87991 Token *pValue, /* Token for <value>, or NULL */
87992 int minusFlag /* True if a '-' sign preceded <value> */
87994 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
87995 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
87996 const char *zDb = 0; /* The database name */
87997 Token *pId; /* Pointer to <id> token */
87998 int iDb; /* Database index for <database> */
87999 sqlite3 *db = pParse->db;
88000 Db *pDb;
88001 Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
88002 if( v==0 ) return;
88003 sqlite3VdbeRunOnlyOnce(v);
88004 pParse->nMem = 2;
88006 /* Interpret the [database.] part of the pragma statement. iDb is the
88007 ** index of the database this pragma is being applied to in db.aDb[]. */
88008 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
88009 if( iDb<0 ) return;
88010 pDb = &db->aDb[iDb];
88012 /* If the temp database has been explicitly named as part of the
88013 ** pragma, make sure it is open.
88015 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
88016 return;
88019 zLeft = sqlite3NameFromToken(db, pId);
88020 if( !zLeft ) return;
88021 if( minusFlag ){
88022 zRight = sqlite3MPrintf(db, "-%T", pValue);
88023 }else{
88024 zRight = sqlite3NameFromToken(db, pValue);
88027 assert( pId2 );
88028 zDb = pId2->n>0 ? pDb->zName : 0;
88029 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
88030 goto pragma_out;
88033 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88035 ** PRAGMA [database.]default_cache_size
88036 ** PRAGMA [database.]default_cache_size=N
88038 ** The first form reports the current persistent setting for the
88039 ** page cache size. The value returned is the maximum number of
88040 ** pages in the page cache. The second form sets both the current
88041 ** page cache size value and the persistent page cache size value
88042 ** stored in the database file.
88044 ** Older versions of SQLite would set the default cache size to a
88045 ** negative number to indicate synchronous=OFF. These days, synchronous
88046 ** is always on by default regardless of the sign of the default cache
88047 ** size. But continue to take the absolute value of the default cache
88048 ** size of historical compatibility.
88050 if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
88051 static const VdbeOpList getCacheSize[] = {
88052 { OP_Transaction, 0, 0, 0}, /* 0 */
88053 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
88054 { OP_IfPos, 1, 7, 0},
88055 { OP_Integer, 0, 2, 0},
88056 { OP_Subtract, 1, 2, 1},
88057 { OP_IfPos, 1, 7, 0},
88058 { OP_Integer, 0, 1, 0}, /* 6 */
88059 { OP_ResultRow, 1, 1, 0},
88061 int addr;
88062 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88063 sqlite3VdbeUsesBtree(v, iDb);
88064 if( !zRight ){
88065 sqlite3VdbeSetNumCols(v, 1);
88066 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
88067 pParse->nMem += 2;
88068 addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
88069 sqlite3VdbeChangeP1(v, addr, iDb);
88070 sqlite3VdbeChangeP1(v, addr+1, iDb);
88071 sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
88072 }else{
88073 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
88074 sqlite3BeginWriteOperation(pParse, 0, iDb);
88075 sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
88076 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
88077 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88078 pDb->pSchema->cache_size = size;
88079 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
88081 }else
88084 ** PRAGMA [database.]page_size
88085 ** PRAGMA [database.]page_size=N
88087 ** The first form reports the current setting for the
88088 ** database page size in bytes. The second form sets the
88089 ** database page size value. The value can only be set if
88090 ** the database has not yet been created.
88092 if( sqlite3StrICmp(zLeft,"page_size")==0 ){
88093 Btree *pBt = pDb->pBt;
88094 assert( pBt!=0 );
88095 if( !zRight ){
88096 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
88097 returnSingleInt(pParse, "page_size", size);
88098 }else{
88099 /* Malloc may fail when setting the page-size, as there is an internal
88100 ** buffer that the pager module resizes using sqlite3_realloc().
88102 db->nextPagesize = sqlite3Atoi(zRight);
88103 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
88104 db->mallocFailed = 1;
88107 }else
88110 ** PRAGMA [database.]secure_delete
88111 ** PRAGMA [database.]secure_delete=ON/OFF
88113 ** The first form reports the current setting for the
88114 ** secure_delete flag. The second form changes the secure_delete
88115 ** flag setting and reports thenew value.
88117 if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
88118 Btree *pBt = pDb->pBt;
88119 int b = -1;
88120 assert( pBt!=0 );
88121 if( zRight ){
88122 b = getBoolean(zRight);
88124 if( pId2->n==0 && b>=0 ){
88125 int ii;
88126 for(ii=0; ii<db->nDb; ii++){
88127 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
88130 b = sqlite3BtreeSecureDelete(pBt, b);
88131 returnSingleInt(pParse, "secure_delete", b);
88132 }else
88135 ** PRAGMA [database.]max_page_count
88136 ** PRAGMA [database.]max_page_count=N
88138 ** The first form reports the current setting for the
88139 ** maximum number of pages in the database file. The
88140 ** second form attempts to change this setting. Both
88141 ** forms return the current setting.
88143 ** PRAGMA [database.]page_count
88145 ** Return the number of pages in the specified database.
88147 if( sqlite3StrICmp(zLeft,"page_count")==0
88148 || sqlite3StrICmp(zLeft,"max_page_count")==0
88150 int iReg;
88151 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88152 sqlite3CodeVerifySchema(pParse, iDb);
88153 iReg = ++pParse->nMem;
88154 if( zLeft[0]=='p' ){
88155 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
88156 }else{
88157 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
88159 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
88160 sqlite3VdbeSetNumCols(v, 1);
88161 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
88162 }else
88165 ** PRAGMA [database.]locking_mode
88166 ** PRAGMA [database.]locking_mode = (normal|exclusive)
88168 if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
88169 const char *zRet = "normal";
88170 int eMode = getLockingMode(zRight);
88172 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
88173 /* Simple "PRAGMA locking_mode;" statement. This is a query for
88174 ** the current default locking mode (which may be different to
88175 ** the locking-mode of the main database).
88177 eMode = db->dfltLockMode;
88178 }else{
88179 Pager *pPager;
88180 if( pId2->n==0 ){
88181 /* This indicates that no database name was specified as part
88182 ** of the PRAGMA command. In this case the locking-mode must be
88183 ** set on all attached databases, as well as the main db file.
88185 ** Also, the sqlite3.dfltLockMode variable is set so that
88186 ** any subsequently attached databases also use the specified
88187 ** locking mode.
88189 int ii;
88190 assert(pDb==&db->aDb[0]);
88191 for(ii=2; ii<db->nDb; ii++){
88192 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
88193 sqlite3PagerLockingMode(pPager, eMode);
88195 db->dfltLockMode = (u8)eMode;
88197 pPager = sqlite3BtreePager(pDb->pBt);
88198 eMode = sqlite3PagerLockingMode(pPager, eMode);
88201 assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
88202 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
88203 zRet = "exclusive";
88205 sqlite3VdbeSetNumCols(v, 1);
88206 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
88207 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
88208 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88209 }else
88212 ** PRAGMA [database.]journal_mode
88213 ** PRAGMA [database.]journal_mode =
88214 ** (delete|persist|off|truncate|memory|wal|off)
88216 if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
88217 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
88218 int ii; /* Loop counter */
88220 /* Force the schema to be loaded on all databases. This cases all
88221 ** database files to be opened and the journal_modes set. */
88222 if( sqlite3ReadSchema(pParse) ){
88223 goto pragma_out;
88226 sqlite3VdbeSetNumCols(v, 1);
88227 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
88229 if( zRight==0 ){
88230 /* If there is no "=MODE" part of the pragma, do a query for the
88231 ** current mode */
88232 eMode = PAGER_JOURNALMODE_QUERY;
88233 }else{
88234 const char *zMode;
88235 int n = sqlite3Strlen30(zRight);
88236 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
88237 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
88239 if( !zMode ){
88240 /* If the "=MODE" part does not match any known journal mode,
88241 ** then do a query */
88242 eMode = PAGER_JOURNALMODE_QUERY;
88245 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
88246 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
88247 iDb = 0;
88248 pId2->n = 1;
88250 for(ii=db->nDb-1; ii>=0; ii--){
88251 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
88252 sqlite3VdbeUsesBtree(v, ii);
88253 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
88256 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88257 }else
88260 ** PRAGMA [database.]journal_size_limit
88261 ** PRAGMA [database.]journal_size_limit=N
88263 ** Get or set the size limit on rollback journal files.
88265 if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
88266 Pager *pPager = sqlite3BtreePager(pDb->pBt);
88267 i64 iLimit = -2;
88268 if( zRight ){
88269 sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
88270 if( iLimit<-1 ) iLimit = -1;
88272 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
88273 returnSingleInt(pParse, "journal_size_limit", iLimit);
88274 }else
88276 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
88279 ** PRAGMA [database.]auto_vacuum
88280 ** PRAGMA [database.]auto_vacuum=N
88282 ** Get or set the value of the database 'auto-vacuum' parameter.
88283 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
88285 #ifndef SQLITE_OMIT_AUTOVACUUM
88286 if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
88287 Btree *pBt = pDb->pBt;
88288 assert( pBt!=0 );
88289 if( sqlite3ReadSchema(pParse) ){
88290 goto pragma_out;
88292 if( !zRight ){
88293 int auto_vacuum;
88294 if( ALWAYS(pBt) ){
88295 auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
88296 }else{
88297 auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
88299 returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
88300 }else{
88301 int eAuto = getAutoVacuum(zRight);
88302 assert( eAuto>=0 && eAuto<=2 );
88303 db->nextAutovac = (u8)eAuto;
88304 if( ALWAYS(eAuto>=0) ){
88305 /* Call SetAutoVacuum() to set initialize the internal auto and
88306 ** incr-vacuum flags. This is required in case this connection
88307 ** creates the database file. It is important that it is created
88308 ** as an auto-vacuum capable db.
88310 int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
88311 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
88312 /* When setting the auto_vacuum mode to either "full" or
88313 ** "incremental", write the value of meta[6] in the database
88314 ** file. Before writing to meta[6], check that meta[3] indicates
88315 ** that this really is an auto-vacuum capable database.
88317 static const VdbeOpList setMeta6[] = {
88318 { OP_Transaction, 0, 1, 0}, /* 0 */
88319 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
88320 { OP_If, 1, 0, 0}, /* 2 */
88321 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
88322 { OP_Integer, 0, 1, 0}, /* 4 */
88323 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
88325 int iAddr;
88326 iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
88327 sqlite3VdbeChangeP1(v, iAddr, iDb);
88328 sqlite3VdbeChangeP1(v, iAddr+1, iDb);
88329 sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
88330 sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
88331 sqlite3VdbeChangeP1(v, iAddr+5, iDb);
88332 sqlite3VdbeUsesBtree(v, iDb);
88336 }else
88337 #endif
88340 ** PRAGMA [database.]incremental_vacuum(N)
88342 ** Do N steps of incremental vacuuming on a database.
88344 #ifndef SQLITE_OMIT_AUTOVACUUM
88345 if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
88346 int iLimit, addr;
88347 if( sqlite3ReadSchema(pParse) ){
88348 goto pragma_out;
88350 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
88351 iLimit = 0x7fffffff;
88353 sqlite3BeginWriteOperation(pParse, 0, iDb);
88354 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
88355 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
88356 sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
88357 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
88358 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
88359 sqlite3VdbeJumpHere(v, addr);
88360 }else
88361 #endif
88363 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88365 ** PRAGMA [database.]cache_size
88366 ** PRAGMA [database.]cache_size=N
88368 ** The first form reports the current local setting for the
88369 ** page cache size. The local setting can be different from
88370 ** the persistent cache size value that is stored in the database
88371 ** file itself. The value returned is the maximum number of
88372 ** pages in the page cache. The second form sets the local
88373 ** page cache size value. It does not change the persistent
88374 ** cache size stored on the disk so the cache size will revert
88375 ** to its default value when the database is closed and reopened.
88376 ** N should be a positive integer.
88378 if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
88379 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88380 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88381 if( !zRight ){
88382 returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
88383 }else{
88384 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
88385 pDb->pSchema->cache_size = size;
88386 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
88388 }else
88391 ** PRAGMA temp_store
88392 ** PRAGMA temp_store = "default"|"memory"|"file"
88394 ** Return or set the local value of the temp_store flag. Changing
88395 ** the local value does not make changes to the disk file and the default
88396 ** value will be restored the next time the database is opened.
88398 ** Note that it is possible for the library compile-time options to
88399 ** override this setting
88401 if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
88402 if( !zRight ){
88403 returnSingleInt(pParse, "temp_store", db->temp_store);
88404 }else{
88405 changeTempStorage(pParse, zRight);
88407 }else
88410 ** PRAGMA temp_store_directory
88411 ** PRAGMA temp_store_directory = ""|"directory_name"
88413 ** Return or set the local value of the temp_store_directory flag. Changing
88414 ** the value sets a specific directory to be used for temporary files.
88415 ** Setting to a null string reverts to the default temporary directory search.
88416 ** If temporary directory is changed, then invalidateTempStorage.
88419 if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
88420 if( !zRight ){
88421 if( sqlite3_temp_directory ){
88422 sqlite3VdbeSetNumCols(v, 1);
88423 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
88424 "temp_store_directory", SQLITE_STATIC);
88425 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
88426 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88428 }else{
88429 #ifndef SQLITE_OMIT_WSD
88430 if( zRight[0] ){
88431 int rc;
88432 int res;
88433 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
88434 if( rc!=SQLITE_OK || res==0 ){
88435 sqlite3ErrorMsg(pParse, "not a writable directory");
88436 goto pragma_out;
88439 if( SQLITE_TEMP_STORE==0
88440 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
88441 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
88443 invalidateTempStorage(pParse);
88445 sqlite3_free(sqlite3_temp_directory);
88446 if( zRight[0] ){
88447 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
88448 }else{
88449 sqlite3_temp_directory = 0;
88451 #endif /* SQLITE_OMIT_WSD */
88453 }else
88455 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
88456 # if defined(__APPLE__)
88457 # define SQLITE_ENABLE_LOCKING_STYLE 1
88458 # else
88459 # define SQLITE_ENABLE_LOCKING_STYLE 0
88460 # endif
88461 #endif
88462 #if SQLITE_ENABLE_LOCKING_STYLE
88464 ** PRAGMA [database.]lock_proxy_file
88465 ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
88467 ** Return or set the value of the lock_proxy_file flag. Changing
88468 ** the value sets a specific file to be used for database access locks.
88471 if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
88472 if( !zRight ){
88473 Pager *pPager = sqlite3BtreePager(pDb->pBt);
88474 char *proxy_file_path = NULL;
88475 sqlite3_file *pFile = sqlite3PagerFile(pPager);
88476 sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
88477 &proxy_file_path);
88479 if( proxy_file_path ){
88480 sqlite3VdbeSetNumCols(v, 1);
88481 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
88482 "lock_proxy_file", SQLITE_STATIC);
88483 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
88484 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88486 }else{
88487 Pager *pPager = sqlite3BtreePager(pDb->pBt);
88488 sqlite3_file *pFile = sqlite3PagerFile(pPager);
88489 int res;
88490 if( zRight[0] ){
88491 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
88492 zRight);
88493 } else {
88494 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
88495 NULL);
88497 if( res!=SQLITE_OK ){
88498 sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
88499 goto pragma_out;
88502 }else
88503 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
88506 ** PRAGMA [database.]synchronous
88507 ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
88509 ** Return or set the local value of the synchronous flag. Changing
88510 ** the local value does not make changes to the disk file and the
88511 ** default value will be restored the next time the database is
88512 ** opened.
88514 if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
88515 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88516 if( !zRight ){
88517 returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
88518 }else{
88519 if( !db->autoCommit ){
88520 sqlite3ErrorMsg(pParse,
88521 "Safety level may not be changed inside a transaction");
88522 }else{
88523 pDb->safety_level = getSafetyLevel(zRight)+1;
88526 }else
88527 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
88529 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
88530 if( flagPragma(pParse, zLeft, zRight) ){
88531 /* The flagPragma() subroutine also generates any necessary code
88532 ** there is nothing more to do here */
88533 }else
88534 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
88536 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
88538 ** PRAGMA table_info(<table>)
88540 ** Return a single row for each column of the named table. The columns of
88541 ** the returned data set are:
88543 ** cid: Column id (numbered from left to right, starting at 0)
88544 ** name: Column name
88545 ** type: Column declaration type.
88546 ** notnull: True if 'NOT NULL' is part of column declaration
88547 ** dflt_value: The default value for the column, if any.
88549 if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
88550 Table *pTab;
88551 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88552 pTab = sqlite3FindTable(db, zRight, zDb);
88553 if( pTab ){
88554 int i;
88555 int nHidden = 0;
88556 Column *pCol;
88557 sqlite3VdbeSetNumCols(v, 6);
88558 pParse->nMem = 6;
88559 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
88560 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88561 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
88562 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
88563 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
88564 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
88565 sqlite3ViewGetColumnNames(pParse, pTab);
88566 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
88567 if( IsHiddenColumn(pCol) ){
88568 nHidden++;
88569 continue;
88571 sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
88572 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
88573 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88574 pCol->zType ? pCol->zType : "", 0);
88575 sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
88576 if( pCol->zDflt ){
88577 sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
88578 }else{
88579 sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
88581 sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
88582 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
88585 }else
88587 if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
88588 Index *pIdx;
88589 Table *pTab;
88590 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88591 pIdx = sqlite3FindIndex(db, zRight, zDb);
88592 if( pIdx ){
88593 int i;
88594 pTab = pIdx->pTable;
88595 sqlite3VdbeSetNumCols(v, 3);
88596 pParse->nMem = 3;
88597 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
88598 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
88599 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
88600 for(i=0; i<pIdx->nColumn; i++){
88601 int cnum = pIdx->aiColumn[i];
88602 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88603 sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
88604 assert( pTab->nCol>cnum );
88605 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
88606 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88609 }else
88611 if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
88612 Index *pIdx;
88613 Table *pTab;
88614 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88615 pTab = sqlite3FindTable(db, zRight, zDb);
88616 if( pTab ){
88617 v = sqlite3GetVdbe(pParse);
88618 pIdx = pTab->pIndex;
88619 if( pIdx ){
88620 int i = 0;
88621 sqlite3VdbeSetNumCols(v, 3);
88622 pParse->nMem = 3;
88623 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88624 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88625 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
88626 while(pIdx){
88627 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88628 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
88629 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
88630 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88631 ++i;
88632 pIdx = pIdx->pNext;
88636 }else
88638 if( sqlite3StrICmp(zLeft, "database_list")==0 ){
88639 int i;
88640 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88641 sqlite3VdbeSetNumCols(v, 3);
88642 pParse->nMem = 3;
88643 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88644 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88645 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
88646 for(i=0; i<db->nDb; i++){
88647 if( db->aDb[i].pBt==0 ) continue;
88648 assert( db->aDb[i].zName!=0 );
88649 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88650 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
88651 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88652 sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
88653 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88655 }else
88657 if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
88658 int i = 0;
88659 HashElem *p;
88660 sqlite3VdbeSetNumCols(v, 2);
88661 pParse->nMem = 2;
88662 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88663 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88664 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
88665 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
88666 sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
88667 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
88668 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
88670 }else
88671 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
88673 #ifndef SQLITE_OMIT_FOREIGN_KEY
88674 if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
88675 FKey *pFK;
88676 Table *pTab;
88677 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88678 pTab = sqlite3FindTable(db, zRight, zDb);
88679 if( pTab ){
88680 v = sqlite3GetVdbe(pParse);
88681 pFK = pTab->pFKey;
88682 if( pFK ){
88683 int i = 0;
88684 sqlite3VdbeSetNumCols(v, 8);
88685 pParse->nMem = 8;
88686 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
88687 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
88688 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
88689 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
88690 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
88691 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
88692 sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
88693 sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
88694 while(pFK){
88695 int j;
88696 for(j=0; j<pFK->nCol; j++){
88697 char *zCol = pFK->aCol[j].zCol;
88698 char *zOnDelete = (char *)actionName(pFK->aAction[0]);
88699 char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
88700 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88701 sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
88702 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
88703 sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
88704 pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
88705 sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
88706 sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
88707 sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
88708 sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
88709 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
88711 ++i;
88712 pFK = pFK->pNextFrom;
88716 }else
88717 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
88719 #ifndef NDEBUG
88720 if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
88721 if( zRight ){
88722 if( getBoolean(zRight) ){
88723 sqlite3ParserTrace(stderr, "parser: ");
88724 }else{
88725 sqlite3ParserTrace(0, 0);
88728 }else
88729 #endif
88731 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
88732 ** used will be case sensitive or not depending on the RHS.
88734 if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
88735 if( zRight ){
88736 sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
88738 }else
88740 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
88741 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
88742 #endif
88744 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
88745 /* Pragma "quick_check" is an experimental reduced version of
88746 ** integrity_check designed to detect most database corruption
88747 ** without most of the overhead of a full integrity-check.
88749 if( sqlite3StrICmp(zLeft, "integrity_check")==0
88750 || sqlite3StrICmp(zLeft, "quick_check")==0
88752 int i, j, addr, mxErr;
88754 /* Code that appears at the end of the integrity check. If no error
88755 ** messages have been generated, output OK. Otherwise output the
88756 ** error message
88758 static const VdbeOpList endCode[] = {
88759 { OP_AddImm, 1, 0, 0}, /* 0 */
88760 { OP_IfNeg, 1, 0, 0}, /* 1 */
88761 { OP_String8, 0, 3, 0}, /* 2 */
88762 { OP_ResultRow, 3, 1, 0},
88765 int isQuick = (zLeft[0]=='q');
88767 /* Initialize the VDBE program */
88768 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88769 pParse->nMem = 6;
88770 sqlite3VdbeSetNumCols(v, 1);
88771 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
88773 /* Set the maximum error count */
88774 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
88775 if( zRight ){
88776 sqlite3GetInt32(zRight, &mxErr);
88777 if( mxErr<=0 ){
88778 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
88781 sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
88783 /* Do an integrity check on each database file */
88784 for(i=0; i<db->nDb; i++){
88785 HashElem *x;
88786 Hash *pTbls;
88787 int cnt = 0;
88789 if( OMIT_TEMPDB && i==1 ) continue;
88791 sqlite3CodeVerifySchema(pParse, i);
88792 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
88793 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88794 sqlite3VdbeJumpHere(v, addr);
88796 /* Do an integrity check of the B-Tree
88798 ** Begin by filling registers 2, 3, ... with the root pages numbers
88799 ** for all tables and indices in the database.
88801 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88802 pTbls = &db->aDb[i].pSchema->tblHash;
88803 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
88804 Table *pTab = sqliteHashData(x);
88805 Index *pIdx;
88806 sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
88807 cnt++;
88808 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
88809 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
88810 cnt++;
88814 /* Make sure sufficient number of registers have been allocated */
88815 if( pParse->nMem < cnt+4 ){
88816 pParse->nMem = cnt+4;
88819 /* Do the b-tree integrity checks */
88820 sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
88821 sqlite3VdbeChangeP5(v, (u8)i);
88822 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
88823 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88824 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
88825 P4_DYNAMIC);
88826 sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
88827 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
88828 sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
88829 sqlite3VdbeJumpHere(v, addr);
88831 /* Make sure all the indices are constructed correctly.
88833 for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
88834 Table *pTab = sqliteHashData(x);
88835 Index *pIdx;
88836 int loopTop;
88838 if( pTab->pIndex==0 ) continue;
88839 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
88840 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88841 sqlite3VdbeJumpHere(v, addr);
88842 sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
88843 sqlite3VdbeAddOp2(v, OP_Integer, 0, 2); /* reg(2) will count entries */
88844 loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
88845 sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1); /* increment entry count */
88846 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
88847 int jmp2;
88848 int r1;
88849 static const VdbeOpList idxErr[] = {
88850 { OP_AddImm, 1, -1, 0},
88851 { OP_String8, 0, 3, 0}, /* 1 */
88852 { OP_Rowid, 1, 4, 0},
88853 { OP_String8, 0, 5, 0}, /* 3 */
88854 { OP_String8, 0, 6, 0}, /* 4 */
88855 { OP_Concat, 4, 3, 3},
88856 { OP_Concat, 5, 3, 3},
88857 { OP_Concat, 6, 3, 3},
88858 { OP_ResultRow, 3, 1, 0},
88859 { OP_IfPos, 1, 0, 0}, /* 9 */
88860 { OP_Halt, 0, 0, 0},
88862 r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
88863 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
88864 addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
88865 sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
88866 sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
88867 sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
88868 sqlite3VdbeJumpHere(v, addr+9);
88869 sqlite3VdbeJumpHere(v, jmp2);
88871 sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
88872 sqlite3VdbeJumpHere(v, loopTop);
88873 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
88874 static const VdbeOpList cntIdx[] = {
88875 { OP_Integer, 0, 3, 0},
88876 { OP_Rewind, 0, 0, 0}, /* 1 */
88877 { OP_AddImm, 3, 1, 0},
88878 { OP_Next, 0, 0, 0}, /* 3 */
88879 { OP_Eq, 2, 0, 3}, /* 4 */
88880 { OP_AddImm, 1, -1, 0},
88881 { OP_String8, 0, 2, 0}, /* 6 */
88882 { OP_String8, 0, 3, 0}, /* 7 */
88883 { OP_Concat, 3, 2, 2},
88884 { OP_ResultRow, 2, 1, 0},
88886 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
88887 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88888 sqlite3VdbeJumpHere(v, addr);
88889 addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
88890 sqlite3VdbeChangeP1(v, addr+1, j+2);
88891 sqlite3VdbeChangeP2(v, addr+1, addr+4);
88892 sqlite3VdbeChangeP1(v, addr+3, j+2);
88893 sqlite3VdbeChangeP2(v, addr+3, addr+2);
88894 sqlite3VdbeJumpHere(v, addr+4);
88895 sqlite3VdbeChangeP4(v, addr+6,
88896 "wrong # of entries in index ", P4_STATIC);
88897 sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
88901 addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
88902 sqlite3VdbeChangeP2(v, addr, -mxErr);
88903 sqlite3VdbeJumpHere(v, addr+1);
88904 sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
88905 }else
88906 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
88908 #ifndef SQLITE_OMIT_UTF16
88910 ** PRAGMA encoding
88911 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
88913 ** In its first form, this pragma returns the encoding of the main
88914 ** database. If the database is not initialized, it is initialized now.
88916 ** The second form of this pragma is a no-op if the main database file
88917 ** has not already been initialized. In this case it sets the default
88918 ** encoding that will be used for the main database file if a new file
88919 ** is created. If an existing main database file is opened, then the
88920 ** default text encoding for the existing database is used.
88922 ** In all cases new databases created using the ATTACH command are
88923 ** created to use the same default text encoding as the main database. If
88924 ** the main database has not been initialized and/or created when ATTACH
88925 ** is executed, this is done before the ATTACH operation.
88927 ** In the second form this pragma sets the text encoding to be used in
88928 ** new database files created using this database handle. It is only
88929 ** useful if invoked immediately after the main database i
88931 if( sqlite3StrICmp(zLeft, "encoding")==0 ){
88932 static const struct EncName {
88933 char *zName;
88934 u8 enc;
88935 } encnames[] = {
88936 { "UTF8", SQLITE_UTF8 },
88937 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
88938 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
88939 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
88940 { "UTF16le", SQLITE_UTF16LE },
88941 { "UTF16be", SQLITE_UTF16BE },
88942 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
88943 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
88944 { 0, 0 }
88946 const struct EncName *pEnc;
88947 if( !zRight ){ /* "PRAGMA encoding" */
88948 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88949 sqlite3VdbeSetNumCols(v, 1);
88950 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
88951 sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
88952 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
88953 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
88954 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
88955 sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
88956 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88957 }else{ /* "PRAGMA encoding = XXX" */
88958 /* Only change the value of sqlite.enc if the database handle is not
88959 ** initialized. If the main database exists, the new sqlite.enc value
88960 ** will be overwritten when the schema is next loaded. If it does not
88961 ** already exists, it will be created to use the new encoding value.
88963 if(
88964 !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
88965 DbHasProperty(db, 0, DB_Empty)
88967 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
88968 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
88969 ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
88970 break;
88973 if( !pEnc->zName ){
88974 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
88978 }else
88979 #endif /* SQLITE_OMIT_UTF16 */
88981 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
88983 ** PRAGMA [database.]schema_version
88984 ** PRAGMA [database.]schema_version = <integer>
88986 ** PRAGMA [database.]user_version
88987 ** PRAGMA [database.]user_version = <integer>
88989 ** The pragma's schema_version and user_version are used to set or get
88990 ** the value of the schema-version and user-version, respectively. Both
88991 ** the schema-version and the user-version are 32-bit signed integers
88992 ** stored in the database header.
88994 ** The schema-cookie is usually only manipulated internally by SQLite. It
88995 ** is incremented by SQLite whenever the database schema is modified (by
88996 ** creating or dropping a table or index). The schema version is used by
88997 ** SQLite each time a query is executed to ensure that the internal cache
88998 ** of the schema used when compiling the SQL query matches the schema of
88999 ** the database against which the compiled query is actually executed.
89000 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
89001 ** the schema-version is potentially dangerous and may lead to program
89002 ** crashes or database corruption. Use with caution!
89004 ** The user-version is not used internally by SQLite. It may be used by
89005 ** applications for any purpose.
89007 if( sqlite3StrICmp(zLeft, "schema_version")==0
89008 || sqlite3StrICmp(zLeft, "user_version")==0
89009 || sqlite3StrICmp(zLeft, "freelist_count")==0
89011 int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
89012 sqlite3VdbeUsesBtree(v, iDb);
89013 switch( zLeft[0] ){
89014 case 'f': case 'F':
89015 iCookie = BTREE_FREE_PAGE_COUNT;
89016 break;
89017 case 's': case 'S':
89018 iCookie = BTREE_SCHEMA_VERSION;
89019 break;
89020 default:
89021 iCookie = BTREE_USER_VERSION;
89022 break;
89025 if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
89026 /* Write the specified cookie value */
89027 static const VdbeOpList setCookie[] = {
89028 { OP_Transaction, 0, 1, 0}, /* 0 */
89029 { OP_Integer, 0, 1, 0}, /* 1 */
89030 { OP_SetCookie, 0, 0, 1}, /* 2 */
89032 int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
89033 sqlite3VdbeChangeP1(v, addr, iDb);
89034 sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
89035 sqlite3VdbeChangeP1(v, addr+2, iDb);
89036 sqlite3VdbeChangeP2(v, addr+2, iCookie);
89037 }else{
89038 /* Read the specified cookie value */
89039 static const VdbeOpList readCookie[] = {
89040 { OP_Transaction, 0, 0, 0}, /* 0 */
89041 { OP_ReadCookie, 0, 1, 0}, /* 1 */
89042 { OP_ResultRow, 1, 1, 0}
89044 int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
89045 sqlite3VdbeChangeP1(v, addr, iDb);
89046 sqlite3VdbeChangeP1(v, addr+1, iDb);
89047 sqlite3VdbeChangeP3(v, addr+1, iCookie);
89048 sqlite3VdbeSetNumCols(v, 1);
89049 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
89051 }else
89052 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
89054 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
89056 ** PRAGMA compile_options
89058 ** Return the names of all compile-time options used in this build,
89059 ** one option per row.
89061 if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
89062 int i = 0;
89063 const char *zOpt;
89064 sqlite3VdbeSetNumCols(v, 1);
89065 pParse->nMem = 1;
89066 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
89067 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
89068 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
89069 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
89071 }else
89072 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
89074 #ifndef SQLITE_OMIT_WAL
89076 ** PRAGMA [database.]wal_checkpoint = passive|full|restart
89078 ** Checkpoint the database.
89080 if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
89081 int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
89082 int eMode = SQLITE_CHECKPOINT_PASSIVE;
89083 if( zRight ){
89084 if( sqlite3StrICmp(zRight, "full")==0 ){
89085 eMode = SQLITE_CHECKPOINT_FULL;
89086 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
89087 eMode = SQLITE_CHECKPOINT_RESTART;
89090 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
89091 sqlite3VdbeSetNumCols(v, 3);
89092 pParse->nMem = 3;
89093 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
89094 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
89095 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
89097 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
89098 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
89099 }else
89102 ** PRAGMA wal_autocheckpoint
89103 ** PRAGMA wal_autocheckpoint = N
89105 ** Configure a database connection to automatically checkpoint a database
89106 ** after accumulating N frames in the log. Or query for the current value
89107 ** of N.
89109 if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
89110 if( zRight ){
89111 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
89113 returnSingleInt(pParse, "wal_autocheckpoint",
89114 db->xWalCallback==sqlite3WalDefaultHook ?
89115 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
89116 }else
89117 #endif
89119 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
89121 ** Report the current state of file logs for all databases
89123 if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
89124 static const char *const azLockName[] = {
89125 "unlocked", "shared", "reserved", "pending", "exclusive"
89127 int i;
89128 sqlite3VdbeSetNumCols(v, 2);
89129 pParse->nMem = 2;
89130 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
89131 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
89132 for(i=0; i<db->nDb; i++){
89133 Btree *pBt;
89134 Pager *pPager;
89135 const char *zState = "unknown";
89136 int j;
89137 if( db->aDb[i].zName==0 ) continue;
89138 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
89139 pBt = db->aDb[i].pBt;
89140 if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
89141 zState = "closed";
89142 }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
89143 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
89144 zState = azLockName[j];
89146 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
89147 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
89150 }else
89151 #endif
89153 #ifdef SQLITE_HAS_CODEC
89154 if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
89155 sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
89156 }else
89157 if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
89158 sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
89159 }else
89160 if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
89161 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
89162 int i, h1, h2;
89163 char zKey[40];
89164 for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
89165 h1 += 9*(1&(h1>>6));
89166 h2 += 9*(1&(h2>>6));
89167 zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
89169 if( (zLeft[3] & 0xf)==0xb ){
89170 sqlite3_key(db, zKey, i/2);
89171 }else{
89172 sqlite3_rekey(db, zKey, i/2);
89174 }else
89175 #endif
89176 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
89177 if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
89178 #ifdef SQLITE_HAS_CODEC
89179 if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
89180 sqlite3_activate_see(&zRight[4]);
89182 #endif
89183 #ifdef SQLITE_ENABLE_CEROD
89184 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
89185 sqlite3_activate_cerod(&zRight[6]);
89187 #endif
89188 }else
89189 #endif
89192 {/* Empty ELSE clause */}
89195 ** Reset the safety level, in case the fullfsync flag or synchronous
89196 ** setting changed.
89198 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
89199 if( db->autoCommit ){
89200 sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
89201 (db->flags&SQLITE_FullFSync)!=0,
89202 (db->flags&SQLITE_CkptFullFSync)!=0);
89204 #endif
89205 pragma_out:
89206 sqlite3DbFree(db, zLeft);
89207 sqlite3DbFree(db, zRight);
89210 #endif /* SQLITE_OMIT_PRAGMA */
89212 /************** End of pragma.c **********************************************/
89213 /************** Begin file prepare.c *****************************************/
89215 ** 2005 May 25
89217 ** The author disclaims copyright to this source code. In place of
89218 ** a legal notice, here is a blessing:
89220 ** May you do good and not evil.
89221 ** May you find forgiveness for yourself and forgive others.
89222 ** May you share freely, never taking more than you give.
89224 *************************************************************************
89225 ** This file contains the implementation of the sqlite3_prepare()
89226 ** interface, and routines that contribute to loading the database schema
89227 ** from disk.
89231 ** Fill the InitData structure with an error message that indicates
89232 ** that the database is corrupt.
89234 static void corruptSchema(
89235 InitData *pData, /* Initialization context */
89236 const char *zObj, /* Object being parsed at the point of error */
89237 const char *zExtra /* Error information */
89239 sqlite3 *db = pData->db;
89240 if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
89241 if( zObj==0 ) zObj = "?";
89242 sqlite3SetString(pData->pzErrMsg, db,
89243 "malformed database schema (%s)", zObj);
89244 if( zExtra ){
89245 *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
89246 "%s - %s", *pData->pzErrMsg, zExtra);
89249 pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
89253 ** This is the callback routine for the code that initializes the
89254 ** database. See sqlite3Init() below for additional information.
89255 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
89257 ** Each callback contains the following information:
89259 ** argv[0] = name of thing being created
89260 ** argv[1] = root page number for table or index. 0 for trigger or view.
89261 ** argv[2] = SQL text for the CREATE statement.
89264 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
89265 InitData *pData = (InitData*)pInit;
89266 sqlite3 *db = pData->db;
89267 int iDb = pData->iDb;
89269 assert( argc==3 );
89270 UNUSED_PARAMETER2(NotUsed, argc);
89271 assert( sqlite3_mutex_held(db->mutex) );
89272 DbClearProperty(db, iDb, DB_Empty);
89273 if( db->mallocFailed ){
89274 corruptSchema(pData, argv[0], 0);
89275 return 1;
89278 assert( iDb>=0 && iDb<db->nDb );
89279 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
89280 if( argv[1]==0 ){
89281 corruptSchema(pData, argv[0], 0);
89282 }else if( argv[2] && argv[2][0] ){
89283 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
89284 ** But because db->init.busy is set to 1, no VDBE code is generated
89285 ** or executed. All the parser does is build the internal data
89286 ** structures that describe the table, index, or view.
89288 int rc;
89289 sqlite3_stmt *pStmt;
89290 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
89292 assert( db->init.busy );
89293 db->init.iDb = iDb;
89294 db->init.newTnum = sqlite3Atoi(argv[1]);
89295 db->init.orphanTrigger = 0;
89296 TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
89297 rc = db->errCode;
89298 assert( (rc&0xFF)==(rcp&0xFF) );
89299 db->init.iDb = 0;
89300 if( SQLITE_OK!=rc ){
89301 if( db->init.orphanTrigger ){
89302 assert( iDb==1 );
89303 }else{
89304 pData->rc = rc;
89305 if( rc==SQLITE_NOMEM ){
89306 db->mallocFailed = 1;
89307 }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
89308 corruptSchema(pData, argv[0], sqlite3_errmsg(db));
89312 sqlite3_finalize(pStmt);
89313 }else if( argv[0]==0 ){
89314 corruptSchema(pData, 0, 0);
89315 }else{
89316 /* If the SQL column is blank it means this is an index that
89317 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
89318 ** constraint for a CREATE TABLE. The index should have already
89319 ** been created when we processed the CREATE TABLE. All we have
89320 ** to do here is record the root page number for that index.
89322 Index *pIndex;
89323 pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
89324 if( pIndex==0 ){
89325 /* This can occur if there exists an index on a TEMP table which
89326 ** has the same name as another index on a permanent index. Since
89327 ** the permanent table is hidden by the TEMP table, we can also
89328 ** safely ignore the index on the permanent table.
89330 /* Do Nothing */;
89331 }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
89332 corruptSchema(pData, argv[0], "invalid rootpage");
89335 return 0;
89339 ** Attempt to read the database schema and initialize internal
89340 ** data structures for a single database file. The index of the
89341 ** database file is given by iDb. iDb==0 is used for the main
89342 ** database. iDb==1 should never be used. iDb>=2 is used for
89343 ** auxiliary databases. Return one of the SQLITE_ error codes to
89344 ** indicate success or failure.
89346 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
89347 int rc;
89348 int i;
89349 int size;
89350 Table *pTab;
89351 Db *pDb;
89352 char const *azArg[4];
89353 int meta[5];
89354 InitData initData;
89355 char const *zMasterSchema;
89356 char const *zMasterName;
89357 int openedTransaction = 0;
89360 ** The master database table has a structure like this
89362 static const char master_schema[] =
89363 "CREATE TABLE sqlite_master(\n"
89364 " type text,\n"
89365 " name text,\n"
89366 " tbl_name text,\n"
89367 " rootpage integer,\n"
89368 " sql text\n"
89371 #ifndef SQLITE_OMIT_TEMPDB
89372 static const char temp_master_schema[] =
89373 "CREATE TEMP TABLE sqlite_temp_master(\n"
89374 " type text,\n"
89375 " name text,\n"
89376 " tbl_name text,\n"
89377 " rootpage integer,\n"
89378 " sql text\n"
89381 #else
89382 #define temp_master_schema 0
89383 #endif
89385 assert( iDb>=0 && iDb<db->nDb );
89386 assert( db->aDb[iDb].pSchema );
89387 assert( sqlite3_mutex_held(db->mutex) );
89388 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
89390 /* zMasterSchema and zInitScript are set to point at the master schema
89391 ** and initialisation script appropriate for the database being
89392 ** initialised. zMasterName is the name of the master table.
89394 if( !OMIT_TEMPDB && iDb==1 ){
89395 zMasterSchema = temp_master_schema;
89396 }else{
89397 zMasterSchema = master_schema;
89399 zMasterName = SCHEMA_TABLE(iDb);
89401 /* Construct the schema tables. */
89402 azArg[0] = zMasterName;
89403 azArg[1] = "1";
89404 azArg[2] = zMasterSchema;
89405 azArg[3] = 0;
89406 initData.db = db;
89407 initData.iDb = iDb;
89408 initData.rc = SQLITE_OK;
89409 initData.pzErrMsg = pzErrMsg;
89410 sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
89411 if( initData.rc ){
89412 rc = initData.rc;
89413 goto error_out;
89415 pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
89416 if( ALWAYS(pTab) ){
89417 pTab->tabFlags |= TF_Readonly;
89420 /* Create a cursor to hold the database open
89422 pDb = &db->aDb[iDb];
89423 if( pDb->pBt==0 ){
89424 if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
89425 DbSetProperty(db, 1, DB_SchemaLoaded);
89427 return SQLITE_OK;
89430 /* If there is not already a read-only (or read-write) transaction opened
89431 ** on the b-tree database, open one now. If a transaction is opened, it
89432 ** will be closed before this function returns. */
89433 sqlite3BtreeEnter(pDb->pBt);
89434 if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
89435 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
89436 if( rc!=SQLITE_OK ){
89437 sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
89438 goto initone_error_out;
89440 openedTransaction = 1;
89443 /* Get the database meta information.
89445 ** Meta values are as follows:
89446 ** meta[0] Schema cookie. Changes with each schema change.
89447 ** meta[1] File format of schema layer.
89448 ** meta[2] Size of the page cache.
89449 ** meta[3] Largest rootpage (auto/incr_vacuum mode)
89450 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
89451 ** meta[5] User version
89452 ** meta[6] Incremental vacuum mode
89453 ** meta[7] unused
89454 ** meta[8] unused
89455 ** meta[9] unused
89457 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
89458 ** the possible values of meta[4].
89460 for(i=0; i<ArraySize(meta); i++){
89461 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
89463 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
89465 /* If opening a non-empty database, check the text encoding. For the
89466 ** main database, set sqlite3.enc to the encoding of the main database.
89467 ** For an attached db, it is an error if the encoding is not the same
89468 ** as sqlite3.enc.
89470 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
89471 if( iDb==0 ){
89472 u8 encoding;
89473 /* If opening the main database, set ENC(db). */
89474 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
89475 if( encoding==0 ) encoding = SQLITE_UTF8;
89476 ENC(db) = encoding;
89477 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
89478 }else{
89479 /* If opening an attached database, the encoding much match ENC(db) */
89480 if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
89481 sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
89482 " text encoding as main database");
89483 rc = SQLITE_ERROR;
89484 goto initone_error_out;
89487 }else{
89488 DbSetProperty(db, iDb, DB_Empty);
89490 pDb->pSchema->enc = ENC(db);
89492 if( pDb->pSchema->cache_size==0 ){
89493 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
89494 if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
89495 pDb->pSchema->cache_size = size;
89496 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
89500 ** file_format==1 Version 3.0.0.
89501 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
89502 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
89503 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
89505 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
89506 if( pDb->pSchema->file_format==0 ){
89507 pDb->pSchema->file_format = 1;
89509 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
89510 sqlite3SetString(pzErrMsg, db, "unsupported file format");
89511 rc = SQLITE_ERROR;
89512 goto initone_error_out;
89515 /* Ticket #2804: When we open a database in the newer file format,
89516 ** clear the legacy_file_format pragma flag so that a VACUUM will
89517 ** not downgrade the database and thus invalidate any descending
89518 ** indices that the user might have created.
89520 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
89521 db->flags &= ~SQLITE_LegacyFileFmt;
89524 /* Read the schema information out of the schema tables
89526 assert( db->init.busy );
89528 char *zSql;
89529 zSql = sqlite3MPrintf(db,
89530 "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
89531 db->aDb[iDb].zName, zMasterName);
89532 #ifndef SQLITE_OMIT_AUTHORIZATION
89534 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
89535 xAuth = db->xAuth;
89536 db->xAuth = 0;
89537 #endif
89538 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
89539 #ifndef SQLITE_OMIT_AUTHORIZATION
89540 db->xAuth = xAuth;
89542 #endif
89543 if( rc==SQLITE_OK ) rc = initData.rc;
89544 sqlite3DbFree(db, zSql);
89545 #ifndef SQLITE_OMIT_ANALYZE
89546 if( rc==SQLITE_OK ){
89547 sqlite3AnalysisLoad(db, iDb);
89549 #endif
89551 if( db->mallocFailed ){
89552 rc = SQLITE_NOMEM;
89553 sqlite3ResetInternalSchema(db, -1);
89555 if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
89556 /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
89557 ** the schema loaded, even if errors occurred. In this situation the
89558 ** current sqlite3_prepare() operation will fail, but the following one
89559 ** will attempt to compile the supplied statement against whatever subset
89560 ** of the schema was loaded before the error occurred. The primary
89561 ** purpose of this is to allow access to the sqlite_master table
89562 ** even when its contents have been corrupted.
89564 DbSetProperty(db, iDb, DB_SchemaLoaded);
89565 rc = SQLITE_OK;
89568 /* Jump here for an error that occurs after successfully allocating
89569 ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
89570 ** before that point, jump to error_out.
89572 initone_error_out:
89573 if( openedTransaction ){
89574 sqlite3BtreeCommit(pDb->pBt);
89576 sqlite3BtreeLeave(pDb->pBt);
89578 error_out:
89579 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89580 db->mallocFailed = 1;
89582 return rc;
89586 ** Initialize all database files - the main database file, the file
89587 ** used to store temporary tables, and any additional database files
89588 ** created using ATTACH statements. Return a success code. If an
89589 ** error occurs, write an error message into *pzErrMsg.
89591 ** After a database is initialized, the DB_SchemaLoaded bit is set
89592 ** bit is set in the flags field of the Db structure. If the database
89593 ** file was of zero-length, then the DB_Empty flag is also set.
89595 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
89596 int i, rc;
89597 int commit_internal = !(db->flags&SQLITE_InternChanges);
89599 assert( sqlite3_mutex_held(db->mutex) );
89600 rc = SQLITE_OK;
89601 db->init.busy = 1;
89602 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
89603 if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
89604 rc = sqlite3InitOne(db, i, pzErrMsg);
89605 if( rc ){
89606 sqlite3ResetInternalSchema(db, i);
89610 /* Once all the other databases have been initialised, load the schema
89611 ** for the TEMP database. This is loaded last, as the TEMP database
89612 ** schema may contain references to objects in other databases.
89614 #ifndef SQLITE_OMIT_TEMPDB
89615 if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
89616 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
89617 rc = sqlite3InitOne(db, 1, pzErrMsg);
89618 if( rc ){
89619 sqlite3ResetInternalSchema(db, 1);
89622 #endif
89624 db->init.busy = 0;
89625 if( rc==SQLITE_OK && commit_internal ){
89626 sqlite3CommitInternalChanges(db);
89629 return rc;
89633 ** This routine is a no-op if the database schema is already initialised.
89634 ** Otherwise, the schema is loaded. An error code is returned.
89636 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
89637 int rc = SQLITE_OK;
89638 sqlite3 *db = pParse->db;
89639 assert( sqlite3_mutex_held(db->mutex) );
89640 if( !db->init.busy ){
89641 rc = sqlite3Init(db, &pParse->zErrMsg);
89643 if( rc!=SQLITE_OK ){
89644 pParse->rc = rc;
89645 pParse->nErr++;
89647 return rc;
89652 ** Check schema cookies in all databases. If any cookie is out
89653 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
89654 ** make no changes to pParse->rc.
89656 static void schemaIsValid(Parse *pParse){
89657 sqlite3 *db = pParse->db;
89658 int iDb;
89659 int rc;
89660 int cookie;
89662 assert( pParse->checkSchema );
89663 assert( sqlite3_mutex_held(db->mutex) );
89664 for(iDb=0; iDb<db->nDb; iDb++){
89665 int openedTransaction = 0; /* True if a transaction is opened */
89666 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
89667 if( pBt==0 ) continue;
89669 /* If there is not already a read-only (or read-write) transaction opened
89670 ** on the b-tree database, open one now. If a transaction is opened, it
89671 ** will be closed immediately after reading the meta-value. */
89672 if( !sqlite3BtreeIsInReadTrans(pBt) ){
89673 rc = sqlite3BtreeBeginTrans(pBt, 0);
89674 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89675 db->mallocFailed = 1;
89677 if( rc!=SQLITE_OK ) return;
89678 openedTransaction = 1;
89681 /* Read the schema cookie from the database. If it does not match the
89682 ** value stored as part of the in-memory schema representation,
89683 ** set Parse.rc to SQLITE_SCHEMA. */
89684 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
89685 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89686 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
89687 sqlite3ResetInternalSchema(db, iDb);
89688 pParse->rc = SQLITE_SCHEMA;
89691 /* Close the transaction, if one was opened. */
89692 if( openedTransaction ){
89693 sqlite3BtreeCommit(pBt);
89699 ** Convert a schema pointer into the iDb index that indicates
89700 ** which database file in db->aDb[] the schema refers to.
89702 ** If the same database is attached more than once, the first
89703 ** attached database is returned.
89705 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
89706 int i = -1000000;
89708 /* If pSchema is NULL, then return -1000000. This happens when code in
89709 ** expr.c is trying to resolve a reference to a transient table (i.e. one
89710 ** created by a sub-select). In this case the return value of this
89711 ** function should never be used.
89713 ** We return -1000000 instead of the more usual -1 simply because using
89714 ** -1000000 as the incorrect index into db->aDb[] is much
89715 ** more likely to cause a segfault than -1 (of course there are assert()
89716 ** statements too, but it never hurts to play the odds).
89718 assert( sqlite3_mutex_held(db->mutex) );
89719 if( pSchema ){
89720 for(i=0; ALWAYS(i<db->nDb); i++){
89721 if( db->aDb[i].pSchema==pSchema ){
89722 break;
89725 assert( i>=0 && i<db->nDb );
89727 return i;
89731 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
89733 static int sqlite3Prepare(
89734 sqlite3 *db, /* Database handle. */
89735 const char *zSql, /* UTF-8 encoded SQL statement. */
89736 int nBytes, /* Length of zSql in bytes. */
89737 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
89738 Vdbe *pReprepare, /* VM being reprepared */
89739 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
89740 const char **pzTail /* OUT: End of parsed string */
89742 Parse *pParse; /* Parsing context */
89743 char *zErrMsg = 0; /* Error message */
89744 int rc = SQLITE_OK; /* Result code */
89745 int i; /* Loop counter */
89747 /* Allocate the parsing context */
89748 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
89749 if( pParse==0 ){
89750 rc = SQLITE_NOMEM;
89751 goto end_prepare;
89753 pParse->pReprepare = pReprepare;
89754 assert( ppStmt && *ppStmt==0 );
89755 assert( !db->mallocFailed );
89756 assert( sqlite3_mutex_held(db->mutex) );
89758 /* Check to verify that it is possible to get a read lock on all
89759 ** database schemas. The inability to get a read lock indicates that
89760 ** some other database connection is holding a write-lock, which in
89761 ** turn means that the other connection has made uncommitted changes
89762 ** to the schema.
89764 ** Were we to proceed and prepare the statement against the uncommitted
89765 ** schema changes and if those schema changes are subsequently rolled
89766 ** back and different changes are made in their place, then when this
89767 ** prepared statement goes to run the schema cookie would fail to detect
89768 ** the schema change. Disaster would follow.
89770 ** This thread is currently holding mutexes on all Btrees (because
89771 ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
89772 ** is not possible for another thread to start a new schema change
89773 ** while this routine is running. Hence, we do not need to hold
89774 ** locks on the schema, we just need to make sure nobody else is
89775 ** holding them.
89777 ** Note that setting READ_UNCOMMITTED overrides most lock detection,
89778 ** but it does *not* override schema lock detection, so this all still
89779 ** works even if READ_UNCOMMITTED is set.
89781 for(i=0; i<db->nDb; i++) {
89782 Btree *pBt = db->aDb[i].pBt;
89783 if( pBt ){
89784 assert( sqlite3BtreeHoldsMutex(pBt) );
89785 rc = sqlite3BtreeSchemaLocked(pBt);
89786 if( rc ){
89787 const char *zDb = db->aDb[i].zName;
89788 sqlite3Error(db, rc, "database schema is locked: %s", zDb);
89789 testcase( db->flags & SQLITE_ReadUncommitted );
89790 goto end_prepare;
89795 sqlite3VtabUnlockList(db);
89797 pParse->db = db;
89798 pParse->nQueryLoop = (double)1;
89799 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
89800 char *zSqlCopy;
89801 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
89802 testcase( nBytes==mxLen );
89803 testcase( nBytes==mxLen+1 );
89804 if( nBytes>mxLen ){
89805 sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
89806 rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
89807 goto end_prepare;
89809 zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
89810 if( zSqlCopy ){
89811 sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
89812 sqlite3DbFree(db, zSqlCopy);
89813 pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
89814 }else{
89815 pParse->zTail = &zSql[nBytes];
89817 }else{
89818 sqlite3RunParser(pParse, zSql, &zErrMsg);
89820 assert( 1==(int)pParse->nQueryLoop );
89822 if( db->mallocFailed ){
89823 pParse->rc = SQLITE_NOMEM;
89825 if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
89826 if( pParse->checkSchema ){
89827 schemaIsValid(pParse);
89829 if( db->mallocFailed ){
89830 pParse->rc = SQLITE_NOMEM;
89832 if( pzTail ){
89833 *pzTail = pParse->zTail;
89835 rc = pParse->rc;
89837 #ifndef SQLITE_OMIT_EXPLAIN
89838 if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
89839 static const char * const azColName[] = {
89840 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
89841 "selectid", "order", "from", "detail"
89843 int iFirst, mx;
89844 if( pParse->explain==2 ){
89845 sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
89846 iFirst = 8;
89847 mx = 12;
89848 }else{
89849 sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
89850 iFirst = 0;
89851 mx = 8;
89853 for(i=iFirst; i<mx; i++){
89854 sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
89855 azColName[i], SQLITE_STATIC);
89858 #endif
89860 assert( db->init.busy==0 || saveSqlFlag==0 );
89861 if( db->init.busy==0 ){
89862 Vdbe *pVdbe = pParse->pVdbe;
89863 sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
89865 if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
89866 sqlite3VdbeFinalize(pParse->pVdbe);
89867 assert(!(*ppStmt));
89868 }else{
89869 *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
89872 if( zErrMsg ){
89873 sqlite3Error(db, rc, "%s", zErrMsg);
89874 sqlite3DbFree(db, zErrMsg);
89875 }else{
89876 sqlite3Error(db, rc, 0);
89879 /* Delete any TriggerPrg structures allocated while parsing this statement. */
89880 while( pParse->pTriggerPrg ){
89881 TriggerPrg *pT = pParse->pTriggerPrg;
89882 pParse->pTriggerPrg = pT->pNext;
89883 sqlite3DbFree(db, pT);
89886 end_prepare:
89888 sqlite3StackFree(db, pParse);
89889 rc = sqlite3ApiExit(db, rc);
89890 assert( (rc&db->errMask)==rc );
89891 return rc;
89893 static int sqlite3LockAndPrepare(
89894 sqlite3 *db, /* Database handle. */
89895 const char *zSql, /* UTF-8 encoded SQL statement. */
89896 int nBytes, /* Length of zSql in bytes. */
89897 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
89898 Vdbe *pOld, /* VM being reprepared */
89899 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
89900 const char **pzTail /* OUT: End of parsed string */
89902 int rc;
89903 assert( ppStmt!=0 );
89904 *ppStmt = 0;
89905 if( !sqlite3SafetyCheckOk(db) ){
89906 return SQLITE_MISUSE_BKPT;
89908 sqlite3_mutex_enter(db->mutex);
89909 sqlite3BtreeEnterAll(db);
89910 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
89911 if( rc==SQLITE_SCHEMA ){
89912 sqlite3_finalize(*ppStmt);
89913 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
89915 sqlite3BtreeLeaveAll(db);
89916 sqlite3_mutex_leave(db->mutex);
89917 return rc;
89921 ** Rerun the compilation of a statement after a schema change.
89923 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
89924 ** if the statement cannot be recompiled because another connection has
89925 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
89926 ** occurs, return SQLITE_SCHEMA.
89928 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
89929 int rc;
89930 sqlite3_stmt *pNew;
89931 const char *zSql;
89932 sqlite3 *db;
89934 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
89935 zSql = sqlite3_sql((sqlite3_stmt *)p);
89936 assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
89937 db = sqlite3VdbeDb(p);
89938 assert( sqlite3_mutex_held(db->mutex) );
89939 rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
89940 if( rc ){
89941 if( rc==SQLITE_NOMEM ){
89942 db->mallocFailed = 1;
89944 assert( pNew==0 );
89945 return rc;
89946 }else{
89947 assert( pNew!=0 );
89949 sqlite3VdbeSwap((Vdbe*)pNew, p);
89950 sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
89951 sqlite3VdbeResetStepResult((Vdbe*)pNew);
89952 sqlite3VdbeFinalize((Vdbe*)pNew);
89953 return SQLITE_OK;
89958 ** Two versions of the official API. Legacy and new use. In the legacy
89959 ** version, the original SQL text is not saved in the prepared statement
89960 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
89961 ** sqlite3_step(). In the new version, the original SQL text is retained
89962 ** and the statement is automatically recompiled if an schema change
89963 ** occurs.
89965 SQLITE_API int sqlite3_prepare(
89966 sqlite3 *db, /* Database handle. */
89967 const char *zSql, /* UTF-8 encoded SQL statement. */
89968 int nBytes, /* Length of zSql in bytes. */
89969 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
89970 const char **pzTail /* OUT: End of parsed string */
89972 int rc;
89973 rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
89974 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
89975 return rc;
89977 SQLITE_API int sqlite3_prepare_v2(
89978 sqlite3 *db, /* Database handle. */
89979 const char *zSql, /* UTF-8 encoded SQL statement. */
89980 int nBytes, /* Length of zSql in bytes. */
89981 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
89982 const char **pzTail /* OUT: End of parsed string */
89984 int rc;
89985 rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
89986 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
89987 return rc;
89991 #ifndef SQLITE_OMIT_UTF16
89993 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
89995 static int sqlite3Prepare16(
89996 sqlite3 *db, /* Database handle. */
89997 const void *zSql, /* UTF-16 encoded SQL statement. */
89998 int nBytes, /* Length of zSql in bytes. */
89999 int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
90000 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
90001 const void **pzTail /* OUT: End of parsed string */
90003 /* This function currently works by first transforming the UTF-16
90004 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
90005 ** tricky bit is figuring out the pointer to return in *pzTail.
90007 char *zSql8;
90008 const char *zTail8 = 0;
90009 int rc = SQLITE_OK;
90011 assert( ppStmt );
90012 *ppStmt = 0;
90013 if( !sqlite3SafetyCheckOk(db) ){
90014 return SQLITE_MISUSE_BKPT;
90016 sqlite3_mutex_enter(db->mutex);
90017 zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
90018 if( zSql8 ){
90019 rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
90022 if( zTail8 && pzTail ){
90023 /* If sqlite3_prepare returns a tail pointer, we calculate the
90024 ** equivalent pointer into the UTF-16 string by counting the unicode
90025 ** characters between zSql8 and zTail8, and then returning a pointer
90026 ** the same number of characters into the UTF-16 string.
90028 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
90029 *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
90031 sqlite3DbFree(db, zSql8);
90032 rc = sqlite3ApiExit(db, rc);
90033 sqlite3_mutex_leave(db->mutex);
90034 return rc;
90038 ** Two versions of the official API. Legacy and new use. In the legacy
90039 ** version, the original SQL text is not saved in the prepared statement
90040 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
90041 ** sqlite3_step(). In the new version, the original SQL text is retained
90042 ** and the statement is automatically recompiled if an schema change
90043 ** occurs.
90045 SQLITE_API int sqlite3_prepare16(
90046 sqlite3 *db, /* Database handle. */
90047 const void *zSql, /* UTF-16 encoded SQL statement. */
90048 int nBytes, /* Length of zSql in bytes. */
90049 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
90050 const void **pzTail /* OUT: End of parsed string */
90052 int rc;
90053 rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
90054 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
90055 return rc;
90057 SQLITE_API int sqlite3_prepare16_v2(
90058 sqlite3 *db, /* Database handle. */
90059 const void *zSql, /* UTF-16 encoded SQL statement. */
90060 int nBytes, /* Length of zSql in bytes. */
90061 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
90062 const void **pzTail /* OUT: End of parsed string */
90064 int rc;
90065 rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
90066 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
90067 return rc;
90070 #endif /* SQLITE_OMIT_UTF16 */
90072 /************** End of prepare.c *********************************************/
90073 /************** Begin file select.c ******************************************/
90075 ** 2001 September 15
90077 ** The author disclaims copyright to this source code. In place of
90078 ** a legal notice, here is a blessing:
90080 ** May you do good and not evil.
90081 ** May you find forgiveness for yourself and forgive others.
90082 ** May you share freely, never taking more than you give.
90084 *************************************************************************
90085 ** This file contains C code routines that are called by the parser
90086 ** to handle SELECT statements in SQLite.
90091 ** Delete all the content of a Select structure but do not deallocate
90092 ** the select structure itself.
90094 static void clearSelect(sqlite3 *db, Select *p){
90095 sqlite3ExprListDelete(db, p->pEList);
90096 sqlite3SrcListDelete(db, p->pSrc);
90097 sqlite3ExprDelete(db, p->pWhere);
90098 sqlite3ExprListDelete(db, p->pGroupBy);
90099 sqlite3ExprDelete(db, p->pHaving);
90100 sqlite3ExprListDelete(db, p->pOrderBy);
90101 sqlite3SelectDelete(db, p->pPrior);
90102 sqlite3ExprDelete(db, p->pLimit);
90103 sqlite3ExprDelete(db, p->pOffset);
90107 ** Initialize a SelectDest structure.
90109 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
90110 pDest->eDest = (u8)eDest;
90111 pDest->iParm = iParm;
90112 pDest->affinity = 0;
90113 pDest->iMem = 0;
90114 pDest->nMem = 0;
90119 ** Allocate a new Select structure and return a pointer to that
90120 ** structure.
90122 SQLITE_PRIVATE Select *sqlite3SelectNew(
90123 Parse *pParse, /* Parsing context */
90124 ExprList *pEList, /* which columns to include in the result */
90125 SrcList *pSrc, /* the FROM clause -- which tables to scan */
90126 Expr *pWhere, /* the WHERE clause */
90127 ExprList *pGroupBy, /* the GROUP BY clause */
90128 Expr *pHaving, /* the HAVING clause */
90129 ExprList *pOrderBy, /* the ORDER BY clause */
90130 int isDistinct, /* true if the DISTINCT keyword is present */
90131 Expr *pLimit, /* LIMIT value. NULL means not used */
90132 Expr *pOffset /* OFFSET value. NULL means no offset */
90134 Select *pNew;
90135 Select standin;
90136 sqlite3 *db = pParse->db;
90137 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
90138 assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
90139 if( pNew==0 ){
90140 pNew = &standin;
90141 memset(pNew, 0, sizeof(*pNew));
90143 if( pEList==0 ){
90144 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
90146 pNew->pEList = pEList;
90147 pNew->pSrc = pSrc;
90148 pNew->pWhere = pWhere;
90149 pNew->pGroupBy = pGroupBy;
90150 pNew->pHaving = pHaving;
90151 pNew->pOrderBy = pOrderBy;
90152 pNew->selFlags = isDistinct ? SF_Distinct : 0;
90153 pNew->op = TK_SELECT;
90154 pNew->pLimit = pLimit;
90155 pNew->pOffset = pOffset;
90156 assert( pOffset==0 || pLimit!=0 );
90157 pNew->addrOpenEphm[0] = -1;
90158 pNew->addrOpenEphm[1] = -1;
90159 pNew->addrOpenEphm[2] = -1;
90160 if( db->mallocFailed ) {
90161 clearSelect(db, pNew);
90162 if( pNew!=&standin ) sqlite3DbFree(db, pNew);
90163 pNew = 0;
90165 return pNew;
90169 ** Delete the given Select structure and all of its substructures.
90171 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
90172 if( p ){
90173 clearSelect(db, p);
90174 sqlite3DbFree(db, p);
90179 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
90180 ** type of join. Return an integer constant that expresses that type
90181 ** in terms of the following bit values:
90183 ** JT_INNER
90184 ** JT_CROSS
90185 ** JT_OUTER
90186 ** JT_NATURAL
90187 ** JT_LEFT
90188 ** JT_RIGHT
90190 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
90192 ** If an illegal or unsupported join type is seen, then still return
90193 ** a join type, but put an error in the pParse structure.
90195 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
90196 int jointype = 0;
90197 Token *apAll[3];
90198 Token *p;
90199 /* 0123456789 123456789 123456789 123 */
90200 static const char zKeyText[] = "naturaleftouterightfullinnercross";
90201 static const struct {
90202 u8 i; /* Beginning of keyword text in zKeyText[] */
90203 u8 nChar; /* Length of the keyword in characters */
90204 u8 code; /* Join type mask */
90205 } aKeyword[] = {
90206 /* natural */ { 0, 7, JT_NATURAL },
90207 /* left */ { 6, 4, JT_LEFT|JT_OUTER },
90208 /* outer */ { 10, 5, JT_OUTER },
90209 /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
90210 /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
90211 /* inner */ { 23, 5, JT_INNER },
90212 /* cross */ { 28, 5, JT_INNER|JT_CROSS },
90214 int i, j;
90215 apAll[0] = pA;
90216 apAll[1] = pB;
90217 apAll[2] = pC;
90218 for(i=0; i<3 && apAll[i]; i++){
90219 p = apAll[i];
90220 for(j=0; j<ArraySize(aKeyword); j++){
90221 if( p->n==aKeyword[j].nChar
90222 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
90223 jointype |= aKeyword[j].code;
90224 break;
90227 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
90228 if( j>=ArraySize(aKeyword) ){
90229 jointype |= JT_ERROR;
90230 break;
90234 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
90235 (jointype & JT_ERROR)!=0
90237 const char *zSp = " ";
90238 assert( pB!=0 );
90239 if( pC==0 ){ zSp++; }
90240 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
90241 "%T %T%s%T", pA, pB, zSp, pC);
90242 jointype = JT_INNER;
90243 }else if( (jointype & JT_OUTER)!=0
90244 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
90245 sqlite3ErrorMsg(pParse,
90246 "RIGHT and FULL OUTER JOINs are not currently supported");
90247 jointype = JT_INNER;
90249 return jointype;
90253 ** Return the index of a column in a table. Return -1 if the column
90254 ** is not contained in the table.
90256 static int columnIndex(Table *pTab, const char *zCol){
90257 int i;
90258 for(i=0; i<pTab->nCol; i++){
90259 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
90261 return -1;
90265 ** Search the first N tables in pSrc, from left to right, looking for a
90266 ** table that has a column named zCol.
90268 ** When found, set *piTab and *piCol to the table index and column index
90269 ** of the matching column and return TRUE.
90271 ** If not found, return FALSE.
90273 static int tableAndColumnIndex(
90274 SrcList *pSrc, /* Array of tables to search */
90275 int N, /* Number of tables in pSrc->a[] to search */
90276 const char *zCol, /* Name of the column we are looking for */
90277 int *piTab, /* Write index of pSrc->a[] here */
90278 int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
90280 int i; /* For looping over tables in pSrc */
90281 int iCol; /* Index of column matching zCol */
90283 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
90284 for(i=0; i<N; i++){
90285 iCol = columnIndex(pSrc->a[i].pTab, zCol);
90286 if( iCol>=0 ){
90287 if( piTab ){
90288 *piTab = i;
90289 *piCol = iCol;
90291 return 1;
90294 return 0;
90298 ** This function is used to add terms implied by JOIN syntax to the
90299 ** WHERE clause expression of a SELECT statement. The new term, which
90300 ** is ANDed with the existing WHERE clause, is of the form:
90302 ** (tab1.col1 = tab2.col2)
90304 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
90305 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
90306 ** column iColRight of tab2.
90308 static void addWhereTerm(
90309 Parse *pParse, /* Parsing context */
90310 SrcList *pSrc, /* List of tables in FROM clause */
90311 int iLeft, /* Index of first table to join in pSrc */
90312 int iColLeft, /* Index of column in first table */
90313 int iRight, /* Index of second table in pSrc */
90314 int iColRight, /* Index of column in second table */
90315 int isOuterJoin, /* True if this is an OUTER join */
90316 Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
90318 sqlite3 *db = pParse->db;
90319 Expr *pE1;
90320 Expr *pE2;
90321 Expr *pEq;
90323 assert( iLeft<iRight );
90324 assert( pSrc->nSrc>iRight );
90325 assert( pSrc->a[iLeft].pTab );
90326 assert( pSrc->a[iRight].pTab );
90328 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
90329 pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
90331 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
90332 if( pEq && isOuterJoin ){
90333 ExprSetProperty(pEq, EP_FromJoin);
90334 assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
90335 ExprSetIrreducible(pEq);
90336 pEq->iRightJoinTable = (i16)pE2->iTable;
90338 *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
90342 ** Set the EP_FromJoin property on all terms of the given expression.
90343 ** And set the Expr.iRightJoinTable to iTable for every term in the
90344 ** expression.
90346 ** The EP_FromJoin property is used on terms of an expression to tell
90347 ** the LEFT OUTER JOIN processing logic that this term is part of the
90348 ** join restriction specified in the ON or USING clause and not a part
90349 ** of the more general WHERE clause. These terms are moved over to the
90350 ** WHERE clause during join processing but we need to remember that they
90351 ** originated in the ON or USING clause.
90353 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
90354 ** expression depends on table iRightJoinTable even if that table is not
90355 ** explicitly mentioned in the expression. That information is needed
90356 ** for cases like this:
90358 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
90360 ** The where clause needs to defer the handling of the t1.x=5
90361 ** term until after the t2 loop of the join. In that way, a
90362 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
90363 ** defer the handling of t1.x=5, it will be processed immediately
90364 ** after the t1 loop and rows with t1.x!=5 will never appear in
90365 ** the output, which is incorrect.
90367 static void setJoinExpr(Expr *p, int iTable){
90368 while( p ){
90369 ExprSetProperty(p, EP_FromJoin);
90370 assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
90371 ExprSetIrreducible(p);
90372 p->iRightJoinTable = (i16)iTable;
90373 setJoinExpr(p->pLeft, iTable);
90374 p = p->pRight;
90379 ** This routine processes the join information for a SELECT statement.
90380 ** ON and USING clauses are converted into extra terms of the WHERE clause.
90381 ** NATURAL joins also create extra WHERE clause terms.
90383 ** The terms of a FROM clause are contained in the Select.pSrc structure.
90384 ** The left most table is the first entry in Select.pSrc. The right-most
90385 ** table is the last entry. The join operator is held in the entry to
90386 ** the left. Thus entry 0 contains the join operator for the join between
90387 ** entries 0 and 1. Any ON or USING clauses associated with the join are
90388 ** also attached to the left entry.
90390 ** This routine returns the number of errors encountered.
90392 static int sqliteProcessJoin(Parse *pParse, Select *p){
90393 SrcList *pSrc; /* All tables in the FROM clause */
90394 int i, j; /* Loop counters */
90395 struct SrcList_item *pLeft; /* Left table being joined */
90396 struct SrcList_item *pRight; /* Right table being joined */
90398 pSrc = p->pSrc;
90399 pLeft = &pSrc->a[0];
90400 pRight = &pLeft[1];
90401 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
90402 Table *pLeftTab = pLeft->pTab;
90403 Table *pRightTab = pRight->pTab;
90404 int isOuter;
90406 if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
90407 isOuter = (pRight->jointype & JT_OUTER)!=0;
90409 /* When the NATURAL keyword is present, add WHERE clause terms for
90410 ** every column that the two tables have in common.
90412 if( pRight->jointype & JT_NATURAL ){
90413 if( pRight->pOn || pRight->pUsing ){
90414 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
90415 "an ON or USING clause", 0);
90416 return 1;
90418 for(j=0; j<pRightTab->nCol; j++){
90419 char *zName; /* Name of column in the right table */
90420 int iLeft; /* Matching left table */
90421 int iLeftCol; /* Matching column in the left table */
90423 zName = pRightTab->aCol[j].zName;
90424 if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
90425 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
90426 isOuter, &p->pWhere);
90431 /* Disallow both ON and USING clauses in the same join
90433 if( pRight->pOn && pRight->pUsing ){
90434 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
90435 "clauses in the same join");
90436 return 1;
90439 /* Add the ON clause to the end of the WHERE clause, connected by
90440 ** an AND operator.
90442 if( pRight->pOn ){
90443 if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
90444 p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
90445 pRight->pOn = 0;
90448 /* Create extra terms on the WHERE clause for each column named
90449 ** in the USING clause. Example: If the two tables to be joined are
90450 ** A and B and the USING clause names X, Y, and Z, then add this
90451 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
90452 ** Report an error if any column mentioned in the USING clause is
90453 ** not contained in both tables to be joined.
90455 if( pRight->pUsing ){
90456 IdList *pList = pRight->pUsing;
90457 for(j=0; j<pList->nId; j++){
90458 char *zName; /* Name of the term in the USING clause */
90459 int iLeft; /* Table on the left with matching column name */
90460 int iLeftCol; /* Column number of matching column on the left */
90461 int iRightCol; /* Column number of matching column on the right */
90463 zName = pList->a[j].zName;
90464 iRightCol = columnIndex(pRightTab, zName);
90465 if( iRightCol<0
90466 || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
90468 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
90469 "not present in both tables", zName);
90470 return 1;
90472 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
90473 isOuter, &p->pWhere);
90477 return 0;
90481 ** Insert code into "v" that will push the record on the top of the
90482 ** stack into the sorter.
90484 static void pushOntoSorter(
90485 Parse *pParse, /* Parser context */
90486 ExprList *pOrderBy, /* The ORDER BY clause */
90487 Select *pSelect, /* The whole SELECT statement */
90488 int regData /* Register holding data to be sorted */
90490 Vdbe *v = pParse->pVdbe;
90491 int nExpr = pOrderBy->nExpr;
90492 int regBase = sqlite3GetTempRange(pParse, nExpr+2);
90493 int regRecord = sqlite3GetTempReg(pParse);
90494 sqlite3ExprCacheClear(pParse);
90495 sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
90496 sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
90497 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
90498 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
90499 sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
90500 sqlite3ReleaseTempReg(pParse, regRecord);
90501 sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
90502 if( pSelect->iLimit ){
90503 int addr1, addr2;
90504 int iLimit;
90505 if( pSelect->iOffset ){
90506 iLimit = pSelect->iOffset+1;
90507 }else{
90508 iLimit = pSelect->iLimit;
90510 addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
90511 sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
90512 addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
90513 sqlite3VdbeJumpHere(v, addr1);
90514 sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
90515 sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
90516 sqlite3VdbeJumpHere(v, addr2);
90521 ** Add code to implement the OFFSET
90523 static void codeOffset(
90524 Vdbe *v, /* Generate code into this VM */
90525 Select *p, /* The SELECT statement being coded */
90526 int iContinue /* Jump here to skip the current record */
90528 if( p->iOffset && iContinue!=0 ){
90529 int addr;
90530 sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
90531 addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
90532 sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
90533 VdbeComment((v, "skip OFFSET records"));
90534 sqlite3VdbeJumpHere(v, addr);
90539 ** Add code that will check to make sure the N registers starting at iMem
90540 ** form a distinct entry. iTab is a sorting index that holds previously
90541 ** seen combinations of the N values. A new entry is made in iTab
90542 ** if the current N values are new.
90544 ** A jump to addrRepeat is made and the N+1 values are popped from the
90545 ** stack if the top N elements are not distinct.
90547 static void codeDistinct(
90548 Parse *pParse, /* Parsing and code generating context */
90549 int iTab, /* A sorting index used to test for distinctness */
90550 int addrRepeat, /* Jump to here if not distinct */
90551 int N, /* Number of elements */
90552 int iMem /* First element */
90554 Vdbe *v;
90555 int r1;
90557 v = pParse->pVdbe;
90558 r1 = sqlite3GetTempReg(pParse);
90559 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
90560 sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
90561 sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
90562 sqlite3ReleaseTempReg(pParse, r1);
90565 #ifndef SQLITE_OMIT_SUBQUERY
90567 ** Generate an error message when a SELECT is used within a subexpression
90568 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
90569 ** column. We do this in a subroutine because the error used to occur
90570 ** in multiple places. (The error only occurs in one place now, but we
90571 ** retain the subroutine to minimize code disruption.)
90573 static int checkForMultiColumnSelectError(
90574 Parse *pParse, /* Parse context. */
90575 SelectDest *pDest, /* Destination of SELECT results */
90576 int nExpr /* Number of result columns returned by SELECT */
90578 int eDest = pDest->eDest;
90579 if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
90580 sqlite3ErrorMsg(pParse, "only a single result allowed for "
90581 "a SELECT that is part of an expression");
90582 return 1;
90583 }else{
90584 return 0;
90587 #endif
90590 ** This routine generates the code for the inside of the inner loop
90591 ** of a SELECT.
90593 ** If srcTab and nColumn are both zero, then the pEList expressions
90594 ** are evaluated in order to get the data for this row. If nColumn>0
90595 ** then data is pulled from srcTab and pEList is used only to get the
90596 ** datatypes for each column.
90598 static void selectInnerLoop(
90599 Parse *pParse, /* The parser context */
90600 Select *p, /* The complete select statement being coded */
90601 ExprList *pEList, /* List of values being extracted */
90602 int srcTab, /* Pull data from this table */
90603 int nColumn, /* Number of columns in the source table */
90604 ExprList *pOrderBy, /* If not NULL, sort results using this key */
90605 int distinct, /* If >=0, make sure results are distinct */
90606 SelectDest *pDest, /* How to dispose of the results */
90607 int iContinue, /* Jump here to continue with next row */
90608 int iBreak /* Jump here to break out of the inner loop */
90610 Vdbe *v = pParse->pVdbe;
90611 int i;
90612 int hasDistinct; /* True if the DISTINCT keyword is present */
90613 int regResult; /* Start of memory holding result set */
90614 int eDest = pDest->eDest; /* How to dispose of results */
90615 int iParm = pDest->iParm; /* First argument to disposal method */
90616 int nResultCol; /* Number of result columns */
90618 assert( v );
90619 if( NEVER(v==0) ) return;
90620 assert( pEList!=0 );
90621 hasDistinct = distinct>=0;
90622 if( pOrderBy==0 && !hasDistinct ){
90623 codeOffset(v, p, iContinue);
90626 /* Pull the requested columns.
90628 if( nColumn>0 ){
90629 nResultCol = nColumn;
90630 }else{
90631 nResultCol = pEList->nExpr;
90633 if( pDest->iMem==0 ){
90634 pDest->iMem = pParse->nMem+1;
90635 pDest->nMem = nResultCol;
90636 pParse->nMem += nResultCol;
90637 }else{
90638 assert( pDest->nMem==nResultCol );
90640 regResult = pDest->iMem;
90641 if( nColumn>0 ){
90642 for(i=0; i<nColumn; i++){
90643 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
90645 }else if( eDest!=SRT_Exists ){
90646 /* If the destination is an EXISTS(...) expression, the actual
90647 ** values returned by the SELECT are not required.
90649 sqlite3ExprCacheClear(pParse);
90650 sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
90652 nColumn = nResultCol;
90654 /* If the DISTINCT keyword was present on the SELECT statement
90655 ** and this row has been seen before, then do not make this row
90656 ** part of the result.
90658 if( hasDistinct ){
90659 assert( pEList!=0 );
90660 assert( pEList->nExpr==nColumn );
90661 codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
90662 if( pOrderBy==0 ){
90663 codeOffset(v, p, iContinue);
90667 switch( eDest ){
90668 /* In this mode, write each query result to the key of the temporary
90669 ** table iParm.
90671 #ifndef SQLITE_OMIT_COMPOUND_SELECT
90672 case SRT_Union: {
90673 int r1;
90674 r1 = sqlite3GetTempReg(pParse);
90675 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90676 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
90677 sqlite3ReleaseTempReg(pParse, r1);
90678 break;
90681 /* Construct a record from the query result, but instead of
90682 ** saving that record, use it as a key to delete elements from
90683 ** the temporary table iParm.
90685 case SRT_Except: {
90686 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
90687 break;
90689 #endif
90691 /* Store the result as data using a unique key.
90693 case SRT_Table:
90694 case SRT_EphemTab: {
90695 int r1 = sqlite3GetTempReg(pParse);
90696 testcase( eDest==SRT_Table );
90697 testcase( eDest==SRT_EphemTab );
90698 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90699 if( pOrderBy ){
90700 pushOntoSorter(pParse, pOrderBy, p, r1);
90701 }else{
90702 int r2 = sqlite3GetTempReg(pParse);
90703 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
90704 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
90705 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90706 sqlite3ReleaseTempReg(pParse, r2);
90708 sqlite3ReleaseTempReg(pParse, r1);
90709 break;
90712 #ifndef SQLITE_OMIT_SUBQUERY
90713 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
90714 ** then there should be a single item on the stack. Write this
90715 ** item into the set table with bogus data.
90717 case SRT_Set: {
90718 assert( nColumn==1 );
90719 p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
90720 if( pOrderBy ){
90721 /* At first glance you would think we could optimize out the
90722 ** ORDER BY in this case since the order of entries in the set
90723 ** does not matter. But there might be a LIMIT clause, in which
90724 ** case the order does matter */
90725 pushOntoSorter(pParse, pOrderBy, p, regResult);
90726 }else{
90727 int r1 = sqlite3GetTempReg(pParse);
90728 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
90729 sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
90730 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
90731 sqlite3ReleaseTempReg(pParse, r1);
90733 break;
90736 /* If any row exist in the result set, record that fact and abort.
90738 case SRT_Exists: {
90739 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
90740 /* The LIMIT clause will terminate the loop for us */
90741 break;
90744 /* If this is a scalar select that is part of an expression, then
90745 ** store the results in the appropriate memory cell and break out
90746 ** of the scan loop.
90748 case SRT_Mem: {
90749 assert( nColumn==1 );
90750 if( pOrderBy ){
90751 pushOntoSorter(pParse, pOrderBy, p, regResult);
90752 }else{
90753 sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
90754 /* The LIMIT clause will jump out of the loop for us */
90756 break;
90758 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
90760 /* Send the data to the callback function or to a subroutine. In the
90761 ** case of a subroutine, the subroutine itself is responsible for
90762 ** popping the data from the stack.
90764 case SRT_Coroutine:
90765 case SRT_Output: {
90766 testcase( eDest==SRT_Coroutine );
90767 testcase( eDest==SRT_Output );
90768 if( pOrderBy ){
90769 int r1 = sqlite3GetTempReg(pParse);
90770 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90771 pushOntoSorter(pParse, pOrderBy, p, r1);
90772 sqlite3ReleaseTempReg(pParse, r1);
90773 }else if( eDest==SRT_Coroutine ){
90774 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
90775 }else{
90776 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
90777 sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
90779 break;
90782 #if !defined(SQLITE_OMIT_TRIGGER)
90783 /* Discard the results. This is used for SELECT statements inside
90784 ** the body of a TRIGGER. The purpose of such selects is to call
90785 ** user-defined functions that have side effects. We do not care
90786 ** about the actual results of the select.
90788 default: {
90789 assert( eDest==SRT_Discard );
90790 break;
90792 #endif
90795 /* Jump to the end of the loop if the LIMIT is reached. Except, if
90796 ** there is a sorter, in which case the sorter has already limited
90797 ** the output for us.
90799 if( pOrderBy==0 && p->iLimit ){
90800 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
90805 ** Given an expression list, generate a KeyInfo structure that records
90806 ** the collating sequence for each expression in that expression list.
90808 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
90809 ** KeyInfo structure is appropriate for initializing a virtual index to
90810 ** implement that clause. If the ExprList is the result set of a SELECT
90811 ** then the KeyInfo structure is appropriate for initializing a virtual
90812 ** index to implement a DISTINCT test.
90814 ** Space to hold the KeyInfo structure is obtain from malloc. The calling
90815 ** function is responsible for seeing that this structure is eventually
90816 ** freed. Add the KeyInfo structure to the P4 field of an opcode using
90817 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
90819 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
90820 sqlite3 *db = pParse->db;
90821 int nExpr;
90822 KeyInfo *pInfo;
90823 struct ExprList_item *pItem;
90824 int i;
90826 nExpr = pList->nExpr;
90827 pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
90828 if( pInfo ){
90829 pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
90830 pInfo->nField = (u16)nExpr;
90831 pInfo->enc = ENC(db);
90832 pInfo->db = db;
90833 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
90834 CollSeq *pColl;
90835 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
90836 if( !pColl ){
90837 pColl = db->pDfltColl;
90839 pInfo->aColl[i] = pColl;
90840 pInfo->aSortOrder[i] = pItem->sortOrder;
90843 return pInfo;
90846 #ifndef SQLITE_OMIT_COMPOUND_SELECT
90848 ** Name of the connection operator, used for error messages.
90850 static const char *selectOpName(int id){
90851 char *z;
90852 switch( id ){
90853 case TK_ALL: z = "UNION ALL"; break;
90854 case TK_INTERSECT: z = "INTERSECT"; break;
90855 case TK_EXCEPT: z = "EXCEPT"; break;
90856 default: z = "UNION"; break;
90858 return z;
90860 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
90862 #ifndef SQLITE_OMIT_EXPLAIN
90864 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
90865 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
90866 ** where the caption is of the form:
90868 ** "USE TEMP B-TREE FOR xxx"
90870 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
90871 ** is determined by the zUsage argument.
90873 static void explainTempTable(Parse *pParse, const char *zUsage){
90874 if( pParse->explain==2 ){
90875 Vdbe *v = pParse->pVdbe;
90876 char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
90877 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
90882 ** Assign expression b to lvalue a. A second, no-op, version of this macro
90883 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
90884 ** in sqlite3Select() to assign values to structure member variables that
90885 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
90886 ** code with #ifndef directives.
90888 # define explainSetInteger(a, b) a = b
90890 #else
90891 /* No-op versions of the explainXXX() functions and macros. */
90892 # define explainTempTable(y,z)
90893 # define explainSetInteger(y,z)
90894 #endif
90896 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
90898 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
90899 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
90900 ** where the caption is of one of the two forms:
90902 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
90903 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
90905 ** where iSub1 and iSub2 are the integers passed as the corresponding
90906 ** function parameters, and op is the text representation of the parameter
90907 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
90908 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
90909 ** false, or the second form if it is true.
90911 static void explainComposite(
90912 Parse *pParse, /* Parse context */
90913 int op, /* One of TK_UNION, TK_EXCEPT etc. */
90914 int iSub1, /* Subquery id 1 */
90915 int iSub2, /* Subquery id 2 */
90916 int bUseTmp /* True if a temp table was used */
90918 assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
90919 if( pParse->explain==2 ){
90920 Vdbe *v = pParse->pVdbe;
90921 char *zMsg = sqlite3MPrintf(
90922 pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
90923 bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
90925 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
90928 #else
90929 /* No-op versions of the explainXXX() functions and macros. */
90930 # define explainComposite(v,w,x,y,z)
90931 #endif
90934 ** If the inner loop was generated using a non-null pOrderBy argument,
90935 ** then the results were placed in a sorter. After the loop is terminated
90936 ** we need to run the sorter and output the results. The following
90937 ** routine generates the code needed to do that.
90939 static void generateSortTail(
90940 Parse *pParse, /* Parsing context */
90941 Select *p, /* The SELECT statement */
90942 Vdbe *v, /* Generate code into this VDBE */
90943 int nColumn, /* Number of columns of data */
90944 SelectDest *pDest /* Write the sorted results here */
90946 int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
90947 int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
90948 int addr;
90949 int iTab;
90950 int pseudoTab = 0;
90951 ExprList *pOrderBy = p->pOrderBy;
90953 int eDest = pDest->eDest;
90954 int iParm = pDest->iParm;
90956 int regRow;
90957 int regRowid;
90959 iTab = pOrderBy->iECursor;
90960 regRow = sqlite3GetTempReg(pParse);
90961 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
90962 pseudoTab = pParse->nTab++;
90963 sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
90964 regRowid = 0;
90965 }else{
90966 regRowid = sqlite3GetTempReg(pParse);
90968 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
90969 codeOffset(v, p, addrContinue);
90970 sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
90971 switch( eDest ){
90972 case SRT_Table:
90973 case SRT_EphemTab: {
90974 testcase( eDest==SRT_Table );
90975 testcase( eDest==SRT_EphemTab );
90976 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
90977 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
90978 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90979 break;
90981 #ifndef SQLITE_OMIT_SUBQUERY
90982 case SRT_Set: {
90983 assert( nColumn==1 );
90984 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
90985 sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
90986 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
90987 break;
90989 case SRT_Mem: {
90990 assert( nColumn==1 );
90991 sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
90992 /* The LIMIT clause will terminate the loop for us */
90993 break;
90995 #endif
90996 default: {
90997 int i;
90998 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
90999 testcase( eDest==SRT_Output );
91000 testcase( eDest==SRT_Coroutine );
91001 for(i=0; i<nColumn; i++){
91002 assert( regRow!=pDest->iMem+i );
91003 sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
91004 if( i==0 ){
91005 sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
91008 if( eDest==SRT_Output ){
91009 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
91010 sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
91011 }else{
91012 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
91014 break;
91017 sqlite3ReleaseTempReg(pParse, regRow);
91018 sqlite3ReleaseTempReg(pParse, regRowid);
91020 /* The bottom of the loop
91022 sqlite3VdbeResolveLabel(v, addrContinue);
91023 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
91024 sqlite3VdbeResolveLabel(v, addrBreak);
91025 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
91026 sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
91031 ** Return a pointer to a string containing the 'declaration type' of the
91032 ** expression pExpr. The string may be treated as static by the caller.
91034 ** The declaration type is the exact datatype definition extracted from the
91035 ** original CREATE TABLE statement if the expression is a column. The
91036 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
91037 ** is considered a column can be complex in the presence of subqueries. The
91038 ** result-set expression in all of the following SELECT statements is
91039 ** considered a column by this function.
91041 ** SELECT col FROM tbl;
91042 ** SELECT (SELECT col FROM tbl;
91043 ** SELECT (SELECT col FROM tbl);
91044 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
91046 ** The declaration type for any expression other than a column is NULL.
91048 static const char *columnType(
91049 NameContext *pNC,
91050 Expr *pExpr,
91051 const char **pzOriginDb,
91052 const char **pzOriginTab,
91053 const char **pzOriginCol
91055 char const *zType = 0;
91056 char const *zOriginDb = 0;
91057 char const *zOriginTab = 0;
91058 char const *zOriginCol = 0;
91059 int j;
91060 if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
91062 switch( pExpr->op ){
91063 case TK_AGG_COLUMN:
91064 case TK_COLUMN: {
91065 /* The expression is a column. Locate the table the column is being
91066 ** extracted from in NameContext.pSrcList. This table may be real
91067 ** database table or a subquery.
91069 Table *pTab = 0; /* Table structure column is extracted from */
91070 Select *pS = 0; /* Select the column is extracted from */
91071 int iCol = pExpr->iColumn; /* Index of column in pTab */
91072 testcase( pExpr->op==TK_AGG_COLUMN );
91073 testcase( pExpr->op==TK_COLUMN );
91074 while( pNC && !pTab ){
91075 SrcList *pTabList = pNC->pSrcList;
91076 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
91077 if( j<pTabList->nSrc ){
91078 pTab = pTabList->a[j].pTab;
91079 pS = pTabList->a[j].pSelect;
91080 }else{
91081 pNC = pNC->pNext;
91085 if( pTab==0 ){
91086 /* At one time, code such as "SELECT new.x" within a trigger would
91087 ** cause this condition to run. Since then, we have restructured how
91088 ** trigger code is generated and so this condition is no longer
91089 ** possible. However, it can still be true for statements like
91090 ** the following:
91092 ** CREATE TABLE t1(col INTEGER);
91093 ** SELECT (SELECT t1.col) FROM FROM t1;
91095 ** when columnType() is called on the expression "t1.col" in the
91096 ** sub-select. In this case, set the column type to NULL, even
91097 ** though it should really be "INTEGER".
91099 ** This is not a problem, as the column type of "t1.col" is never
91100 ** used. When columnType() is called on the expression
91101 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
91102 ** branch below. */
91103 break;
91106 assert( pTab && pExpr->pTab==pTab );
91107 if( pS ){
91108 /* The "table" is actually a sub-select or a view in the FROM clause
91109 ** of the SELECT statement. Return the declaration type and origin
91110 ** data for the result-set column of the sub-select.
91112 if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
91113 /* If iCol is less than zero, then the expression requests the
91114 ** rowid of the sub-select or view. This expression is legal (see
91115 ** test case misc2.2.2) - it always evaluates to NULL.
91117 NameContext sNC;
91118 Expr *p = pS->pEList->a[iCol].pExpr;
91119 sNC.pSrcList = pS->pSrc;
91120 sNC.pNext = pNC;
91121 sNC.pParse = pNC->pParse;
91122 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
91124 }else if( ALWAYS(pTab->pSchema) ){
91125 /* A real table */
91126 assert( !pS );
91127 if( iCol<0 ) iCol = pTab->iPKey;
91128 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
91129 if( iCol<0 ){
91130 zType = "INTEGER";
91131 zOriginCol = "rowid";
91132 }else{
91133 zType = pTab->aCol[iCol].zType;
91134 zOriginCol = pTab->aCol[iCol].zName;
91136 zOriginTab = pTab->zName;
91137 if( pNC->pParse ){
91138 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
91139 zOriginDb = pNC->pParse->db->aDb[iDb].zName;
91142 break;
91144 #ifndef SQLITE_OMIT_SUBQUERY
91145 case TK_SELECT: {
91146 /* The expression is a sub-select. Return the declaration type and
91147 ** origin info for the single column in the result set of the SELECT
91148 ** statement.
91150 NameContext sNC;
91151 Select *pS = pExpr->x.pSelect;
91152 Expr *p = pS->pEList->a[0].pExpr;
91153 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
91154 sNC.pSrcList = pS->pSrc;
91155 sNC.pNext = pNC;
91156 sNC.pParse = pNC->pParse;
91157 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
91158 break;
91160 #endif
91163 if( pzOriginDb ){
91164 assert( pzOriginTab && pzOriginCol );
91165 *pzOriginDb = zOriginDb;
91166 *pzOriginTab = zOriginTab;
91167 *pzOriginCol = zOriginCol;
91169 return zType;
91173 ** Generate code that will tell the VDBE the declaration types of columns
91174 ** in the result set.
91176 static void generateColumnTypes(
91177 Parse *pParse, /* Parser context */
91178 SrcList *pTabList, /* List of tables */
91179 ExprList *pEList /* Expressions defining the result set */
91181 #ifndef SQLITE_OMIT_DECLTYPE
91182 Vdbe *v = pParse->pVdbe;
91183 int i;
91184 NameContext sNC;
91185 sNC.pSrcList = pTabList;
91186 sNC.pParse = pParse;
91187 for(i=0; i<pEList->nExpr; i++){
91188 Expr *p = pEList->a[i].pExpr;
91189 const char *zType;
91190 #ifdef SQLITE_ENABLE_COLUMN_METADATA
91191 const char *zOrigDb = 0;
91192 const char *zOrigTab = 0;
91193 const char *zOrigCol = 0;
91194 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
91196 /* The vdbe must make its own copy of the column-type and other
91197 ** column specific strings, in case the schema is reset before this
91198 ** virtual machine is deleted.
91200 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
91201 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
91202 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
91203 #else
91204 zType = columnType(&sNC, p, 0, 0, 0);
91205 #endif
91206 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
91208 #endif /* SQLITE_OMIT_DECLTYPE */
91212 ** Generate code that will tell the VDBE the names of columns
91213 ** in the result set. This information is used to provide the
91214 ** azCol[] values in the callback.
91216 static void generateColumnNames(
91217 Parse *pParse, /* Parser context */
91218 SrcList *pTabList, /* List of tables */
91219 ExprList *pEList /* Expressions defining the result set */
91221 Vdbe *v = pParse->pVdbe;
91222 int i, j;
91223 sqlite3 *db = pParse->db;
91224 int fullNames, shortNames;
91226 #ifndef SQLITE_OMIT_EXPLAIN
91227 /* If this is an EXPLAIN, skip this step */
91228 if( pParse->explain ){
91229 return;
91231 #endif
91233 if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
91234 pParse->colNamesSet = 1;
91235 fullNames = (db->flags & SQLITE_FullColNames)!=0;
91236 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
91237 sqlite3VdbeSetNumCols(v, pEList->nExpr);
91238 for(i=0; i<pEList->nExpr; i++){
91239 Expr *p;
91240 p = pEList->a[i].pExpr;
91241 if( NEVER(p==0) ) continue;
91242 if( pEList->a[i].zName ){
91243 char *zName = pEList->a[i].zName;
91244 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
91245 }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
91246 Table *pTab;
91247 char *zCol;
91248 int iCol = p->iColumn;
91249 for(j=0; ALWAYS(j<pTabList->nSrc); j++){
91250 if( pTabList->a[j].iCursor==p->iTable ) break;
91252 assert( j<pTabList->nSrc );
91253 pTab = pTabList->a[j].pTab;
91254 if( iCol<0 ) iCol = pTab->iPKey;
91255 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
91256 if( iCol<0 ){
91257 zCol = "rowid";
91258 }else{
91259 zCol = pTab->aCol[iCol].zName;
91261 if( !shortNames && !fullNames ){
91262 sqlite3VdbeSetColName(v, i, COLNAME_NAME,
91263 sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
91264 }else if( fullNames ){
91265 char *zName = 0;
91266 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
91267 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
91268 }else{
91269 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
91271 }else{
91272 sqlite3VdbeSetColName(v, i, COLNAME_NAME,
91273 sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
91276 generateColumnTypes(pParse, pTabList, pEList);
91280 ** Given a an expression list (which is really the list of expressions
91281 ** that form the result set of a SELECT statement) compute appropriate
91282 ** column names for a table that would hold the expression list.
91284 ** All column names will be unique.
91286 ** Only the column names are computed. Column.zType, Column.zColl,
91287 ** and other fields of Column are zeroed.
91289 ** Return SQLITE_OK on success. If a memory allocation error occurs,
91290 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
91292 static int selectColumnsFromExprList(
91293 Parse *pParse, /* Parsing context */
91294 ExprList *pEList, /* Expr list from which to derive column names */
91295 int *pnCol, /* Write the number of columns here */
91296 Column **paCol /* Write the new column list here */
91298 sqlite3 *db = pParse->db; /* Database connection */
91299 int i, j; /* Loop counters */
91300 int cnt; /* Index added to make the name unique */
91301 Column *aCol, *pCol; /* For looping over result columns */
91302 int nCol; /* Number of columns in the result set */
91303 Expr *p; /* Expression for a single result column */
91304 char *zName; /* Column name */
91305 int nName; /* Size of name in zName[] */
91307 *pnCol = nCol = pEList->nExpr;
91308 aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
91309 if( aCol==0 ) return SQLITE_NOMEM;
91310 for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91311 /* Get an appropriate name for the column
91313 p = pEList->a[i].pExpr;
91314 assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
91315 || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
91316 if( (zName = pEList->a[i].zName)!=0 ){
91317 /* If the column contains an "AS <name>" phrase, use <name> as the name */
91318 zName = sqlite3DbStrDup(db, zName);
91319 }else{
91320 Expr *pColExpr = p; /* The expression that is the result column name */
91321 Table *pTab; /* Table associated with this expression */
91322 while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
91323 if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
91324 /* For columns use the column name name */
91325 int iCol = pColExpr->iColumn;
91326 pTab = pColExpr->pTab;
91327 if( iCol<0 ) iCol = pTab->iPKey;
91328 zName = sqlite3MPrintf(db, "%s",
91329 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
91330 }else if( pColExpr->op==TK_ID ){
91331 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
91332 zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
91333 }else{
91334 /* Use the original text of the column expression as its name */
91335 zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
91338 if( db->mallocFailed ){
91339 sqlite3DbFree(db, zName);
91340 break;
91343 /* Make sure the column name is unique. If the name is not unique,
91344 ** append a integer to the name so that it becomes unique.
91346 nName = sqlite3Strlen30(zName);
91347 for(j=cnt=0; j<i; j++){
91348 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
91349 char *zNewName;
91350 zName[nName] = 0;
91351 zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
91352 sqlite3DbFree(db, zName);
91353 zName = zNewName;
91354 j = -1;
91355 if( zName==0 ) break;
91358 pCol->zName = zName;
91360 if( db->mallocFailed ){
91361 for(j=0; j<i; j++){
91362 sqlite3DbFree(db, aCol[j].zName);
91364 sqlite3DbFree(db, aCol);
91365 *paCol = 0;
91366 *pnCol = 0;
91367 return SQLITE_NOMEM;
91369 return SQLITE_OK;
91373 ** Add type and collation information to a column list based on
91374 ** a SELECT statement.
91376 ** The column list presumably came from selectColumnNamesFromExprList().
91377 ** The column list has only names, not types or collations. This
91378 ** routine goes through and adds the types and collations.
91380 ** This routine requires that all identifiers in the SELECT
91381 ** statement be resolved.
91383 static void selectAddColumnTypeAndCollation(
91384 Parse *pParse, /* Parsing contexts */
91385 int nCol, /* Number of columns */
91386 Column *aCol, /* List of columns */
91387 Select *pSelect /* SELECT used to determine types and collations */
91389 sqlite3 *db = pParse->db;
91390 NameContext sNC;
91391 Column *pCol;
91392 CollSeq *pColl;
91393 int i;
91394 Expr *p;
91395 struct ExprList_item *a;
91397 assert( pSelect!=0 );
91398 assert( (pSelect->selFlags & SF_Resolved)!=0 );
91399 assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
91400 if( db->mallocFailed ) return;
91401 memset(&sNC, 0, sizeof(sNC));
91402 sNC.pSrcList = pSelect->pSrc;
91403 a = pSelect->pEList->a;
91404 for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91405 p = a[i].pExpr;
91406 pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
91407 pCol->affinity = sqlite3ExprAffinity(p);
91408 if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
91409 pColl = sqlite3ExprCollSeq(pParse, p);
91410 if( pColl ){
91411 pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
91417 ** Given a SELECT statement, generate a Table structure that describes
91418 ** the result set of that SELECT.
91420 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
91421 Table *pTab;
91422 sqlite3 *db = pParse->db;
91423 int savedFlags;
91425 savedFlags = db->flags;
91426 db->flags &= ~SQLITE_FullColNames;
91427 db->flags |= SQLITE_ShortColNames;
91428 sqlite3SelectPrep(pParse, pSelect, 0);
91429 if( pParse->nErr ) return 0;
91430 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
91431 db->flags = savedFlags;
91432 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
91433 if( pTab==0 ){
91434 return 0;
91436 /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
91437 ** is disabled */
91438 assert( db->lookaside.bEnabled==0 );
91439 pTab->nRef = 1;
91440 pTab->zName = 0;
91441 pTab->nRowEst = 1000000;
91442 selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
91443 selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
91444 pTab->iPKey = -1;
91445 if( db->mallocFailed ){
91446 sqlite3DeleteTable(db, pTab);
91447 return 0;
91449 return pTab;
91453 ** Get a VDBE for the given parser context. Create a new one if necessary.
91454 ** If an error occurs, return NULL and leave a message in pParse.
91456 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
91457 Vdbe *v = pParse->pVdbe;
91458 if( v==0 ){
91459 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
91460 #ifndef SQLITE_OMIT_TRACE
91461 if( v ){
91462 sqlite3VdbeAddOp0(v, OP_Trace);
91464 #endif
91466 return v;
91471 ** Compute the iLimit and iOffset fields of the SELECT based on the
91472 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
91473 ** that appear in the original SQL statement after the LIMIT and OFFSET
91474 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
91475 ** are the integer memory register numbers for counters used to compute
91476 ** the limit and offset. If there is no limit and/or offset, then
91477 ** iLimit and iOffset are negative.
91479 ** This routine changes the values of iLimit and iOffset only if
91480 ** a limit or offset is defined by pLimit and pOffset. iLimit and
91481 ** iOffset should have been preset to appropriate default values
91482 ** (usually but not always -1) prior to calling this routine.
91483 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
91484 ** redefined. The UNION ALL operator uses this property to force
91485 ** the reuse of the same limit and offset registers across multiple
91486 ** SELECT statements.
91488 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
91489 Vdbe *v = 0;
91490 int iLimit = 0;
91491 int iOffset;
91492 int addr1, n;
91493 if( p->iLimit ) return;
91496 ** "LIMIT -1" always shows all rows. There is some
91497 ** contraversy about what the correct behavior should be.
91498 ** The current implementation interprets "LIMIT 0" to mean
91499 ** no rows.
91501 sqlite3ExprCacheClear(pParse);
91502 assert( p->pOffset==0 || p->pLimit!=0 );
91503 if( p->pLimit ){
91504 p->iLimit = iLimit = ++pParse->nMem;
91505 v = sqlite3GetVdbe(pParse);
91506 if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
91507 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
91508 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
91509 VdbeComment((v, "LIMIT counter"));
91510 if( n==0 ){
91511 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
91512 }else{
91513 if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
91515 }else{
91516 sqlite3ExprCode(pParse, p->pLimit, iLimit);
91517 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
91518 VdbeComment((v, "LIMIT counter"));
91519 sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
91521 if( p->pOffset ){
91522 p->iOffset = iOffset = ++pParse->nMem;
91523 pParse->nMem++; /* Allocate an extra register for limit+offset */
91524 sqlite3ExprCode(pParse, p->pOffset, iOffset);
91525 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
91526 VdbeComment((v, "OFFSET counter"));
91527 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
91528 sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
91529 sqlite3VdbeJumpHere(v, addr1);
91530 sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
91531 VdbeComment((v, "LIMIT+OFFSET"));
91532 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
91533 sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
91534 sqlite3VdbeJumpHere(v, addr1);
91539 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91541 ** Return the appropriate collating sequence for the iCol-th column of
91542 ** the result set for the compound-select statement "p". Return NULL if
91543 ** the column has no default collating sequence.
91545 ** The collating sequence for the compound select is taken from the
91546 ** left-most term of the select that has a collating sequence.
91548 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
91549 CollSeq *pRet;
91550 if( p->pPrior ){
91551 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
91552 }else{
91553 pRet = 0;
91555 assert( iCol>=0 );
91556 if( pRet==0 && iCol<p->pEList->nExpr ){
91557 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
91559 return pRet;
91561 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
91563 /* Forward reference */
91564 static int multiSelectOrderBy(
91565 Parse *pParse, /* Parsing context */
91566 Select *p, /* The right-most of SELECTs to be coded */
91567 SelectDest *pDest /* What to do with query results */
91571 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91573 ** This routine is called to process a compound query form from
91574 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
91575 ** INTERSECT
91577 ** "p" points to the right-most of the two queries. the query on the
91578 ** left is p->pPrior. The left query could also be a compound query
91579 ** in which case this routine will be called recursively.
91581 ** The results of the total query are to be written into a destination
91582 ** of type eDest with parameter iParm.
91584 ** Example 1: Consider a three-way compound SQL statement.
91586 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
91588 ** This statement is parsed up as follows:
91590 ** SELECT c FROM t3
91591 ** |
91592 ** `-----> SELECT b FROM t2
91593 ** |
91594 ** `------> SELECT a FROM t1
91596 ** The arrows in the diagram above represent the Select.pPrior pointer.
91597 ** So if this routine is called with p equal to the t3 query, then
91598 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
91600 ** Notice that because of the way SQLite parses compound SELECTs, the
91601 ** individual selects always group from left to right.
91603 static int multiSelect(
91604 Parse *pParse, /* Parsing context */
91605 Select *p, /* The right-most of SELECTs to be coded */
91606 SelectDest *pDest /* What to do with query results */
91608 int rc = SQLITE_OK; /* Success code from a subroutine */
91609 Select *pPrior; /* Another SELECT immediately to our left */
91610 Vdbe *v; /* Generate code to this VDBE */
91611 SelectDest dest; /* Alternative data destination */
91612 Select *pDelete = 0; /* Chain of simple selects to delete */
91613 sqlite3 *db; /* Database connection */
91614 #ifndef SQLITE_OMIT_EXPLAIN
91615 int iSub1; /* EQP id of left-hand query */
91616 int iSub2; /* EQP id of right-hand query */
91617 #endif
91619 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
91620 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
91622 assert( p && p->pPrior ); /* Calling function guarantees this much */
91623 db = pParse->db;
91624 pPrior = p->pPrior;
91625 assert( pPrior->pRightmost!=pPrior );
91626 assert( pPrior->pRightmost==p->pRightmost );
91627 dest = *pDest;
91628 if( pPrior->pOrderBy ){
91629 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
91630 selectOpName(p->op));
91631 rc = 1;
91632 goto multi_select_end;
91634 if( pPrior->pLimit ){
91635 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
91636 selectOpName(p->op));
91637 rc = 1;
91638 goto multi_select_end;
91641 v = sqlite3GetVdbe(pParse);
91642 assert( v!=0 ); /* The VDBE already created by calling function */
91644 /* Create the destination temporary table if necessary
91646 if( dest.eDest==SRT_EphemTab ){
91647 assert( p->pEList );
91648 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
91649 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
91650 dest.eDest = SRT_Table;
91653 /* Make sure all SELECTs in the statement have the same number of elements
91654 ** in their result sets.
91656 assert( p->pEList && pPrior->pEList );
91657 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
91658 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
91659 " do not have the same number of result columns", selectOpName(p->op));
91660 rc = 1;
91661 goto multi_select_end;
91664 /* Compound SELECTs that have an ORDER BY clause are handled separately.
91666 if( p->pOrderBy ){
91667 return multiSelectOrderBy(pParse, p, pDest);
91670 /* Generate code for the left and right SELECT statements.
91672 switch( p->op ){
91673 case TK_ALL: {
91674 int addr = 0;
91675 int nLimit;
91676 assert( !pPrior->pLimit );
91677 pPrior->pLimit = p->pLimit;
91678 pPrior->pOffset = p->pOffset;
91679 explainSetInteger(iSub1, pParse->iNextSelectId);
91680 rc = sqlite3Select(pParse, pPrior, &dest);
91681 p->pLimit = 0;
91682 p->pOffset = 0;
91683 if( rc ){
91684 goto multi_select_end;
91686 p->pPrior = 0;
91687 p->iLimit = pPrior->iLimit;
91688 p->iOffset = pPrior->iOffset;
91689 if( p->iLimit ){
91690 addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
91691 VdbeComment((v, "Jump ahead if LIMIT reached"));
91693 explainSetInteger(iSub2, pParse->iNextSelectId);
91694 rc = sqlite3Select(pParse, p, &dest);
91695 testcase( rc!=SQLITE_OK );
91696 pDelete = p->pPrior;
91697 p->pPrior = pPrior;
91698 p->nSelectRow += pPrior->nSelectRow;
91699 if( pPrior->pLimit
91700 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
91701 && p->nSelectRow > (double)nLimit
91703 p->nSelectRow = (double)nLimit;
91705 if( addr ){
91706 sqlite3VdbeJumpHere(v, addr);
91708 break;
91710 case TK_EXCEPT:
91711 case TK_UNION: {
91712 int unionTab; /* Cursor number of the temporary table holding result */
91713 u8 op = 0; /* One of the SRT_ operations to apply to self */
91714 int priorOp; /* The SRT_ operation to apply to prior selects */
91715 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
91716 int addr;
91717 SelectDest uniondest;
91719 testcase( p->op==TK_EXCEPT );
91720 testcase( p->op==TK_UNION );
91721 priorOp = SRT_Union;
91722 if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
91723 /* We can reuse a temporary table generated by a SELECT to our
91724 ** right.
91726 assert( p->pRightmost!=p ); /* Can only happen for leftward elements
91727 ** of a 3-way or more compound */
91728 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
91729 assert( p->pOffset==0 ); /* Not allowed on leftward elements */
91730 unionTab = dest.iParm;
91731 }else{
91732 /* We will need to create our own temporary table to hold the
91733 ** intermediate results.
91735 unionTab = pParse->nTab++;
91736 assert( p->pOrderBy==0 );
91737 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
91738 assert( p->addrOpenEphm[0] == -1 );
91739 p->addrOpenEphm[0] = addr;
91740 p->pRightmost->selFlags |= SF_UsesEphemeral;
91741 assert( p->pEList );
91744 /* Code the SELECT statements to our left
91746 assert( !pPrior->pOrderBy );
91747 sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
91748 explainSetInteger(iSub1, pParse->iNextSelectId);
91749 rc = sqlite3Select(pParse, pPrior, &uniondest);
91750 if( rc ){
91751 goto multi_select_end;
91754 /* Code the current SELECT statement
91756 if( p->op==TK_EXCEPT ){
91757 op = SRT_Except;
91758 }else{
91759 assert( p->op==TK_UNION );
91760 op = SRT_Union;
91762 p->pPrior = 0;
91763 pLimit = p->pLimit;
91764 p->pLimit = 0;
91765 pOffset = p->pOffset;
91766 p->pOffset = 0;
91767 uniondest.eDest = op;
91768 explainSetInteger(iSub2, pParse->iNextSelectId);
91769 rc = sqlite3Select(pParse, p, &uniondest);
91770 testcase( rc!=SQLITE_OK );
91771 /* Query flattening in sqlite3Select() might refill p->pOrderBy.
91772 ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
91773 sqlite3ExprListDelete(db, p->pOrderBy);
91774 pDelete = p->pPrior;
91775 p->pPrior = pPrior;
91776 p->pOrderBy = 0;
91777 if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
91778 sqlite3ExprDelete(db, p->pLimit);
91779 p->pLimit = pLimit;
91780 p->pOffset = pOffset;
91781 p->iLimit = 0;
91782 p->iOffset = 0;
91784 /* Convert the data in the temporary table into whatever form
91785 ** it is that we currently need.
91787 assert( unionTab==dest.iParm || dest.eDest!=priorOp );
91788 if( dest.eDest!=priorOp ){
91789 int iCont, iBreak, iStart;
91790 assert( p->pEList );
91791 if( dest.eDest==SRT_Output ){
91792 Select *pFirst = p;
91793 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
91794 generateColumnNames(pParse, 0, pFirst->pEList);
91796 iBreak = sqlite3VdbeMakeLabel(v);
91797 iCont = sqlite3VdbeMakeLabel(v);
91798 computeLimitRegisters(pParse, p, iBreak);
91799 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
91800 iStart = sqlite3VdbeCurrentAddr(v);
91801 selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
91802 0, -1, &dest, iCont, iBreak);
91803 sqlite3VdbeResolveLabel(v, iCont);
91804 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
91805 sqlite3VdbeResolveLabel(v, iBreak);
91806 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
91808 break;
91810 default: assert( p->op==TK_INTERSECT ); {
91811 int tab1, tab2;
91812 int iCont, iBreak, iStart;
91813 Expr *pLimit, *pOffset;
91814 int addr;
91815 SelectDest intersectdest;
91816 int r1;
91818 /* INTERSECT is different from the others since it requires
91819 ** two temporary tables. Hence it has its own case. Begin
91820 ** by allocating the tables we will need.
91822 tab1 = pParse->nTab++;
91823 tab2 = pParse->nTab++;
91824 assert( p->pOrderBy==0 );
91826 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
91827 assert( p->addrOpenEphm[0] == -1 );
91828 p->addrOpenEphm[0] = addr;
91829 p->pRightmost->selFlags |= SF_UsesEphemeral;
91830 assert( p->pEList );
91832 /* Code the SELECTs to our left into temporary table "tab1".
91834 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
91835 explainSetInteger(iSub1, pParse->iNextSelectId);
91836 rc = sqlite3Select(pParse, pPrior, &intersectdest);
91837 if( rc ){
91838 goto multi_select_end;
91841 /* Code the current SELECT into temporary table "tab2"
91843 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
91844 assert( p->addrOpenEphm[1] == -1 );
91845 p->addrOpenEphm[1] = addr;
91846 p->pPrior = 0;
91847 pLimit = p->pLimit;
91848 p->pLimit = 0;
91849 pOffset = p->pOffset;
91850 p->pOffset = 0;
91851 intersectdest.iParm = tab2;
91852 explainSetInteger(iSub2, pParse->iNextSelectId);
91853 rc = sqlite3Select(pParse, p, &intersectdest);
91854 testcase( rc!=SQLITE_OK );
91855 pDelete = p->pPrior;
91856 p->pPrior = pPrior;
91857 if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
91858 sqlite3ExprDelete(db, p->pLimit);
91859 p->pLimit = pLimit;
91860 p->pOffset = pOffset;
91862 /* Generate code to take the intersection of the two temporary
91863 ** tables.
91865 assert( p->pEList );
91866 if( dest.eDest==SRT_Output ){
91867 Select *pFirst = p;
91868 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
91869 generateColumnNames(pParse, 0, pFirst->pEList);
91871 iBreak = sqlite3VdbeMakeLabel(v);
91872 iCont = sqlite3VdbeMakeLabel(v);
91873 computeLimitRegisters(pParse, p, iBreak);
91874 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
91875 r1 = sqlite3GetTempReg(pParse);
91876 iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
91877 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
91878 sqlite3ReleaseTempReg(pParse, r1);
91879 selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
91880 0, -1, &dest, iCont, iBreak);
91881 sqlite3VdbeResolveLabel(v, iCont);
91882 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
91883 sqlite3VdbeResolveLabel(v, iBreak);
91884 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
91885 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
91886 break;
91890 explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
91892 /* Compute collating sequences used by
91893 ** temporary tables needed to implement the compound select.
91894 ** Attach the KeyInfo structure to all temporary tables.
91896 ** This section is run by the right-most SELECT statement only.
91897 ** SELECT statements to the left always skip this part. The right-most
91898 ** SELECT might also skip this part if it has no ORDER BY clause and
91899 ** no temp tables are required.
91901 if( p->selFlags & SF_UsesEphemeral ){
91902 int i; /* Loop counter */
91903 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
91904 Select *pLoop; /* For looping through SELECT statements */
91905 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
91906 int nCol; /* Number of columns in result set */
91908 assert( p->pRightmost==p );
91909 nCol = p->pEList->nExpr;
91910 pKeyInfo = sqlite3DbMallocZero(db,
91911 sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
91912 if( !pKeyInfo ){
91913 rc = SQLITE_NOMEM;
91914 goto multi_select_end;
91917 pKeyInfo->enc = ENC(db);
91918 pKeyInfo->nField = (u16)nCol;
91920 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
91921 *apColl = multiSelectCollSeq(pParse, p, i);
91922 if( 0==*apColl ){
91923 *apColl = db->pDfltColl;
91927 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
91928 for(i=0; i<2; i++){
91929 int addr = pLoop->addrOpenEphm[i];
91930 if( addr<0 ){
91931 /* If [0] is unused then [1] is also unused. So we can
91932 ** always safely abort as soon as the first unused slot is found */
91933 assert( pLoop->addrOpenEphm[1]<0 );
91934 break;
91936 sqlite3VdbeChangeP2(v, addr, nCol);
91937 sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
91938 pLoop->addrOpenEphm[i] = -1;
91941 sqlite3DbFree(db, pKeyInfo);
91944 multi_select_end:
91945 pDest->iMem = dest.iMem;
91946 pDest->nMem = dest.nMem;
91947 sqlite3SelectDelete(db, pDelete);
91948 return rc;
91950 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
91953 ** Code an output subroutine for a coroutine implementation of a
91954 ** SELECT statment.
91956 ** The data to be output is contained in pIn->iMem. There are
91957 ** pIn->nMem columns to be output. pDest is where the output should
91958 ** be sent.
91960 ** regReturn is the number of the register holding the subroutine
91961 ** return address.
91963 ** If regPrev>0 then it is the first register in a vector that
91964 ** records the previous output. mem[regPrev] is a flag that is false
91965 ** if there has been no previous output. If regPrev>0 then code is
91966 ** generated to suppress duplicates. pKeyInfo is used for comparing
91967 ** keys.
91969 ** If the LIMIT found in p->iLimit is reached, jump immediately to
91970 ** iBreak.
91972 static int generateOutputSubroutine(
91973 Parse *pParse, /* Parsing context */
91974 Select *p, /* The SELECT statement */
91975 SelectDest *pIn, /* Coroutine supplying data */
91976 SelectDest *pDest, /* Where to send the data */
91977 int regReturn, /* The return address register */
91978 int regPrev, /* Previous result register. No uniqueness if 0 */
91979 KeyInfo *pKeyInfo, /* For comparing with previous entry */
91980 int p4type, /* The p4 type for pKeyInfo */
91981 int iBreak /* Jump here if we hit the LIMIT */
91983 Vdbe *v = pParse->pVdbe;
91984 int iContinue;
91985 int addr;
91987 addr = sqlite3VdbeCurrentAddr(v);
91988 iContinue = sqlite3VdbeMakeLabel(v);
91990 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
91992 if( regPrev ){
91993 int j1, j2;
91994 j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
91995 j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
91996 (char*)pKeyInfo, p4type);
91997 sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
91998 sqlite3VdbeJumpHere(v, j1);
91999 sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
92000 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
92002 if( pParse->db->mallocFailed ) return 0;
92004 /* Suppress the the first OFFSET entries if there is an OFFSET clause
92006 codeOffset(v, p, iContinue);
92008 switch( pDest->eDest ){
92009 /* Store the result as data using a unique key.
92011 case SRT_Table:
92012 case SRT_EphemTab: {
92013 int r1 = sqlite3GetTempReg(pParse);
92014 int r2 = sqlite3GetTempReg(pParse);
92015 testcase( pDest->eDest==SRT_Table );
92016 testcase( pDest->eDest==SRT_EphemTab );
92017 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
92018 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
92019 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
92020 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
92021 sqlite3ReleaseTempReg(pParse, r2);
92022 sqlite3ReleaseTempReg(pParse, r1);
92023 break;
92026 #ifndef SQLITE_OMIT_SUBQUERY
92027 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
92028 ** then there should be a single item on the stack. Write this
92029 ** item into the set table with bogus data.
92031 case SRT_Set: {
92032 int r1;
92033 assert( pIn->nMem==1 );
92034 p->affinity =
92035 sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
92036 r1 = sqlite3GetTempReg(pParse);
92037 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
92038 sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
92039 sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
92040 sqlite3ReleaseTempReg(pParse, r1);
92041 break;
92044 #if 0 /* Never occurs on an ORDER BY query */
92045 /* If any row exist in the result set, record that fact and abort.
92047 case SRT_Exists: {
92048 sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
92049 /* The LIMIT clause will terminate the loop for us */
92050 break;
92052 #endif
92054 /* If this is a scalar select that is part of an expression, then
92055 ** store the results in the appropriate memory cell and break out
92056 ** of the scan loop.
92058 case SRT_Mem: {
92059 assert( pIn->nMem==1 );
92060 sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
92061 /* The LIMIT clause will jump out of the loop for us */
92062 break;
92064 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
92066 /* The results are stored in a sequence of registers
92067 ** starting at pDest->iMem. Then the co-routine yields.
92069 case SRT_Coroutine: {
92070 if( pDest->iMem==0 ){
92071 pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
92072 pDest->nMem = pIn->nMem;
92074 sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
92075 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
92076 break;
92079 /* If none of the above, then the result destination must be
92080 ** SRT_Output. This routine is never called with any other
92081 ** destination other than the ones handled above or SRT_Output.
92083 ** For SRT_Output, results are stored in a sequence of registers.
92084 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
92085 ** return the next row of result.
92087 default: {
92088 assert( pDest->eDest==SRT_Output );
92089 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
92090 sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
92091 break;
92095 /* Jump to the end of the loop if the LIMIT is reached.
92097 if( p->iLimit ){
92098 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
92101 /* Generate the subroutine return
92103 sqlite3VdbeResolveLabel(v, iContinue);
92104 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
92106 return addr;
92110 ** Alternative compound select code generator for cases when there
92111 ** is an ORDER BY clause.
92113 ** We assume a query of the following form:
92115 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
92117 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
92118 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
92119 ** co-routines. Then run the co-routines in parallel and merge the results
92120 ** into the output. In addition to the two coroutines (called selectA and
92121 ** selectB) there are 7 subroutines:
92123 ** outA: Move the output of the selectA coroutine into the output
92124 ** of the compound query.
92126 ** outB: Move the output of the selectB coroutine into the output
92127 ** of the compound query. (Only generated for UNION and
92128 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
92129 ** appears only in B.)
92131 ** AltB: Called when there is data from both coroutines and A<B.
92133 ** AeqB: Called when there is data from both coroutines and A==B.
92135 ** AgtB: Called when there is data from both coroutines and A>B.
92137 ** EofA: Called when data is exhausted from selectA.
92139 ** EofB: Called when data is exhausted from selectB.
92141 ** The implementation of the latter five subroutines depend on which
92142 ** <operator> is used:
92145 ** UNION ALL UNION EXCEPT INTERSECT
92146 ** ------------- ----------------- -------------- -----------------
92147 ** AltB: outA, nextA outA, nextA outA, nextA nextA
92149 ** AeqB: outA, nextA nextA nextA outA, nextA
92151 ** AgtB: outB, nextB outB, nextB nextB nextB
92153 ** EofA: outB, nextB outB, nextB halt halt
92155 ** EofB: outA, nextA outA, nextA outA, nextA halt
92157 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
92158 ** causes an immediate jump to EofA and an EOF on B following nextB causes
92159 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
92160 ** following nextX causes a jump to the end of the select processing.
92162 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
92163 ** within the output subroutine. The regPrev register set holds the previously
92164 ** output value. A comparison is made against this value and the output
92165 ** is skipped if the next results would be the same as the previous.
92167 ** The implementation plan is to implement the two coroutines and seven
92168 ** subroutines first, then put the control logic at the bottom. Like this:
92170 ** goto Init
92171 ** coA: coroutine for left query (A)
92172 ** coB: coroutine for right query (B)
92173 ** outA: output one row of A
92174 ** outB: output one row of B (UNION and UNION ALL only)
92175 ** EofA: ...
92176 ** EofB: ...
92177 ** AltB: ...
92178 ** AeqB: ...
92179 ** AgtB: ...
92180 ** Init: initialize coroutine registers
92181 ** yield coA
92182 ** if eof(A) goto EofA
92183 ** yield coB
92184 ** if eof(B) goto EofB
92185 ** Cmpr: Compare A, B
92186 ** Jump AltB, AeqB, AgtB
92187 ** End: ...
92189 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
92190 ** actually called using Gosub and they do not Return. EofA and EofB loop
92191 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
92192 ** and AgtB jump to either L2 or to one of EofA or EofB.
92194 #ifndef SQLITE_OMIT_COMPOUND_SELECT
92195 static int multiSelectOrderBy(
92196 Parse *pParse, /* Parsing context */
92197 Select *p, /* The right-most of SELECTs to be coded */
92198 SelectDest *pDest /* What to do with query results */
92200 int i, j; /* Loop counters */
92201 Select *pPrior; /* Another SELECT immediately to our left */
92202 Vdbe *v; /* Generate code to this VDBE */
92203 SelectDest destA; /* Destination for coroutine A */
92204 SelectDest destB; /* Destination for coroutine B */
92205 int regAddrA; /* Address register for select-A coroutine */
92206 int regEofA; /* Flag to indicate when select-A is complete */
92207 int regAddrB; /* Address register for select-B coroutine */
92208 int regEofB; /* Flag to indicate when select-B is complete */
92209 int addrSelectA; /* Address of the select-A coroutine */
92210 int addrSelectB; /* Address of the select-B coroutine */
92211 int regOutA; /* Address register for the output-A subroutine */
92212 int regOutB; /* Address register for the output-B subroutine */
92213 int addrOutA; /* Address of the output-A subroutine */
92214 int addrOutB = 0; /* Address of the output-B subroutine */
92215 int addrEofA; /* Address of the select-A-exhausted subroutine */
92216 int addrEofB; /* Address of the select-B-exhausted subroutine */
92217 int addrAltB; /* Address of the A<B subroutine */
92218 int addrAeqB; /* Address of the A==B subroutine */
92219 int addrAgtB; /* Address of the A>B subroutine */
92220 int regLimitA; /* Limit register for select-A */
92221 int regLimitB; /* Limit register for select-A */
92222 int regPrev; /* A range of registers to hold previous output */
92223 int savedLimit; /* Saved value of p->iLimit */
92224 int savedOffset; /* Saved value of p->iOffset */
92225 int labelCmpr; /* Label for the start of the merge algorithm */
92226 int labelEnd; /* Label for the end of the overall SELECT stmt */
92227 int j1; /* Jump instructions that get retargetted */
92228 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
92229 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
92230 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
92231 sqlite3 *db; /* Database connection */
92232 ExprList *pOrderBy; /* The ORDER BY clause */
92233 int nOrderBy; /* Number of terms in the ORDER BY clause */
92234 int *aPermute; /* Mapping from ORDER BY terms to result set columns */
92235 #ifndef SQLITE_OMIT_EXPLAIN
92236 int iSub1; /* EQP id of left-hand query */
92237 int iSub2; /* EQP id of right-hand query */
92238 #endif
92240 assert( p->pOrderBy!=0 );
92241 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
92242 db = pParse->db;
92243 v = pParse->pVdbe;
92244 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
92245 labelEnd = sqlite3VdbeMakeLabel(v);
92246 labelCmpr = sqlite3VdbeMakeLabel(v);
92249 /* Patch up the ORDER BY clause
92251 op = p->op;
92252 pPrior = p->pPrior;
92253 assert( pPrior->pOrderBy==0 );
92254 pOrderBy = p->pOrderBy;
92255 assert( pOrderBy );
92256 nOrderBy = pOrderBy->nExpr;
92258 /* For operators other than UNION ALL we have to make sure that
92259 ** the ORDER BY clause covers every term of the result set. Add
92260 ** terms to the ORDER BY clause as necessary.
92262 if( op!=TK_ALL ){
92263 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
92264 struct ExprList_item *pItem;
92265 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
92266 assert( pItem->iCol>0 );
92267 if( pItem->iCol==i ) break;
92269 if( j==nOrderBy ){
92270 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
92271 if( pNew==0 ) return SQLITE_NOMEM;
92272 pNew->flags |= EP_IntValue;
92273 pNew->u.iValue = i;
92274 pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
92275 pOrderBy->a[nOrderBy++].iCol = (u16)i;
92280 /* Compute the comparison permutation and keyinfo that is used with
92281 ** the permutation used to determine if the next
92282 ** row of results comes from selectA or selectB. Also add explicit
92283 ** collations to the ORDER BY clause terms so that when the subqueries
92284 ** to the right and the left are evaluated, they use the correct
92285 ** collation.
92287 aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
92288 if( aPermute ){
92289 struct ExprList_item *pItem;
92290 for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
92291 assert( pItem->iCol>0 && pItem->iCol<=p->pEList->nExpr );
92292 aPermute[i] = pItem->iCol - 1;
92294 pKeyMerge =
92295 sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
92296 if( pKeyMerge ){
92297 pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
92298 pKeyMerge->nField = (u16)nOrderBy;
92299 pKeyMerge->enc = ENC(db);
92300 for(i=0; i<nOrderBy; i++){
92301 CollSeq *pColl;
92302 Expr *pTerm = pOrderBy->a[i].pExpr;
92303 if( pTerm->flags & EP_ExpCollate ){
92304 pColl = pTerm->pColl;
92305 }else{
92306 pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
92307 pTerm->flags |= EP_ExpCollate;
92308 pTerm->pColl = pColl;
92310 pKeyMerge->aColl[i] = pColl;
92311 pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
92314 }else{
92315 pKeyMerge = 0;
92318 /* Reattach the ORDER BY clause to the query.
92320 p->pOrderBy = pOrderBy;
92321 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
92323 /* Allocate a range of temporary registers and the KeyInfo needed
92324 ** for the logic that removes duplicate result rows when the
92325 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
92327 if( op==TK_ALL ){
92328 regPrev = 0;
92329 }else{
92330 int nExpr = p->pEList->nExpr;
92331 assert( nOrderBy>=nExpr || db->mallocFailed );
92332 regPrev = sqlite3GetTempRange(pParse, nExpr+1);
92333 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
92334 pKeyDup = sqlite3DbMallocZero(db,
92335 sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
92336 if( pKeyDup ){
92337 pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
92338 pKeyDup->nField = (u16)nExpr;
92339 pKeyDup->enc = ENC(db);
92340 for(i=0; i<nExpr; i++){
92341 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
92342 pKeyDup->aSortOrder[i] = 0;
92347 /* Separate the left and the right query from one another
92349 p->pPrior = 0;
92350 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
92351 if( pPrior->pPrior==0 ){
92352 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
92355 /* Compute the limit registers */
92356 computeLimitRegisters(pParse, p, labelEnd);
92357 if( p->iLimit && op==TK_ALL ){
92358 regLimitA = ++pParse->nMem;
92359 regLimitB = ++pParse->nMem;
92360 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
92361 regLimitA);
92362 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
92363 }else{
92364 regLimitA = regLimitB = 0;
92366 sqlite3ExprDelete(db, p->pLimit);
92367 p->pLimit = 0;
92368 sqlite3ExprDelete(db, p->pOffset);
92369 p->pOffset = 0;
92371 regAddrA = ++pParse->nMem;
92372 regEofA = ++pParse->nMem;
92373 regAddrB = ++pParse->nMem;
92374 regEofB = ++pParse->nMem;
92375 regOutA = ++pParse->nMem;
92376 regOutB = ++pParse->nMem;
92377 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
92378 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
92380 /* Jump past the various subroutines and coroutines to the main
92381 ** merge loop
92383 j1 = sqlite3VdbeAddOp0(v, OP_Goto);
92384 addrSelectA = sqlite3VdbeCurrentAddr(v);
92387 /* Generate a coroutine to evaluate the SELECT statement to the
92388 ** left of the compound operator - the "A" select.
92390 VdbeNoopComment((v, "Begin coroutine for left SELECT"));
92391 pPrior->iLimit = regLimitA;
92392 explainSetInteger(iSub1, pParse->iNextSelectId);
92393 sqlite3Select(pParse, pPrior, &destA);
92394 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
92395 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92396 VdbeNoopComment((v, "End coroutine for left SELECT"));
92398 /* Generate a coroutine to evaluate the SELECT statement on
92399 ** the right - the "B" select
92401 addrSelectB = sqlite3VdbeCurrentAddr(v);
92402 VdbeNoopComment((v, "Begin coroutine for right SELECT"));
92403 savedLimit = p->iLimit;
92404 savedOffset = p->iOffset;
92405 p->iLimit = regLimitB;
92406 p->iOffset = 0;
92407 explainSetInteger(iSub2, pParse->iNextSelectId);
92408 sqlite3Select(pParse, p, &destB);
92409 p->iLimit = savedLimit;
92410 p->iOffset = savedOffset;
92411 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
92412 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92413 VdbeNoopComment((v, "End coroutine for right SELECT"));
92415 /* Generate a subroutine that outputs the current row of the A
92416 ** select as the next output row of the compound select.
92418 VdbeNoopComment((v, "Output routine for A"));
92419 addrOutA = generateOutputSubroutine(pParse,
92420 p, &destA, pDest, regOutA,
92421 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
92423 /* Generate a subroutine that outputs the current row of the B
92424 ** select as the next output row of the compound select.
92426 if( op==TK_ALL || op==TK_UNION ){
92427 VdbeNoopComment((v, "Output routine for B"));
92428 addrOutB = generateOutputSubroutine(pParse,
92429 p, &destB, pDest, regOutB,
92430 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
92433 /* Generate a subroutine to run when the results from select A
92434 ** are exhausted and only data in select B remains.
92436 VdbeNoopComment((v, "eof-A subroutine"));
92437 if( op==TK_EXCEPT || op==TK_INTERSECT ){
92438 addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
92439 }else{
92440 addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
92441 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92442 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92443 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
92444 p->nSelectRow += pPrior->nSelectRow;
92447 /* Generate a subroutine to run when the results from select B
92448 ** are exhausted and only data in select A remains.
92450 if( op==TK_INTERSECT ){
92451 addrEofB = addrEofA;
92452 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
92453 }else{
92454 VdbeNoopComment((v, "eof-B subroutine"));
92455 addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
92456 sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92457 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92458 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
92461 /* Generate code to handle the case of A<B
92463 VdbeNoopComment((v, "A-lt-B subroutine"));
92464 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92465 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92466 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92467 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92469 /* Generate code to handle the case of A==B
92471 if( op==TK_ALL ){
92472 addrAeqB = addrAltB;
92473 }else if( op==TK_INTERSECT ){
92474 addrAeqB = addrAltB;
92475 addrAltB++;
92476 }else{
92477 VdbeNoopComment((v, "A-eq-B subroutine"));
92478 addrAeqB =
92479 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92480 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92481 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92484 /* Generate code to handle the case of A>B
92486 VdbeNoopComment((v, "A-gt-B subroutine"));
92487 addrAgtB = sqlite3VdbeCurrentAddr(v);
92488 if( op==TK_ALL || op==TK_UNION ){
92489 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92491 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92492 sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92493 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92495 /* This code runs once to initialize everything.
92497 sqlite3VdbeJumpHere(v, j1);
92498 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
92499 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
92500 sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
92501 sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
92502 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92503 sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92505 /* Implement the main merge loop
92507 sqlite3VdbeResolveLabel(v, labelCmpr);
92508 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
92509 sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
92510 (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
92511 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
92513 /* Release temporary registers
92515 if( regPrev ){
92516 sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
92519 /* Jump to the this point in order to terminate the query.
92521 sqlite3VdbeResolveLabel(v, labelEnd);
92523 /* Set the number of output columns
92525 if( pDest->eDest==SRT_Output ){
92526 Select *pFirst = pPrior;
92527 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
92528 generateColumnNames(pParse, 0, pFirst->pEList);
92531 /* Reassembly the compound query so that it will be freed correctly
92532 ** by the calling function */
92533 if( p->pPrior ){
92534 sqlite3SelectDelete(db, p->pPrior);
92536 p->pPrior = pPrior;
92538 /*** TBD: Insert subroutine calls to close cursors on incomplete
92539 **** subqueries ****/
92540 explainComposite(pParse, p->op, iSub1, iSub2, 0);
92541 return SQLITE_OK;
92543 #endif
92545 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
92546 /* Forward Declarations */
92547 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
92548 static void substSelect(sqlite3*, Select *, int, ExprList *);
92551 ** Scan through the expression pExpr. Replace every reference to
92552 ** a column in table number iTable with a copy of the iColumn-th
92553 ** entry in pEList. (But leave references to the ROWID column
92554 ** unchanged.)
92556 ** This routine is part of the flattening procedure. A subquery
92557 ** whose result set is defined by pEList appears as entry in the
92558 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
92559 ** FORM clause entry is iTable. This routine make the necessary
92560 ** changes to pExpr so that it refers directly to the source table
92561 ** of the subquery rather the result set of the subquery.
92563 static Expr *substExpr(
92564 sqlite3 *db, /* Report malloc errors to this connection */
92565 Expr *pExpr, /* Expr in which substitution occurs */
92566 int iTable, /* Table to be substituted */
92567 ExprList *pEList /* Substitute expressions */
92569 if( pExpr==0 ) return 0;
92570 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
92571 if( pExpr->iColumn<0 ){
92572 pExpr->op = TK_NULL;
92573 }else{
92574 Expr *pNew;
92575 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
92576 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
92577 pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
92578 if( pNew && pExpr->pColl ){
92579 pNew->pColl = pExpr->pColl;
92581 sqlite3ExprDelete(db, pExpr);
92582 pExpr = pNew;
92584 }else{
92585 pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
92586 pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
92587 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
92588 substSelect(db, pExpr->x.pSelect, iTable, pEList);
92589 }else{
92590 substExprList(db, pExpr->x.pList, iTable, pEList);
92593 return pExpr;
92595 static void substExprList(
92596 sqlite3 *db, /* Report malloc errors here */
92597 ExprList *pList, /* List to scan and in which to make substitutes */
92598 int iTable, /* Table to be substituted */
92599 ExprList *pEList /* Substitute values */
92601 int i;
92602 if( pList==0 ) return;
92603 for(i=0; i<pList->nExpr; i++){
92604 pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
92607 static void substSelect(
92608 sqlite3 *db, /* Report malloc errors here */
92609 Select *p, /* SELECT statement in which to make substitutions */
92610 int iTable, /* Table to be replaced */
92611 ExprList *pEList /* Substitute values */
92613 SrcList *pSrc;
92614 struct SrcList_item *pItem;
92615 int i;
92616 if( !p ) return;
92617 substExprList(db, p->pEList, iTable, pEList);
92618 substExprList(db, p->pGroupBy, iTable, pEList);
92619 substExprList(db, p->pOrderBy, iTable, pEList);
92620 p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
92621 p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
92622 substSelect(db, p->pPrior, iTable, pEList);
92623 pSrc = p->pSrc;
92624 assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
92625 if( ALWAYS(pSrc) ){
92626 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
92627 substSelect(db, pItem->pSelect, iTable, pEList);
92631 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
92633 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
92635 ** This routine attempts to flatten subqueries in order to speed
92636 ** execution. It returns 1 if it makes changes and 0 if no flattening
92637 ** occurs.
92639 ** To understand the concept of flattening, consider the following
92640 ** query:
92642 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
92644 ** The default way of implementing this query is to execute the
92645 ** subquery first and store the results in a temporary table, then
92646 ** run the outer query on that temporary table. This requires two
92647 ** passes over the data. Furthermore, because the temporary table
92648 ** has no indices, the WHERE clause on the outer query cannot be
92649 ** optimized.
92651 ** This routine attempts to rewrite queries such as the above into
92652 ** a single flat select, like this:
92654 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
92656 ** The code generated for this simpification gives the same result
92657 ** but only has to scan the data once. And because indices might
92658 ** exist on the table t1, a complete scan of the data might be
92659 ** avoided.
92661 ** Flattening is only attempted if all of the following are true:
92663 ** (1) The subquery and the outer query do not both use aggregates.
92665 ** (2) The subquery is not an aggregate or the outer query is not a join.
92667 ** (3) The subquery is not the right operand of a left outer join
92668 ** (Originally ticket #306. Strengthened by ticket #3300)
92670 ** (4) The subquery is not DISTINCT.
92672 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
92673 ** sub-queries that were excluded from this optimization. Restriction
92674 ** (4) has since been expanded to exclude all DISTINCT subqueries.
92676 ** (6) The subquery does not use aggregates or the outer query is not
92677 ** DISTINCT.
92679 ** (7) The subquery has a FROM clause.
92681 ** (8) The subquery does not use LIMIT or the outer query is not a join.
92683 ** (9) The subquery does not use LIMIT or the outer query does not use
92684 ** aggregates.
92686 ** (10) The subquery does not use aggregates or the outer query does not
92687 ** use LIMIT.
92689 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
92691 ** (**) Not implemented. Subsumed into restriction (3). Was previously
92692 ** a separate restriction deriving from ticket #350.
92694 ** (13) The subquery and outer query do not both use LIMIT.
92696 ** (14) The subquery does not use OFFSET.
92698 ** (15) The outer query is not part of a compound select or the
92699 ** subquery does not have a LIMIT clause.
92700 ** (See ticket #2339 and ticket [02a8e81d44]).
92702 ** (16) The outer query is not an aggregate or the subquery does
92703 ** not contain ORDER BY. (Ticket #2942) This used to not matter
92704 ** until we introduced the group_concat() function.
92706 ** (17) The sub-query is not a compound select, or it is a UNION ALL
92707 ** compound clause made up entirely of non-aggregate queries, and
92708 ** the parent query:
92710 ** * is not itself part of a compound select,
92711 ** * is not an aggregate or DISTINCT query, and
92712 ** * has no other tables or sub-selects in the FROM clause.
92714 ** The parent and sub-query may contain WHERE clauses. Subject to
92715 ** rules (11), (13) and (14), they may also contain ORDER BY,
92716 ** LIMIT and OFFSET clauses.
92718 ** (18) If the sub-query is a compound select, then all terms of the
92719 ** ORDER by clause of the parent must be simple references to
92720 ** columns of the sub-query.
92722 ** (19) The subquery does not use LIMIT or the outer query does not
92723 ** have a WHERE clause.
92725 ** (20) If the sub-query is a compound select, then it must not use
92726 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
92727 ** somewhat by saying that the terms of the ORDER BY clause must
92728 ** appear as unmodified result columns in the outer query. But
92729 ** have other optimizations in mind to deal with that case.
92731 ** (21) The subquery does not use LIMIT or the outer query is not
92732 ** DISTINCT. (See ticket [752e1646fc]).
92734 ** In this routine, the "p" parameter is a pointer to the outer query.
92735 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
92736 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
92738 ** If flattening is not attempted, this routine is a no-op and returns 0.
92739 ** If flattening is attempted this routine returns 1.
92741 ** All of the expression analysis must occur on both the outer query and
92742 ** the subquery before this routine runs.
92744 static int flattenSubquery(
92745 Parse *pParse, /* Parsing context */
92746 Select *p, /* The parent or outer SELECT statement */
92747 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
92748 int isAgg, /* True if outer SELECT uses aggregate functions */
92749 int subqueryIsAgg /* True if the subquery uses aggregate functions */
92751 const char *zSavedAuthContext = pParse->zAuthContext;
92752 Select *pParent;
92753 Select *pSub; /* The inner query or "subquery" */
92754 Select *pSub1; /* Pointer to the rightmost select in sub-query */
92755 SrcList *pSrc; /* The FROM clause of the outer query */
92756 SrcList *pSubSrc; /* The FROM clause of the subquery */
92757 ExprList *pList; /* The result set of the outer query */
92758 int iParent; /* VDBE cursor number of the pSub result set temp table */
92759 int i; /* Loop counter */
92760 Expr *pWhere; /* The WHERE clause */
92761 struct SrcList_item *pSubitem; /* The subquery */
92762 sqlite3 *db = pParse->db;
92764 /* Check to see if flattening is permitted. Return 0 if not.
92766 assert( p!=0 );
92767 assert( p->pPrior==0 ); /* Unable to flatten compound queries */
92768 if( db->flags & SQLITE_QueryFlattener ) return 0;
92769 pSrc = p->pSrc;
92770 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
92771 pSubitem = &pSrc->a[iFrom];
92772 iParent = pSubitem->iCursor;
92773 pSub = pSubitem->pSelect;
92774 assert( pSub!=0 );
92775 if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
92776 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
92777 pSubSrc = pSub->pSrc;
92778 assert( pSubSrc );
92779 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
92780 ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
92781 ** because they could be computed at compile-time. But when LIMIT and OFFSET
92782 ** became arbitrary expressions, we were forced to add restrictions (13)
92783 ** and (14). */
92784 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
92785 if( pSub->pOffset ) return 0; /* Restriction (14) */
92786 if( p->pRightmost && pSub->pLimit ){
92787 return 0; /* Restriction (15) */
92789 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
92790 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
92791 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
92792 return 0; /* Restrictions (8)(9) */
92794 if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
92795 return 0; /* Restriction (6) */
92797 if( p->pOrderBy && pSub->pOrderBy ){
92798 return 0; /* Restriction (11) */
92800 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
92801 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
92802 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
92803 return 0; /* Restriction (21) */
92806 /* OBSOLETE COMMENT 1:
92807 ** Restriction 3: If the subquery is a join, make sure the subquery is
92808 ** not used as the right operand of an outer join. Examples of why this
92809 ** is not allowed:
92811 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
92813 ** If we flatten the above, we would get
92815 ** (t1 LEFT OUTER JOIN t2) JOIN t3
92817 ** which is not at all the same thing.
92819 ** OBSOLETE COMMENT 2:
92820 ** Restriction 12: If the subquery is the right operand of a left outer
92821 ** join, make sure the subquery has no WHERE clause.
92822 ** An examples of why this is not allowed:
92824 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
92826 ** If we flatten the above, we would get
92828 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
92830 ** But the t2.x>0 test will always fail on a NULL row of t2, which
92831 ** effectively converts the OUTER JOIN into an INNER JOIN.
92833 ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
92834 ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
92835 ** is fraught with danger. Best to avoid the whole thing. If the
92836 ** subquery is the right term of a LEFT JOIN, then do not flatten.
92838 if( (pSubitem->jointype & JT_OUTER)!=0 ){
92839 return 0;
92842 /* Restriction 17: If the sub-query is a compound SELECT, then it must
92843 ** use only the UNION ALL operator. And none of the simple select queries
92844 ** that make up the compound SELECT are allowed to be aggregate or distinct
92845 ** queries.
92847 if( pSub->pPrior ){
92848 if( pSub->pOrderBy ){
92849 return 0; /* Restriction 20 */
92851 if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
92852 return 0;
92854 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
92855 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
92856 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
92857 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
92858 || (pSub1->pPrior && pSub1->op!=TK_ALL)
92859 || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
92861 return 0;
92865 /* Restriction 18. */
92866 if( p->pOrderBy ){
92867 int ii;
92868 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
92869 if( p->pOrderBy->a[ii].iCol==0 ) return 0;
92874 /***** If we reach this point, flattening is permitted. *****/
92876 /* Authorize the subquery */
92877 pParse->zAuthContext = pSubitem->zName;
92878 sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
92879 pParse->zAuthContext = zSavedAuthContext;
92881 /* If the sub-query is a compound SELECT statement, then (by restrictions
92882 ** 17 and 18 above) it must be a UNION ALL and the parent query must
92883 ** be of the form:
92885 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
92887 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
92888 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
92889 ** OFFSET clauses and joins them to the left-hand-side of the original
92890 ** using UNION ALL operators. In this case N is the number of simple
92891 ** select statements in the compound sub-query.
92893 ** Example:
92895 ** SELECT a+1 FROM (
92896 ** SELECT x FROM tab
92897 ** UNION ALL
92898 ** SELECT y FROM tab
92899 ** UNION ALL
92900 ** SELECT abs(z*2) FROM tab2
92901 ** ) WHERE a!=5 ORDER BY 1
92903 ** Transformed into:
92905 ** SELECT x+1 FROM tab WHERE x+1!=5
92906 ** UNION ALL
92907 ** SELECT y+1 FROM tab WHERE y+1!=5
92908 ** UNION ALL
92909 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
92910 ** ORDER BY 1
92912 ** We call this the "compound-subquery flattening".
92914 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
92915 Select *pNew;
92916 ExprList *pOrderBy = p->pOrderBy;
92917 Expr *pLimit = p->pLimit;
92918 Select *pPrior = p->pPrior;
92919 p->pOrderBy = 0;
92920 p->pSrc = 0;
92921 p->pPrior = 0;
92922 p->pLimit = 0;
92923 pNew = sqlite3SelectDup(db, p, 0);
92924 p->pLimit = pLimit;
92925 p->pOrderBy = pOrderBy;
92926 p->pSrc = pSrc;
92927 p->op = TK_ALL;
92928 p->pRightmost = 0;
92929 if( pNew==0 ){
92930 pNew = pPrior;
92931 }else{
92932 pNew->pPrior = pPrior;
92933 pNew->pRightmost = 0;
92935 p->pPrior = pNew;
92936 if( db->mallocFailed ) return 1;
92939 /* Begin flattening the iFrom-th entry of the FROM clause
92940 ** in the outer query.
92942 pSub = pSub1 = pSubitem->pSelect;
92944 /* Delete the transient table structure associated with the
92945 ** subquery
92947 sqlite3DbFree(db, pSubitem->zDatabase);
92948 sqlite3DbFree(db, pSubitem->zName);
92949 sqlite3DbFree(db, pSubitem->zAlias);
92950 pSubitem->zDatabase = 0;
92951 pSubitem->zName = 0;
92952 pSubitem->zAlias = 0;
92953 pSubitem->pSelect = 0;
92955 /* Defer deleting the Table object associated with the
92956 ** subquery until code generation is
92957 ** complete, since there may still exist Expr.pTab entries that
92958 ** refer to the subquery even after flattening. Ticket #3346.
92960 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
92962 if( ALWAYS(pSubitem->pTab!=0) ){
92963 Table *pTabToDel = pSubitem->pTab;
92964 if( pTabToDel->nRef==1 ){
92965 Parse *pToplevel = sqlite3ParseToplevel(pParse);
92966 pTabToDel->pNextZombie = pToplevel->pZombieTab;
92967 pToplevel->pZombieTab = pTabToDel;
92968 }else{
92969 pTabToDel->nRef--;
92971 pSubitem->pTab = 0;
92974 /* The following loop runs once for each term in a compound-subquery
92975 ** flattening (as described above). If we are doing a different kind
92976 ** of flattening - a flattening other than a compound-subquery flattening -
92977 ** then this loop only runs once.
92979 ** This loop moves all of the FROM elements of the subquery into the
92980 ** the FROM clause of the outer query. Before doing this, remember
92981 ** the cursor number for the original outer query FROM element in
92982 ** iParent. The iParent cursor will never be used. Subsequent code
92983 ** will scan expressions looking for iParent references and replace
92984 ** those references with expressions that resolve to the subquery FROM
92985 ** elements we are now copying in.
92987 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
92988 int nSubSrc;
92989 u8 jointype = 0;
92990 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
92991 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
92992 pSrc = pParent->pSrc; /* FROM clause of the outer query */
92994 if( pSrc ){
92995 assert( pParent==p ); /* First time through the loop */
92996 jointype = pSubitem->jointype;
92997 }else{
92998 assert( pParent!=p ); /* 2nd and subsequent times through the loop */
92999 pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
93000 if( pSrc==0 ){
93001 assert( db->mallocFailed );
93002 break;
93006 /* The subquery uses a single slot of the FROM clause of the outer
93007 ** query. If the subquery has more than one element in its FROM clause,
93008 ** then expand the outer query to make space for it to hold all elements
93009 ** of the subquery.
93011 ** Example:
93013 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
93015 ** The outer query has 3 slots in its FROM clause. One slot of the
93016 ** outer query (the middle slot) is used by the subquery. The next
93017 ** block of code will expand the out query to 4 slots. The middle
93018 ** slot is expanded to two slots in order to make space for the
93019 ** two elements in the FROM clause of the subquery.
93021 if( nSubSrc>1 ){
93022 pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
93023 if( db->mallocFailed ){
93024 break;
93028 /* Transfer the FROM clause terms from the subquery into the
93029 ** outer query.
93031 for(i=0; i<nSubSrc; i++){
93032 sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
93033 pSrc->a[i+iFrom] = pSubSrc->a[i];
93034 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
93036 pSrc->a[iFrom].jointype = jointype;
93038 /* Now begin substituting subquery result set expressions for
93039 ** references to the iParent in the outer query.
93041 ** Example:
93043 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
93044 ** \ \_____________ subquery __________/ /
93045 ** \_____________________ outer query ______________________________/
93047 ** We look at every expression in the outer query and every place we see
93048 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
93050 pList = pParent->pEList;
93051 for(i=0; i<pList->nExpr; i++){
93052 if( pList->a[i].zName==0 ){
93053 const char *zSpan = pList->a[i].zSpan;
93054 if( ALWAYS(zSpan) ){
93055 pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
93059 substExprList(db, pParent->pEList, iParent, pSub->pEList);
93060 if( isAgg ){
93061 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
93062 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
93064 if( pSub->pOrderBy ){
93065 assert( pParent->pOrderBy==0 );
93066 pParent->pOrderBy = pSub->pOrderBy;
93067 pSub->pOrderBy = 0;
93068 }else if( pParent->pOrderBy ){
93069 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
93071 if( pSub->pWhere ){
93072 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
93073 }else{
93074 pWhere = 0;
93076 if( subqueryIsAgg ){
93077 assert( pParent->pHaving==0 );
93078 pParent->pHaving = pParent->pWhere;
93079 pParent->pWhere = pWhere;
93080 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
93081 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
93082 sqlite3ExprDup(db, pSub->pHaving, 0));
93083 assert( pParent->pGroupBy==0 );
93084 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
93085 }else{
93086 pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
93087 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
93090 /* The flattened query is distinct if either the inner or the
93091 ** outer query is distinct.
93093 pParent->selFlags |= pSub->selFlags & SF_Distinct;
93096 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
93098 ** One is tempted to try to add a and b to combine the limits. But this
93099 ** does not work if either limit is negative.
93101 if( pSub->pLimit ){
93102 pParent->pLimit = pSub->pLimit;
93103 pSub->pLimit = 0;
93107 /* Finially, delete what is left of the subquery and return
93108 ** success.
93110 sqlite3SelectDelete(db, pSub1);
93112 return 1;
93114 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
93117 ** Analyze the SELECT statement passed as an argument to see if it
93118 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
93119 ** it is, or 0 otherwise. At present, a query is considered to be
93120 ** a min()/max() query if:
93122 ** 1. There is a single object in the FROM clause.
93124 ** 2. There is a single expression in the result set, and it is
93125 ** either min(x) or max(x), where x is a column reference.
93127 static u8 minMaxQuery(Select *p){
93128 Expr *pExpr;
93129 ExprList *pEList = p->pEList;
93131 if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
93132 pExpr = pEList->a[0].pExpr;
93133 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
93134 if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
93135 pEList = pExpr->x.pList;
93136 if( pEList==0 || pEList->nExpr!=1 ) return 0;
93137 if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
93138 assert( !ExprHasProperty(pExpr, EP_IntValue) );
93139 if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
93140 return WHERE_ORDERBY_MIN;
93141 }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
93142 return WHERE_ORDERBY_MAX;
93144 return WHERE_ORDERBY_NORMAL;
93148 ** The select statement passed as the first argument is an aggregate query.
93149 ** The second argment is the associated aggregate-info object. This
93150 ** function tests if the SELECT is of the form:
93152 ** SELECT count(*) FROM <tbl>
93154 ** where table is a database table, not a sub-select or view. If the query
93155 ** does match this pattern, then a pointer to the Table object representing
93156 ** <tbl> is returned. Otherwise, 0 is returned.
93158 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
93159 Table *pTab;
93160 Expr *pExpr;
93162 assert( !p->pGroupBy );
93164 if( p->pWhere || p->pEList->nExpr!=1
93165 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
93167 return 0;
93169 pTab = p->pSrc->a[0].pTab;
93170 pExpr = p->pEList->a[0].pExpr;
93171 assert( pTab && !pTab->pSelect && pExpr );
93173 if( IsVirtual(pTab) ) return 0;
93174 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
93175 if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
93176 if( pExpr->flags&EP_Distinct ) return 0;
93178 return pTab;
93182 ** If the source-list item passed as an argument was augmented with an
93183 ** INDEXED BY clause, then try to locate the specified index. If there
93184 ** was such a clause and the named index cannot be found, return
93185 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
93186 ** pFrom->pIndex and return SQLITE_OK.
93188 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
93189 if( pFrom->pTab && pFrom->zIndex ){
93190 Table *pTab = pFrom->pTab;
93191 char *zIndex = pFrom->zIndex;
93192 Index *pIdx;
93193 for(pIdx=pTab->pIndex;
93194 pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
93195 pIdx=pIdx->pNext
93197 if( !pIdx ){
93198 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
93199 pParse->checkSchema = 1;
93200 return SQLITE_ERROR;
93202 pFrom->pIndex = pIdx;
93204 return SQLITE_OK;
93208 ** This routine is a Walker callback for "expanding" a SELECT statement.
93209 ** "Expanding" means to do the following:
93211 ** (1) Make sure VDBE cursor numbers have been assigned to every
93212 ** element of the FROM clause.
93214 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
93215 ** defines FROM clause. When views appear in the FROM clause,
93216 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
93217 ** that implements the view. A copy is made of the view's SELECT
93218 ** statement so that we can freely modify or delete that statement
93219 ** without worrying about messing up the presistent representation
93220 ** of the view.
93222 ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
93223 ** on joins and the ON and USING clause of joins.
93225 ** (4) Scan the list of columns in the result set (pEList) looking
93226 ** for instances of the "*" operator or the TABLE.* operator.
93227 ** If found, expand each "*" to be every column in every table
93228 ** and TABLE.* to be every column in TABLE.
93231 static int selectExpander(Walker *pWalker, Select *p){
93232 Parse *pParse = pWalker->pParse;
93233 int i, j, k;
93234 SrcList *pTabList;
93235 ExprList *pEList;
93236 struct SrcList_item *pFrom;
93237 sqlite3 *db = pParse->db;
93239 if( db->mallocFailed ){
93240 return WRC_Abort;
93242 if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
93243 return WRC_Prune;
93245 p->selFlags |= SF_Expanded;
93246 pTabList = p->pSrc;
93247 pEList = p->pEList;
93249 /* Make sure cursor numbers have been assigned to all entries in
93250 ** the FROM clause of the SELECT statement.
93252 sqlite3SrcListAssignCursors(pParse, pTabList);
93254 /* Look up every table named in the FROM clause of the select. If
93255 ** an entry of the FROM clause is a subquery instead of a table or view,
93256 ** then create a transient table structure to describe the subquery.
93258 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93259 Table *pTab;
93260 if( pFrom->pTab!=0 ){
93261 /* This statement has already been prepared. There is no need
93262 ** to go further. */
93263 assert( i==0 );
93264 return WRC_Prune;
93266 if( pFrom->zName==0 ){
93267 #ifndef SQLITE_OMIT_SUBQUERY
93268 Select *pSel = pFrom->pSelect;
93269 /* A sub-query in the FROM clause of a SELECT */
93270 assert( pSel!=0 );
93271 assert( pFrom->pTab==0 );
93272 sqlite3WalkSelect(pWalker, pSel);
93273 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
93274 if( pTab==0 ) return WRC_Abort;
93275 pTab->nRef = 1;
93276 pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
93277 while( pSel->pPrior ){ pSel = pSel->pPrior; }
93278 selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
93279 pTab->iPKey = -1;
93280 pTab->nRowEst = 1000000;
93281 pTab->tabFlags |= TF_Ephemeral;
93282 #endif
93283 }else{
93284 /* An ordinary table or view name in the FROM clause */
93285 assert( pFrom->pTab==0 );
93286 pFrom->pTab = pTab =
93287 sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
93288 if( pTab==0 ) return WRC_Abort;
93289 pTab->nRef++;
93290 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
93291 if( pTab->pSelect || IsVirtual(pTab) ){
93292 /* We reach here if the named table is a really a view */
93293 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
93294 assert( pFrom->pSelect==0 );
93295 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
93296 sqlite3WalkSelect(pWalker, pFrom->pSelect);
93298 #endif
93301 /* Locate the index named by the INDEXED BY clause, if any. */
93302 if( sqlite3IndexedByLookup(pParse, pFrom) ){
93303 return WRC_Abort;
93307 /* Process NATURAL keywords, and ON and USING clauses of joins.
93309 if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
93310 return WRC_Abort;
93313 /* For every "*" that occurs in the column list, insert the names of
93314 ** all columns in all tables. And for every TABLE.* insert the names
93315 ** of all columns in TABLE. The parser inserted a special expression
93316 ** with the TK_ALL operator for each "*" that it found in the column list.
93317 ** The following code just has to locate the TK_ALL expressions and expand
93318 ** each one to the list of all columns in all tables.
93320 ** The first loop just checks to see if there are any "*" operators
93321 ** that need expanding.
93323 for(k=0; k<pEList->nExpr; k++){
93324 Expr *pE = pEList->a[k].pExpr;
93325 if( pE->op==TK_ALL ) break;
93326 assert( pE->op!=TK_DOT || pE->pRight!=0 );
93327 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
93328 if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
93330 if( k<pEList->nExpr ){
93332 ** If we get here it means the result set contains one or more "*"
93333 ** operators that need to be expanded. Loop through each expression
93334 ** in the result set and expand them one by one.
93336 struct ExprList_item *a = pEList->a;
93337 ExprList *pNew = 0;
93338 int flags = pParse->db->flags;
93339 int longNames = (flags & SQLITE_FullColNames)!=0
93340 && (flags & SQLITE_ShortColNames)==0;
93342 for(k=0; k<pEList->nExpr; k++){
93343 Expr *pE = a[k].pExpr;
93344 assert( pE->op!=TK_DOT || pE->pRight!=0 );
93345 if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
93346 /* This particular expression does not need to be expanded.
93348 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
93349 if( pNew ){
93350 pNew->a[pNew->nExpr-1].zName = a[k].zName;
93351 pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
93352 a[k].zName = 0;
93353 a[k].zSpan = 0;
93355 a[k].pExpr = 0;
93356 }else{
93357 /* This expression is a "*" or a "TABLE.*" and needs to be
93358 ** expanded. */
93359 int tableSeen = 0; /* Set to 1 when TABLE matches */
93360 char *zTName; /* text of name of TABLE */
93361 if( pE->op==TK_DOT ){
93362 assert( pE->pLeft!=0 );
93363 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
93364 zTName = pE->pLeft->u.zToken;
93365 }else{
93366 zTName = 0;
93368 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93369 Table *pTab = pFrom->pTab;
93370 char *zTabName = pFrom->zAlias;
93371 if( zTabName==0 ){
93372 zTabName = pTab->zName;
93374 if( db->mallocFailed ) break;
93375 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
93376 continue;
93378 tableSeen = 1;
93379 for(j=0; j<pTab->nCol; j++){
93380 Expr *pExpr, *pRight;
93381 char *zName = pTab->aCol[j].zName;
93382 char *zColname; /* The computed column name */
93383 char *zToFree; /* Malloced string that needs to be freed */
93384 Token sColname; /* Computed column name as a token */
93386 /* If a column is marked as 'hidden' (currently only possible
93387 ** for virtual tables), do not include it in the expanded
93388 ** result-set list.
93390 if( IsHiddenColumn(&pTab->aCol[j]) ){
93391 assert(IsVirtual(pTab));
93392 continue;
93395 if( i>0 && zTName==0 ){
93396 if( (pFrom->jointype & JT_NATURAL)!=0
93397 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
93399 /* In a NATURAL join, omit the join columns from the
93400 ** table to the right of the join */
93401 continue;
93403 if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
93404 /* In a join with a USING clause, omit columns in the
93405 ** using clause from the table on the right. */
93406 continue;
93409 pRight = sqlite3Expr(db, TK_ID, zName);
93410 zColname = zName;
93411 zToFree = 0;
93412 if( longNames || pTabList->nSrc>1 ){
93413 Expr *pLeft;
93414 pLeft = sqlite3Expr(db, TK_ID, zTabName);
93415 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
93416 if( longNames ){
93417 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
93418 zToFree = zColname;
93420 }else{
93421 pExpr = pRight;
93423 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
93424 sColname.z = zColname;
93425 sColname.n = sqlite3Strlen30(zColname);
93426 sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
93427 sqlite3DbFree(db, zToFree);
93430 if( !tableSeen ){
93431 if( zTName ){
93432 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
93433 }else{
93434 sqlite3ErrorMsg(pParse, "no tables specified");
93439 sqlite3ExprListDelete(db, pEList);
93440 p->pEList = pNew;
93442 #if SQLITE_MAX_COLUMN
93443 if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
93444 sqlite3ErrorMsg(pParse, "too many columns in result set");
93446 #endif
93447 return WRC_Continue;
93451 ** No-op routine for the parse-tree walker.
93453 ** When this routine is the Walker.xExprCallback then expression trees
93454 ** are walked without any actions being taken at each node. Presumably,
93455 ** when this routine is used for Walker.xExprCallback then
93456 ** Walker.xSelectCallback is set to do something useful for every
93457 ** subquery in the parser tree.
93459 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
93460 UNUSED_PARAMETER2(NotUsed, NotUsed2);
93461 return WRC_Continue;
93465 ** This routine "expands" a SELECT statement and all of its subqueries.
93466 ** For additional information on what it means to "expand" a SELECT
93467 ** statement, see the comment on the selectExpand worker callback above.
93469 ** Expanding a SELECT statement is the first step in processing a
93470 ** SELECT statement. The SELECT statement must be expanded before
93471 ** name resolution is performed.
93473 ** If anything goes wrong, an error message is written into pParse.
93474 ** The calling function can detect the problem by looking at pParse->nErr
93475 ** and/or pParse->db->mallocFailed.
93477 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
93478 Walker w;
93479 w.xSelectCallback = selectExpander;
93480 w.xExprCallback = exprWalkNoop;
93481 w.pParse = pParse;
93482 sqlite3WalkSelect(&w, pSelect);
93486 #ifndef SQLITE_OMIT_SUBQUERY
93488 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
93489 ** interface.
93491 ** For each FROM-clause subquery, add Column.zType and Column.zColl
93492 ** information to the Table structure that represents the result set
93493 ** of that subquery.
93495 ** The Table structure that represents the result set was constructed
93496 ** by selectExpander() but the type and collation information was omitted
93497 ** at that point because identifiers had not yet been resolved. This
93498 ** routine is called after identifier resolution.
93500 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
93501 Parse *pParse;
93502 int i;
93503 SrcList *pTabList;
93504 struct SrcList_item *pFrom;
93506 assert( p->selFlags & SF_Resolved );
93507 if( (p->selFlags & SF_HasTypeInfo)==0 ){
93508 p->selFlags |= SF_HasTypeInfo;
93509 pParse = pWalker->pParse;
93510 pTabList = p->pSrc;
93511 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93512 Table *pTab = pFrom->pTab;
93513 if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
93514 /* A sub-query in the FROM clause of a SELECT */
93515 Select *pSel = pFrom->pSelect;
93516 assert( pSel );
93517 while( pSel->pPrior ) pSel = pSel->pPrior;
93518 selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
93522 return WRC_Continue;
93524 #endif
93528 ** This routine adds datatype and collating sequence information to
93529 ** the Table structures of all FROM-clause subqueries in a
93530 ** SELECT statement.
93532 ** Use this routine after name resolution.
93534 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
93535 #ifndef SQLITE_OMIT_SUBQUERY
93536 Walker w;
93537 w.xSelectCallback = selectAddSubqueryTypeInfo;
93538 w.xExprCallback = exprWalkNoop;
93539 w.pParse = pParse;
93540 sqlite3WalkSelect(&w, pSelect);
93541 #endif
93546 ** This routine sets of a SELECT statement for processing. The
93547 ** following is accomplished:
93549 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
93550 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
93551 ** * ON and USING clauses are shifted into WHERE statements
93552 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
93553 ** * Identifiers in expression are matched to tables.
93555 ** This routine acts recursively on all subqueries within the SELECT.
93557 SQLITE_PRIVATE void sqlite3SelectPrep(
93558 Parse *pParse, /* The parser context */
93559 Select *p, /* The SELECT statement being coded. */
93560 NameContext *pOuterNC /* Name context for container */
93562 sqlite3 *db;
93563 if( NEVER(p==0) ) return;
93564 db = pParse->db;
93565 if( p->selFlags & SF_HasTypeInfo ) return;
93566 sqlite3SelectExpand(pParse, p);
93567 if( pParse->nErr || db->mallocFailed ) return;
93568 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
93569 if( pParse->nErr || db->mallocFailed ) return;
93570 sqlite3SelectAddTypeInfo(pParse, p);
93574 ** Reset the aggregate accumulator.
93576 ** The aggregate accumulator is a set of memory cells that hold
93577 ** intermediate results while calculating an aggregate. This
93578 ** routine simply stores NULLs in all of those memory cells.
93580 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
93581 Vdbe *v = pParse->pVdbe;
93582 int i;
93583 struct AggInfo_func *pFunc;
93584 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
93585 return;
93587 for(i=0; i<pAggInfo->nColumn; i++){
93588 sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
93590 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
93591 sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
93592 if( pFunc->iDistinct>=0 ){
93593 Expr *pE = pFunc->pExpr;
93594 assert( !ExprHasProperty(pE, EP_xIsSelect) );
93595 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
93596 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
93597 "argument");
93598 pFunc->iDistinct = -1;
93599 }else{
93600 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
93601 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
93602 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93609 ** Invoke the OP_AggFinalize opcode for every aggregate function
93610 ** in the AggInfo structure.
93612 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
93613 Vdbe *v = pParse->pVdbe;
93614 int i;
93615 struct AggInfo_func *pF;
93616 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
93617 ExprList *pList = pF->pExpr->x.pList;
93618 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
93619 sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
93620 (void*)pF->pFunc, P4_FUNCDEF);
93625 ** Update the accumulator memory cells for an aggregate based on
93626 ** the current cursor position.
93628 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
93629 Vdbe *v = pParse->pVdbe;
93630 int i;
93631 struct AggInfo_func *pF;
93632 struct AggInfo_col *pC;
93634 pAggInfo->directMode = 1;
93635 sqlite3ExprCacheClear(pParse);
93636 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
93637 int nArg;
93638 int addrNext = 0;
93639 int regAgg;
93640 ExprList *pList = pF->pExpr->x.pList;
93641 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
93642 if( pList ){
93643 nArg = pList->nExpr;
93644 regAgg = sqlite3GetTempRange(pParse, nArg);
93645 sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
93646 }else{
93647 nArg = 0;
93648 regAgg = 0;
93650 if( pF->iDistinct>=0 ){
93651 addrNext = sqlite3VdbeMakeLabel(v);
93652 assert( nArg==1 );
93653 codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
93655 if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
93656 CollSeq *pColl = 0;
93657 struct ExprList_item *pItem;
93658 int j;
93659 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
93660 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
93661 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
93663 if( !pColl ){
93664 pColl = pParse->db->pDfltColl;
93666 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
93668 sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
93669 (void*)pF->pFunc, P4_FUNCDEF);
93670 sqlite3VdbeChangeP5(v, (u8)nArg);
93671 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
93672 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
93673 if( addrNext ){
93674 sqlite3VdbeResolveLabel(v, addrNext);
93675 sqlite3ExprCacheClear(pParse);
93679 /* Before populating the accumulator registers, clear the column cache.
93680 ** Otherwise, if any of the required column values are already present
93681 ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
93682 ** to pC->iMem. But by the time the value is used, the original register
93683 ** may have been used, invalidating the underlying buffer holding the
93684 ** text or blob value. See ticket [883034dcb5].
93686 ** Another solution would be to change the OP_SCopy used to copy cached
93687 ** values to an OP_Copy.
93689 sqlite3ExprCacheClear(pParse);
93690 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
93691 sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
93693 pAggInfo->directMode = 0;
93694 sqlite3ExprCacheClear(pParse);
93698 ** Add a single OP_Explain instruction to the VDBE to explain a simple
93699 ** count(*) query ("SELECT count(*) FROM pTab").
93701 #ifndef SQLITE_OMIT_EXPLAIN
93702 static void explainSimpleCount(
93703 Parse *pParse, /* Parse context */
93704 Table *pTab, /* Table being queried */
93705 Index *pIdx /* Index used to optimize scan, or NULL */
93707 if( pParse->explain==2 ){
93708 char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
93709 pTab->zName,
93710 pIdx ? "USING COVERING INDEX " : "",
93711 pIdx ? pIdx->zName : "",
93712 pTab->nRowEst
93714 sqlite3VdbeAddOp4(
93715 pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
93719 #else
93720 # define explainSimpleCount(a,b,c)
93721 #endif
93724 ** Generate code for the SELECT statement given in the p argument.
93726 ** The results are distributed in various ways depending on the
93727 ** contents of the SelectDest structure pointed to by argument pDest
93728 ** as follows:
93730 ** pDest->eDest Result
93731 ** ------------ -------------------------------------------
93732 ** SRT_Output Generate a row of output (using the OP_ResultRow
93733 ** opcode) for each row in the result set.
93735 ** SRT_Mem Only valid if the result is a single column.
93736 ** Store the first column of the first result row
93737 ** in register pDest->iParm then abandon the rest
93738 ** of the query. This destination implies "LIMIT 1".
93740 ** SRT_Set The result must be a single column. Store each
93741 ** row of result as the key in table pDest->iParm.
93742 ** Apply the affinity pDest->affinity before storing
93743 ** results. Used to implement "IN (SELECT ...)".
93745 ** SRT_Union Store results as a key in a temporary table pDest->iParm.
93747 ** SRT_Except Remove results from the temporary table pDest->iParm.
93749 ** SRT_Table Store results in temporary table pDest->iParm.
93750 ** This is like SRT_EphemTab except that the table
93751 ** is assumed to already be open.
93753 ** SRT_EphemTab Create an temporary table pDest->iParm and store
93754 ** the result there. The cursor is left open after
93755 ** returning. This is like SRT_Table except that
93756 ** this destination uses OP_OpenEphemeral to create
93757 ** the table first.
93759 ** SRT_Coroutine Generate a co-routine that returns a new row of
93760 ** results each time it is invoked. The entry point
93761 ** of the co-routine is stored in register pDest->iParm.
93763 ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result
93764 ** set is not empty.
93766 ** SRT_Discard Throw the results away. This is used by SELECT
93767 ** statements within triggers whose only purpose is
93768 ** the side-effects of functions.
93770 ** This routine returns the number of errors. If any errors are
93771 ** encountered, then an appropriate error message is left in
93772 ** pParse->zErrMsg.
93774 ** This routine does NOT free the Select structure passed in. The
93775 ** calling function needs to do that.
93777 SQLITE_PRIVATE int sqlite3Select(
93778 Parse *pParse, /* The parser context */
93779 Select *p, /* The SELECT statement being coded. */
93780 SelectDest *pDest /* What to do with the query results */
93782 int i, j; /* Loop counters */
93783 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
93784 Vdbe *v; /* The virtual machine under construction */
93785 int isAgg; /* True for select lists like "count(*)" */
93786 ExprList *pEList; /* List of columns to extract. */
93787 SrcList *pTabList; /* List of tables to select from */
93788 Expr *pWhere; /* The WHERE clause. May be NULL */
93789 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
93790 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
93791 Expr *pHaving; /* The HAVING clause. May be NULL */
93792 int isDistinct; /* True if the DISTINCT keyword is present */
93793 int distinct; /* Table to use for the distinct set */
93794 int rc = 1; /* Value to return from this function */
93795 int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
93796 AggInfo sAggInfo; /* Information used by aggregate queries */
93797 int iEnd; /* Address of the end of the query */
93798 sqlite3 *db; /* The database connection */
93800 #ifndef SQLITE_OMIT_EXPLAIN
93801 int iRestoreSelectId = pParse->iSelectId;
93802 pParse->iSelectId = pParse->iNextSelectId++;
93803 #endif
93805 db = pParse->db;
93806 if( p==0 || db->mallocFailed || pParse->nErr ){
93807 return 1;
93809 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
93810 memset(&sAggInfo, 0, sizeof(sAggInfo));
93812 if( IgnorableOrderby(pDest) ){
93813 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
93814 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
93815 /* If ORDER BY makes no difference in the output then neither does
93816 ** DISTINCT so it can be removed too. */
93817 sqlite3ExprListDelete(db, p->pOrderBy);
93818 p->pOrderBy = 0;
93819 p->selFlags &= ~SF_Distinct;
93821 sqlite3SelectPrep(pParse, p, 0);
93822 pOrderBy = p->pOrderBy;
93823 pTabList = p->pSrc;
93824 pEList = p->pEList;
93825 if( pParse->nErr || db->mallocFailed ){
93826 goto select_end;
93828 isAgg = (p->selFlags & SF_Aggregate)!=0;
93829 assert( pEList!=0 );
93831 /* Begin generating code.
93833 v = sqlite3GetVdbe(pParse);
93834 if( v==0 ) goto select_end;
93836 /* If writing to memory or generating a set
93837 ** only a single column may be output.
93839 #ifndef SQLITE_OMIT_SUBQUERY
93840 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
93841 goto select_end;
93843 #endif
93845 /* Generate code for all sub-queries in the FROM clause
93847 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
93848 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
93849 struct SrcList_item *pItem = &pTabList->a[i];
93850 SelectDest dest;
93851 Select *pSub = pItem->pSelect;
93852 int isAggSub;
93854 if( pSub==0 || pItem->isPopulated ) continue;
93856 /* Increment Parse.nHeight by the height of the largest expression
93857 ** tree refered to by this, the parent select. The child select
93858 ** may contain expression trees of at most
93859 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
93860 ** more conservative than necessary, but much easier than enforcing
93861 ** an exact limit.
93863 pParse->nHeight += sqlite3SelectExprHeight(p);
93865 /* Check to see if the subquery can be absorbed into the parent. */
93866 isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
93867 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
93868 if( isAggSub ){
93869 isAgg = 1;
93870 p->selFlags |= SF_Aggregate;
93872 i = -1;
93873 }else{
93874 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
93875 assert( pItem->isPopulated==0 );
93876 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
93877 sqlite3Select(pParse, pSub, &dest);
93878 pItem->isPopulated = 1;
93879 pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
93881 if( /*pParse->nErr ||*/ db->mallocFailed ){
93882 goto select_end;
93884 pParse->nHeight -= sqlite3SelectExprHeight(p);
93885 pTabList = p->pSrc;
93886 if( !IgnorableOrderby(pDest) ){
93887 pOrderBy = p->pOrderBy;
93890 pEList = p->pEList;
93891 #endif
93892 pWhere = p->pWhere;
93893 pGroupBy = p->pGroupBy;
93894 pHaving = p->pHaving;
93895 isDistinct = (p->selFlags & SF_Distinct)!=0;
93897 #ifndef SQLITE_OMIT_COMPOUND_SELECT
93898 /* If there is are a sequence of queries, do the earlier ones first.
93900 if( p->pPrior ){
93901 if( p->pRightmost==0 ){
93902 Select *pLoop, *pRight = 0;
93903 int cnt = 0;
93904 int mxSelect;
93905 for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
93906 pLoop->pRightmost = p;
93907 pLoop->pNext = pRight;
93908 pRight = pLoop;
93910 mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
93911 if( mxSelect && cnt>mxSelect ){
93912 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
93913 goto select_end;
93916 rc = multiSelect(pParse, p, pDest);
93917 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
93918 return rc;
93920 #endif
93922 /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
93923 ** GROUP BY might use an index, DISTINCT never does.
93925 assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
93926 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
93927 p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
93928 pGroupBy = p->pGroupBy;
93929 p->selFlags &= ~SF_Distinct;
93932 /* If there is both a GROUP BY and an ORDER BY clause and they are
93933 ** identical, then disable the ORDER BY clause since the GROUP BY
93934 ** will cause elements to come out in the correct order. This is
93935 ** an optimization - the correct answer should result regardless.
93936 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
93937 ** to disable this optimization for testing purposes.
93939 if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
93940 && (db->flags & SQLITE_GroupByOrder)==0 ){
93941 pOrderBy = 0;
93944 /* If there is an ORDER BY clause, then this sorting
93945 ** index might end up being unused if the data can be
93946 ** extracted in pre-sorted order. If that is the case, then the
93947 ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
93948 ** we figure out that the sorting index is not needed. The addrSortIndex
93949 ** variable is used to facilitate that change.
93951 if( pOrderBy ){
93952 KeyInfo *pKeyInfo;
93953 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
93954 pOrderBy->iECursor = pParse->nTab++;
93955 p->addrOpenEphm[2] = addrSortIndex =
93956 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
93957 pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
93958 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93959 }else{
93960 addrSortIndex = -1;
93963 /* If the output is destined for a temporary table, open that table.
93965 if( pDest->eDest==SRT_EphemTab ){
93966 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
93969 /* Set the limiter.
93971 iEnd = sqlite3VdbeMakeLabel(v);
93972 p->nSelectRow = (double)LARGEST_INT64;
93973 computeLimitRegisters(pParse, p, iEnd);
93975 /* Open a virtual index to use for the distinct set.
93977 if( p->selFlags & SF_Distinct ){
93978 KeyInfo *pKeyInfo;
93979 assert( isAgg || pGroupBy );
93980 distinct = pParse->nTab++;
93981 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
93982 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
93983 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93984 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
93985 }else{
93986 distinct = -1;
93989 /* Aggregate and non-aggregate queries are handled differently */
93990 if( !isAgg && pGroupBy==0 ){
93991 /* This case is for non-aggregate queries
93992 ** Begin the database scan
93994 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
93995 if( pWInfo==0 ) goto select_end;
93996 if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
93998 /* If sorting index that was created by a prior OP_OpenEphemeral
93999 ** instruction ended up not being needed, then change the OP_OpenEphemeral
94000 ** into an OP_Noop.
94002 if( addrSortIndex>=0 && pOrderBy==0 ){
94003 sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
94004 p->addrOpenEphm[2] = -1;
94007 /* Use the standard inner loop
94009 assert(!isDistinct);
94010 selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
94011 pWInfo->iContinue, pWInfo->iBreak);
94013 /* End the database scan loop.
94015 sqlite3WhereEnd(pWInfo);
94016 }else{
94017 /* This is the processing for aggregate queries */
94018 NameContext sNC; /* Name context for processing aggregate information */
94019 int iAMem; /* First Mem address for storing current GROUP BY */
94020 int iBMem; /* First Mem address for previous GROUP BY */
94021 int iUseFlag; /* Mem address holding flag indicating that at least
94022 ** one row of the input to the aggregator has been
94023 ** processed */
94024 int iAbortFlag; /* Mem address which causes query abort if positive */
94025 int groupBySort; /* Rows come from source in GROUP BY order */
94026 int addrEnd; /* End of processing for this SELECT */
94028 /* Remove any and all aliases between the result set and the
94029 ** GROUP BY clause.
94031 if( pGroupBy ){
94032 int k; /* Loop counter */
94033 struct ExprList_item *pItem; /* For looping over expression in a list */
94035 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
94036 pItem->iAlias = 0;
94038 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
94039 pItem->iAlias = 0;
94041 if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
94042 }else{
94043 p->nSelectRow = (double)1;
94047 /* Create a label to jump to when we want to abort the query */
94048 addrEnd = sqlite3VdbeMakeLabel(v);
94050 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
94051 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
94052 ** SELECT statement.
94054 memset(&sNC, 0, sizeof(sNC));
94055 sNC.pParse = pParse;
94056 sNC.pSrcList = pTabList;
94057 sNC.pAggInfo = &sAggInfo;
94058 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
94059 sAggInfo.pGroupBy = pGroupBy;
94060 sqlite3ExprAnalyzeAggList(&sNC, pEList);
94061 sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
94062 if( pHaving ){
94063 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
94065 sAggInfo.nAccumulator = sAggInfo.nColumn;
94066 for(i=0; i<sAggInfo.nFunc; i++){
94067 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
94068 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
94070 if( db->mallocFailed ) goto select_end;
94072 /* Processing for aggregates with GROUP BY is very different and
94073 ** much more complex than aggregates without a GROUP BY.
94075 if( pGroupBy ){
94076 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
94077 int j1; /* A-vs-B comparision jump */
94078 int addrOutputRow; /* Start of subroutine that outputs a result row */
94079 int regOutputRow; /* Return address register for output subroutine */
94080 int addrSetAbort; /* Set the abort flag and return */
94081 int addrTopOfLoop; /* Top of the input loop */
94082 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
94083 int addrReset; /* Subroutine for resetting the accumulator */
94084 int regReset; /* Return address register for reset subroutine */
94086 /* If there is a GROUP BY clause we might need a sorting index to
94087 ** implement it. Allocate that sorting index now. If it turns out
94088 ** that we do not need it after all, the OpenEphemeral instruction
94089 ** will be converted into a Noop.
94091 sAggInfo.sortingIdx = pParse->nTab++;
94092 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
94093 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
94094 sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
94095 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
94097 /* Initialize memory locations used by GROUP BY aggregate processing
94099 iUseFlag = ++pParse->nMem;
94100 iAbortFlag = ++pParse->nMem;
94101 regOutputRow = ++pParse->nMem;
94102 addrOutputRow = sqlite3VdbeMakeLabel(v);
94103 regReset = ++pParse->nMem;
94104 addrReset = sqlite3VdbeMakeLabel(v);
94105 iAMem = pParse->nMem + 1;
94106 pParse->nMem += pGroupBy->nExpr;
94107 iBMem = pParse->nMem + 1;
94108 pParse->nMem += pGroupBy->nExpr;
94109 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
94110 VdbeComment((v, "clear abort flag"));
94111 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
94112 VdbeComment((v, "indicate accumulator empty"));
94114 /* Begin a loop that will extract all source rows in GROUP BY order.
94115 ** This might involve two separate loops with an OP_Sort in between, or
94116 ** it might be a single loop that uses an index to extract information
94117 ** in the right order to begin with.
94119 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
94120 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
94121 if( pWInfo==0 ) goto select_end;
94122 if( pGroupBy==0 ){
94123 /* The optimizer is able to deliver rows in group by order so
94124 ** we do not have to sort. The OP_OpenEphemeral table will be
94125 ** cancelled later because we still need to use the pKeyInfo
94127 pGroupBy = p->pGroupBy;
94128 groupBySort = 0;
94129 }else{
94130 /* Rows are coming out in undetermined order. We have to push
94131 ** each row into a sorting index, terminate the first loop,
94132 ** then loop over the sorting index in order to get the output
94133 ** in sorted order
94135 int regBase;
94136 int regRecord;
94137 int nCol;
94138 int nGroupBy;
94140 explainTempTable(pParse,
94141 isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
94143 groupBySort = 1;
94144 nGroupBy = pGroupBy->nExpr;
94145 nCol = nGroupBy + 1;
94146 j = nGroupBy+1;
94147 for(i=0; i<sAggInfo.nColumn; i++){
94148 if( sAggInfo.aCol[i].iSorterColumn>=j ){
94149 nCol++;
94150 j++;
94153 regBase = sqlite3GetTempRange(pParse, nCol);
94154 sqlite3ExprCacheClear(pParse);
94155 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
94156 sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
94157 j = nGroupBy+1;
94158 for(i=0; i<sAggInfo.nColumn; i++){
94159 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
94160 if( pCol->iSorterColumn>=j ){
94161 int r1 = j + regBase;
94162 int r2;
94164 r2 = sqlite3ExprCodeGetColumn(pParse,
94165 pCol->pTab, pCol->iColumn, pCol->iTable, r1);
94166 if( r1!=r2 ){
94167 sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
94169 j++;
94172 regRecord = sqlite3GetTempReg(pParse);
94173 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
94174 sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
94175 sqlite3ReleaseTempReg(pParse, regRecord);
94176 sqlite3ReleaseTempRange(pParse, regBase, nCol);
94177 sqlite3WhereEnd(pWInfo);
94178 sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
94179 VdbeComment((v, "GROUP BY sort"));
94180 sAggInfo.useSortingIdx = 1;
94181 sqlite3ExprCacheClear(pParse);
94184 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
94185 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
94186 ** Then compare the current GROUP BY terms against the GROUP BY terms
94187 ** from the previous row currently stored in a0, a1, a2...
94189 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
94190 sqlite3ExprCacheClear(pParse);
94191 for(j=0; j<pGroupBy->nExpr; j++){
94192 if( groupBySort ){
94193 sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
94194 }else{
94195 sAggInfo.directMode = 1;
94196 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
94199 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
94200 (char*)pKeyInfo, P4_KEYINFO);
94201 j1 = sqlite3VdbeCurrentAddr(v);
94202 sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
94204 /* Generate code that runs whenever the GROUP BY changes.
94205 ** Changes in the GROUP BY are detected by the previous code
94206 ** block. If there were no changes, this block is skipped.
94208 ** This code copies current group by terms in b0,b1,b2,...
94209 ** over to a0,a1,a2. It then calls the output subroutine
94210 ** and resets the aggregate accumulator registers in preparation
94211 ** for the next GROUP BY batch.
94213 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
94214 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
94215 VdbeComment((v, "output one row"));
94216 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
94217 VdbeComment((v, "check abort flag"));
94218 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
94219 VdbeComment((v, "reset accumulator"));
94221 /* Update the aggregate accumulators based on the content of
94222 ** the current row
94224 sqlite3VdbeJumpHere(v, j1);
94225 updateAccumulator(pParse, &sAggInfo);
94226 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
94227 VdbeComment((v, "indicate data in accumulator"));
94229 /* End of the loop
94231 if( groupBySort ){
94232 sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
94233 }else{
94234 sqlite3WhereEnd(pWInfo);
94235 sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
94238 /* Output the final row of result
94240 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
94241 VdbeComment((v, "output final row"));
94243 /* Jump over the subroutines
94245 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
94247 /* Generate a subroutine that outputs a single row of the result
94248 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
94249 ** is less than or equal to zero, the subroutine is a no-op. If
94250 ** the processing calls for the query to abort, this subroutine
94251 ** increments the iAbortFlag memory location before returning in
94252 ** order to signal the caller to abort.
94254 addrSetAbort = sqlite3VdbeCurrentAddr(v);
94255 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
94256 VdbeComment((v, "set abort flag"));
94257 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94258 sqlite3VdbeResolveLabel(v, addrOutputRow);
94259 addrOutputRow = sqlite3VdbeCurrentAddr(v);
94260 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
94261 VdbeComment((v, "Groupby result generator entry point"));
94262 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94263 finalizeAggFunctions(pParse, &sAggInfo);
94264 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
94265 selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
94266 distinct, pDest,
94267 addrOutputRow+1, addrSetAbort);
94268 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94269 VdbeComment((v, "end groupby result generator"));
94271 /* Generate a subroutine that will reset the group-by accumulator
94273 sqlite3VdbeResolveLabel(v, addrReset);
94274 resetAccumulator(pParse, &sAggInfo);
94275 sqlite3VdbeAddOp1(v, OP_Return, regReset);
94277 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
94278 else {
94279 ExprList *pDel = 0;
94280 #ifndef SQLITE_OMIT_BTREECOUNT
94281 Table *pTab;
94282 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
94283 /* If isSimpleCount() returns a pointer to a Table structure, then
94284 ** the SQL statement is of the form:
94286 ** SELECT count(*) FROM <tbl>
94288 ** where the Table structure returned represents table <tbl>.
94290 ** This statement is so common that it is optimized specially. The
94291 ** OP_Count instruction is executed either on the intkey table that
94292 ** contains the data for table <tbl> or on one of its indexes. It
94293 ** is better to execute the op on an index, as indexes are almost
94294 ** always spread across less pages than their corresponding tables.
94296 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94297 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
94298 Index *pIdx; /* Iterator variable */
94299 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
94300 Index *pBest = 0; /* Best index found so far */
94301 int iRoot = pTab->tnum; /* Root page of scanned b-tree */
94303 sqlite3CodeVerifySchema(pParse, iDb);
94304 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
94306 /* Search for the index that has the least amount of columns. If
94307 ** there is such an index, and it has less columns than the table
94308 ** does, then we can assume that it consumes less space on disk and
94309 ** will therefore be cheaper to scan to determine the query result.
94310 ** In this case set iRoot to the root page number of the index b-tree
94311 ** and pKeyInfo to the KeyInfo structure required to navigate the
94312 ** index.
94314 ** In practice the KeyInfo structure will not be used. It is only
94315 ** passed to keep OP_OpenRead happy.
94317 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94318 if( !pBest || pIdx->nColumn<pBest->nColumn ){
94319 pBest = pIdx;
94322 if( pBest && pBest->nColumn<pTab->nCol ){
94323 iRoot = pBest->tnum;
94324 pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
94327 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
94328 sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
94329 if( pKeyInfo ){
94330 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
94332 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
94333 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
94334 explainSimpleCount(pParse, pTab, pBest);
94335 }else
94336 #endif /* SQLITE_OMIT_BTREECOUNT */
94338 /* Check if the query is of one of the following forms:
94340 ** SELECT min(x) FROM ...
94341 ** SELECT max(x) FROM ...
94343 ** If it is, then ask the code in where.c to attempt to sort results
94344 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
94345 ** If where.c is able to produce results sorted in this order, then
94346 ** add vdbe code to break out of the processing loop after the
94347 ** first iteration (since the first iteration of the loop is
94348 ** guaranteed to operate on the row with the minimum or maximum
94349 ** value of x, the only row required).
94351 ** A special flag must be passed to sqlite3WhereBegin() to slightly
94352 ** modify behaviour as follows:
94354 ** + If the query is a "SELECT min(x)", then the loop coded by
94355 ** where.c should not iterate over any values with a NULL value
94356 ** for x.
94358 ** + The optimizer code in where.c (the thing that decides which
94359 ** index or indices to use) should place a different priority on
94360 ** satisfying the 'ORDER BY' clause than it does in other cases.
94361 ** Refer to code and comments in where.c for details.
94363 ExprList *pMinMax = 0;
94364 u8 flag = minMaxQuery(p);
94365 if( flag ){
94366 assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
94367 pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
94368 pDel = pMinMax;
94369 if( pMinMax && !db->mallocFailed ){
94370 pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
94371 pMinMax->a[0].pExpr->op = TK_COLUMN;
94375 /* This case runs if the aggregate has no GROUP BY clause. The
94376 ** processing is much simpler since there is only a single row
94377 ** of output.
94379 resetAccumulator(pParse, &sAggInfo);
94380 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
94381 if( pWInfo==0 ){
94382 sqlite3ExprListDelete(db, pDel);
94383 goto select_end;
94385 updateAccumulator(pParse, &sAggInfo);
94386 if( !pMinMax && flag ){
94387 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
94388 VdbeComment((v, "%s() by index",
94389 (flag==WHERE_ORDERBY_MIN?"min":"max")));
94391 sqlite3WhereEnd(pWInfo);
94392 finalizeAggFunctions(pParse, &sAggInfo);
94395 pOrderBy = 0;
94396 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
94397 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
94398 pDest, addrEnd, addrEnd);
94399 sqlite3ExprListDelete(db, pDel);
94401 sqlite3VdbeResolveLabel(v, addrEnd);
94403 } /* endif aggregate query */
94405 if( distinct>=0 ){
94406 explainTempTable(pParse, "DISTINCT");
94409 /* If there is an ORDER BY clause, then we need to sort the results
94410 ** and send them to the callback one by one.
94412 if( pOrderBy ){
94413 explainTempTable(pParse, "ORDER BY");
94414 generateSortTail(pParse, p, v, pEList->nExpr, pDest);
94417 /* Jump here to skip this query
94419 sqlite3VdbeResolveLabel(v, iEnd);
94421 /* The SELECT was successfully coded. Set the return code to 0
94422 ** to indicate no errors.
94424 rc = 0;
94426 /* Control jumps to here if an error is encountered above, or upon
94427 ** successful coding of the SELECT.
94429 select_end:
94430 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
94432 /* Identify column names if results of the SELECT are to be output.
94434 if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
94435 generateColumnNames(pParse, pTabList, pEList);
94438 sqlite3DbFree(db, sAggInfo.aCol);
94439 sqlite3DbFree(db, sAggInfo.aFunc);
94440 return rc;
94443 #if defined(SQLITE_DEBUG)
94445 *******************************************************************************
94446 ** The following code is used for testing and debugging only. The code
94447 ** that follows does not appear in normal builds.
94449 ** These routines are used to print out the content of all or part of a
94450 ** parse structures such as Select or Expr. Such printouts are useful
94451 ** for helping to understand what is happening inside the code generator
94452 ** during the execution of complex SELECT statements.
94454 ** These routine are not called anywhere from within the normal
94455 ** code base. Then are intended to be called from within the debugger
94456 ** or from temporary "printf" statements inserted for debugging.
94458 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
94459 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
94460 sqlite3DebugPrintf("(%s", p->u.zToken);
94461 }else{
94462 sqlite3DebugPrintf("(%d", p->op);
94464 if( p->pLeft ){
94465 sqlite3DebugPrintf(" ");
94466 sqlite3PrintExpr(p->pLeft);
94468 if( p->pRight ){
94469 sqlite3DebugPrintf(" ");
94470 sqlite3PrintExpr(p->pRight);
94472 sqlite3DebugPrintf(")");
94474 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
94475 int i;
94476 for(i=0; i<pList->nExpr; i++){
94477 sqlite3PrintExpr(pList->a[i].pExpr);
94478 if( i<pList->nExpr-1 ){
94479 sqlite3DebugPrintf(", ");
94483 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
94484 sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
94485 sqlite3PrintExprList(p->pEList);
94486 sqlite3DebugPrintf("\n");
94487 if( p->pSrc ){
94488 char *zPrefix;
94489 int i;
94490 zPrefix = "FROM";
94491 for(i=0; i<p->pSrc->nSrc; i++){
94492 struct SrcList_item *pItem = &p->pSrc->a[i];
94493 sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
94494 zPrefix = "";
94495 if( pItem->pSelect ){
94496 sqlite3DebugPrintf("(\n");
94497 sqlite3PrintSelect(pItem->pSelect, indent+10);
94498 sqlite3DebugPrintf("%*s)", indent+8, "");
94499 }else if( pItem->zName ){
94500 sqlite3DebugPrintf("%s", pItem->zName);
94502 if( pItem->pTab ){
94503 sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
94505 if( pItem->zAlias ){
94506 sqlite3DebugPrintf(" AS %s", pItem->zAlias);
94508 if( i<p->pSrc->nSrc-1 ){
94509 sqlite3DebugPrintf(",");
94511 sqlite3DebugPrintf("\n");
94514 if( p->pWhere ){
94515 sqlite3DebugPrintf("%*s WHERE ", indent, "");
94516 sqlite3PrintExpr(p->pWhere);
94517 sqlite3DebugPrintf("\n");
94519 if( p->pGroupBy ){
94520 sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
94521 sqlite3PrintExprList(p->pGroupBy);
94522 sqlite3DebugPrintf("\n");
94524 if( p->pHaving ){
94525 sqlite3DebugPrintf("%*s HAVING ", indent, "");
94526 sqlite3PrintExpr(p->pHaving);
94527 sqlite3DebugPrintf("\n");
94529 if( p->pOrderBy ){
94530 sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
94531 sqlite3PrintExprList(p->pOrderBy);
94532 sqlite3DebugPrintf("\n");
94535 /* End of the structure debug printing code
94536 *****************************************************************************/
94537 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
94539 /************** End of select.c **********************************************/
94540 /************** Begin file table.c *******************************************/
94542 ** 2001 September 15
94544 ** The author disclaims copyright to this source code. In place of
94545 ** a legal notice, here is a blessing:
94547 ** May you do good and not evil.
94548 ** May you find forgiveness for yourself and forgive others.
94549 ** May you share freely, never taking more than you give.
94551 *************************************************************************
94552 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
94553 ** interface routines. These are just wrappers around the main
94554 ** interface routine of sqlite3_exec().
94556 ** These routines are in a separate files so that they will not be linked
94557 ** if they are not used.
94560 #ifndef SQLITE_OMIT_GET_TABLE
94563 ** This structure is used to pass data from sqlite3_get_table() through
94564 ** to the callback function is uses to build the result.
94566 typedef struct TabResult {
94567 char **azResult; /* Accumulated output */
94568 char *zErrMsg; /* Error message text, if an error occurs */
94569 int nAlloc; /* Slots allocated for azResult[] */
94570 int nRow; /* Number of rows in the result */
94571 int nColumn; /* Number of columns in the result */
94572 int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
94573 int rc; /* Return code from sqlite3_exec() */
94574 } TabResult;
94577 ** This routine is called once for each row in the result table. Its job
94578 ** is to fill in the TabResult structure appropriately, allocating new
94579 ** memory as necessary.
94581 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
94582 TabResult *p = (TabResult*)pArg; /* Result accumulator */
94583 int need; /* Slots needed in p->azResult[] */
94584 int i; /* Loop counter */
94585 char *z; /* A single column of result */
94587 /* Make sure there is enough space in p->azResult to hold everything
94588 ** we need to remember from this invocation of the callback.
94590 if( p->nRow==0 && argv!=0 ){
94591 need = nCol*2;
94592 }else{
94593 need = nCol;
94595 if( p->nData + need > p->nAlloc ){
94596 char **azNew;
94597 p->nAlloc = p->nAlloc*2 + need;
94598 azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
94599 if( azNew==0 ) goto malloc_failed;
94600 p->azResult = azNew;
94603 /* If this is the first row, then generate an extra row containing
94604 ** the names of all columns.
94606 if( p->nRow==0 ){
94607 p->nColumn = nCol;
94608 for(i=0; i<nCol; i++){
94609 z = sqlite3_mprintf("%s", colv[i]);
94610 if( z==0 ) goto malloc_failed;
94611 p->azResult[p->nData++] = z;
94613 }else if( p->nColumn!=nCol ){
94614 sqlite3_free(p->zErrMsg);
94615 p->zErrMsg = sqlite3_mprintf(
94616 "sqlite3_get_table() called with two or more incompatible queries"
94618 p->rc = SQLITE_ERROR;
94619 return 1;
94622 /* Copy over the row data
94624 if( argv!=0 ){
94625 for(i=0; i<nCol; i++){
94626 if( argv[i]==0 ){
94627 z = 0;
94628 }else{
94629 int n = sqlite3Strlen30(argv[i])+1;
94630 z = sqlite3_malloc( n );
94631 if( z==0 ) goto malloc_failed;
94632 memcpy(z, argv[i], n);
94634 p->azResult[p->nData++] = z;
94636 p->nRow++;
94638 return 0;
94640 malloc_failed:
94641 p->rc = SQLITE_NOMEM;
94642 return 1;
94646 ** Query the database. But instead of invoking a callback for each row,
94647 ** malloc() for space to hold the result and return the entire results
94648 ** at the conclusion of the call.
94650 ** The result that is written to ***pazResult is held in memory obtained
94651 ** from malloc(). But the caller cannot free this memory directly.
94652 ** Instead, the entire table should be passed to sqlite3_free_table() when
94653 ** the calling procedure is finished using it.
94655 SQLITE_API int sqlite3_get_table(
94656 sqlite3 *db, /* The database on which the SQL executes */
94657 const char *zSql, /* The SQL to be executed */
94658 char ***pazResult, /* Write the result table here */
94659 int *pnRow, /* Write the number of rows in the result here */
94660 int *pnColumn, /* Write the number of columns of result here */
94661 char **pzErrMsg /* Write error messages here */
94663 int rc;
94664 TabResult res;
94666 *pazResult = 0;
94667 if( pnColumn ) *pnColumn = 0;
94668 if( pnRow ) *pnRow = 0;
94669 if( pzErrMsg ) *pzErrMsg = 0;
94670 res.zErrMsg = 0;
94671 res.nRow = 0;
94672 res.nColumn = 0;
94673 res.nData = 1;
94674 res.nAlloc = 20;
94675 res.rc = SQLITE_OK;
94676 res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
94677 if( res.azResult==0 ){
94678 db->errCode = SQLITE_NOMEM;
94679 return SQLITE_NOMEM;
94681 res.azResult[0] = 0;
94682 rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
94683 assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
94684 res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
94685 if( (rc&0xff)==SQLITE_ABORT ){
94686 sqlite3_free_table(&res.azResult[1]);
94687 if( res.zErrMsg ){
94688 if( pzErrMsg ){
94689 sqlite3_free(*pzErrMsg);
94690 *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
94692 sqlite3_free(res.zErrMsg);
94694 db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
94695 return res.rc;
94697 sqlite3_free(res.zErrMsg);
94698 if( rc!=SQLITE_OK ){
94699 sqlite3_free_table(&res.azResult[1]);
94700 return rc;
94702 if( res.nAlloc>res.nData ){
94703 char **azNew;
94704 azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
94705 if( azNew==0 ){
94706 sqlite3_free_table(&res.azResult[1]);
94707 db->errCode = SQLITE_NOMEM;
94708 return SQLITE_NOMEM;
94710 res.azResult = azNew;
94712 *pazResult = &res.azResult[1];
94713 if( pnColumn ) *pnColumn = res.nColumn;
94714 if( pnRow ) *pnRow = res.nRow;
94715 return rc;
94719 ** This routine frees the space the sqlite3_get_table() malloced.
94721 SQLITE_API void sqlite3_free_table(
94722 char **azResult /* Result returned from from sqlite3_get_table() */
94724 if( azResult ){
94725 int i, n;
94726 azResult--;
94727 assert( azResult!=0 );
94728 n = SQLITE_PTR_TO_INT(azResult[0]);
94729 for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
94730 sqlite3_free(azResult);
94734 #endif /* SQLITE_OMIT_GET_TABLE */
94736 /************** End of table.c ***********************************************/
94737 /************** Begin file trigger.c *****************************************/
94740 ** The author disclaims copyright to this source code. In place of
94741 ** a legal notice, here is a blessing:
94743 ** May you do good and not evil.
94744 ** May you find forgiveness for yourself and forgive others.
94745 ** May you share freely, never taking more than you give.
94747 *************************************************************************
94748 ** This file contains the implementation for TRIGGERs
94751 #ifndef SQLITE_OMIT_TRIGGER
94753 ** Delete a linked list of TriggerStep structures.
94755 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
94756 while( pTriggerStep ){
94757 TriggerStep * pTmp = pTriggerStep;
94758 pTriggerStep = pTriggerStep->pNext;
94760 sqlite3ExprDelete(db, pTmp->pWhere);
94761 sqlite3ExprListDelete(db, pTmp->pExprList);
94762 sqlite3SelectDelete(db, pTmp->pSelect);
94763 sqlite3IdListDelete(db, pTmp->pIdList);
94765 sqlite3DbFree(db, pTmp);
94770 ** Given table pTab, return a list of all the triggers attached to
94771 ** the table. The list is connected by Trigger.pNext pointers.
94773 ** All of the triggers on pTab that are in the same database as pTab
94774 ** are already attached to pTab->pTrigger. But there might be additional
94775 ** triggers on pTab in the TEMP schema. This routine prepends all
94776 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
94777 ** and returns the combined list.
94779 ** To state it another way: This routine returns a list of all triggers
94780 ** that fire off of pTab. The list will include any TEMP triggers on
94781 ** pTab as well as the triggers lised in pTab->pTrigger.
94783 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
94784 Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
94785 Trigger *pList = 0; /* List of triggers to return */
94787 if( pParse->disableTriggers ){
94788 return 0;
94791 if( pTmpSchema!=pTab->pSchema ){
94792 HashElem *p;
94793 assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
94794 for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
94795 Trigger *pTrig = (Trigger *)sqliteHashData(p);
94796 if( pTrig->pTabSchema==pTab->pSchema
94797 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
94799 pTrig->pNext = (pList ? pList : pTab->pTrigger);
94800 pList = pTrig;
94805 return (pList ? pList : pTab->pTrigger);
94809 ** This is called by the parser when it sees a CREATE TRIGGER statement
94810 ** up to the point of the BEGIN before the trigger actions. A Trigger
94811 ** structure is generated based on the information available and stored
94812 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
94813 ** sqlite3FinishTrigger() function is called to complete the trigger
94814 ** construction process.
94816 SQLITE_PRIVATE void sqlite3BeginTrigger(
94817 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
94818 Token *pName1, /* The name of the trigger */
94819 Token *pName2, /* The name of the trigger */
94820 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
94821 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
94822 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
94823 SrcList *pTableName,/* The name of the table/view the trigger applies to */
94824 Expr *pWhen, /* WHEN clause */
94825 int isTemp, /* True if the TEMPORARY keyword is present */
94826 int noErr /* Suppress errors if the trigger already exists */
94828 Trigger *pTrigger = 0; /* The new trigger */
94829 Table *pTab; /* Table that the trigger fires off of */
94830 char *zName = 0; /* Name of the trigger */
94831 sqlite3 *db = pParse->db; /* The database connection */
94832 int iDb; /* The database to store the trigger in */
94833 Token *pName; /* The unqualified db name */
94834 DbFixer sFix; /* State vector for the DB fixer */
94835 int iTabDb; /* Index of the database holding pTab */
94837 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
94838 assert( pName2!=0 );
94839 assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
94840 assert( op>0 && op<0xff );
94841 if( isTemp ){
94842 /* If TEMP was specified, then the trigger name may not be qualified. */
94843 if( pName2->n>0 ){
94844 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
94845 goto trigger_cleanup;
94847 iDb = 1;
94848 pName = pName1;
94849 }else{
94850 /* Figure out the db that the the trigger will be created in */
94851 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
94852 if( iDb<0 ){
94853 goto trigger_cleanup;
94857 /* If the trigger name was unqualified, and the table is a temp table,
94858 ** then set iDb to 1 to create the trigger in the temporary database.
94859 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
94860 ** exist, the error is caught by the block below.
94862 if( !pTableName || db->mallocFailed ){
94863 goto trigger_cleanup;
94865 pTab = sqlite3SrcListLookup(pParse, pTableName);
94866 if( db->init.busy==0 && pName2->n==0 && pTab
94867 && pTab->pSchema==db->aDb[1].pSchema ){
94868 iDb = 1;
94871 /* Ensure the table name matches database name and that the table exists */
94872 if( db->mallocFailed ) goto trigger_cleanup;
94873 assert( pTableName->nSrc==1 );
94874 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
94875 sqlite3FixSrcList(&sFix, pTableName) ){
94876 goto trigger_cleanup;
94878 pTab = sqlite3SrcListLookup(pParse, pTableName);
94879 if( !pTab ){
94880 /* The table does not exist. */
94881 if( db->init.iDb==1 ){
94882 /* Ticket #3810.
94883 ** Normally, whenever a table is dropped, all associated triggers are
94884 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
94885 ** and the table is dropped by a different database connection, the
94886 ** trigger is not visible to the database connection that does the
94887 ** drop so the trigger cannot be dropped. This results in an
94888 ** "orphaned trigger" - a trigger whose associated table is missing.
94890 db->init.orphanTrigger = 1;
94892 goto trigger_cleanup;
94894 if( IsVirtual(pTab) ){
94895 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
94896 goto trigger_cleanup;
94899 /* Check that the trigger name is not reserved and that no trigger of the
94900 ** specified name exists */
94901 zName = sqlite3NameFromToken(db, pName);
94902 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
94903 goto trigger_cleanup;
94905 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94906 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
94907 zName, sqlite3Strlen30(zName)) ){
94908 if( !noErr ){
94909 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
94910 }else{
94911 assert( !db->init.busy );
94912 sqlite3CodeVerifySchema(pParse, iDb);
94914 goto trigger_cleanup;
94917 /* Do not create a trigger on a system table */
94918 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
94919 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
94920 pParse->nErr++;
94921 goto trigger_cleanup;
94924 /* INSTEAD of triggers are only for views and views only support INSTEAD
94925 ** of triggers.
94927 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
94928 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
94929 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
94930 goto trigger_cleanup;
94932 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
94933 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
94934 " trigger on table: %S", pTableName, 0);
94935 goto trigger_cleanup;
94937 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94939 #ifndef SQLITE_OMIT_AUTHORIZATION
94941 int code = SQLITE_CREATE_TRIGGER;
94942 const char *zDb = db->aDb[iTabDb].zName;
94943 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
94944 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
94945 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
94946 goto trigger_cleanup;
94948 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
94949 goto trigger_cleanup;
94952 #endif
94954 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
94955 ** cannot appear on views. So we might as well translate every
94956 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
94957 ** elsewhere.
94959 if (tr_tm == TK_INSTEAD){
94960 tr_tm = TK_BEFORE;
94963 /* Build the Trigger object */
94964 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
94965 if( pTrigger==0 ) goto trigger_cleanup;
94966 pTrigger->zName = zName;
94967 zName = 0;
94968 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
94969 pTrigger->pSchema = db->aDb[iDb].pSchema;
94970 pTrigger->pTabSchema = pTab->pSchema;
94971 pTrigger->op = (u8)op;
94972 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
94973 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
94974 pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
94975 assert( pParse->pNewTrigger==0 );
94976 pParse->pNewTrigger = pTrigger;
94978 trigger_cleanup:
94979 sqlite3DbFree(db, zName);
94980 sqlite3SrcListDelete(db, pTableName);
94981 sqlite3IdListDelete(db, pColumns);
94982 sqlite3ExprDelete(db, pWhen);
94983 if( !pParse->pNewTrigger ){
94984 sqlite3DeleteTrigger(db, pTrigger);
94985 }else{
94986 assert( pParse->pNewTrigger==pTrigger );
94991 ** This routine is called after all of the trigger actions have been parsed
94992 ** in order to complete the process of building the trigger.
94994 SQLITE_PRIVATE void sqlite3FinishTrigger(
94995 Parse *pParse, /* Parser context */
94996 TriggerStep *pStepList, /* The triggered program */
94997 Token *pAll /* Token that describes the complete CREATE TRIGGER */
94999 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
95000 char *zName; /* Name of trigger */
95001 sqlite3 *db = pParse->db; /* The database */
95002 DbFixer sFix; /* Fixer object */
95003 int iDb; /* Database containing the trigger */
95004 Token nameToken; /* Trigger name for error reporting */
95006 pParse->pNewTrigger = 0;
95007 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
95008 zName = pTrig->zName;
95009 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
95010 pTrig->step_list = pStepList;
95011 while( pStepList ){
95012 pStepList->pTrig = pTrig;
95013 pStepList = pStepList->pNext;
95015 nameToken.z = pTrig->zName;
95016 nameToken.n = sqlite3Strlen30(nameToken.z);
95017 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
95018 && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
95019 goto triggerfinish_cleanup;
95022 /* if we are not initializing,
95023 ** build the sqlite_master entry
95025 if( !db->init.busy ){
95026 Vdbe *v;
95027 char *z;
95029 /* Make an entry in the sqlite_master table */
95030 v = sqlite3GetVdbe(pParse);
95031 if( v==0 ) goto triggerfinish_cleanup;
95032 sqlite3BeginWriteOperation(pParse, 0, iDb);
95033 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
95034 sqlite3NestedParse(pParse,
95035 "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
95036 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
95037 pTrig->table, z);
95038 sqlite3DbFree(db, z);
95039 sqlite3ChangeCookie(pParse, iDb);
95040 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
95041 db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
95045 if( db->init.busy ){
95046 Trigger *pLink = pTrig;
95047 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
95048 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95049 pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
95050 if( pTrig ){
95051 db->mallocFailed = 1;
95052 }else if( pLink->pSchema==pLink->pTabSchema ){
95053 Table *pTab;
95054 int n = sqlite3Strlen30(pLink->table);
95055 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
95056 assert( pTab!=0 );
95057 pLink->pNext = pTab->pTrigger;
95058 pTab->pTrigger = pLink;
95062 triggerfinish_cleanup:
95063 sqlite3DeleteTrigger(db, pTrig);
95064 assert( !pParse->pNewTrigger );
95065 sqlite3DeleteTriggerStep(db, pStepList);
95069 ** Turn a SELECT statement (that the pSelect parameter points to) into
95070 ** a trigger step. Return a pointer to a TriggerStep structure.
95072 ** The parser calls this routine when it finds a SELECT statement in
95073 ** body of a TRIGGER.
95075 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
95076 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
95077 if( pTriggerStep==0 ) {
95078 sqlite3SelectDelete(db, pSelect);
95079 return 0;
95081 pTriggerStep->op = TK_SELECT;
95082 pTriggerStep->pSelect = pSelect;
95083 pTriggerStep->orconf = OE_Default;
95084 return pTriggerStep;
95088 ** Allocate space to hold a new trigger step. The allocated space
95089 ** holds both the TriggerStep object and the TriggerStep.target.z string.
95091 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
95093 static TriggerStep *triggerStepAllocate(
95094 sqlite3 *db, /* Database connection */
95095 u8 op, /* Trigger opcode */
95096 Token *pName /* The target name */
95098 TriggerStep *pTriggerStep;
95100 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
95101 if( pTriggerStep ){
95102 char *z = (char*)&pTriggerStep[1];
95103 memcpy(z, pName->z, pName->n);
95104 pTriggerStep->target.z = z;
95105 pTriggerStep->target.n = pName->n;
95106 pTriggerStep->op = op;
95108 return pTriggerStep;
95112 ** Build a trigger step out of an INSERT statement. Return a pointer
95113 ** to the new trigger step.
95115 ** The parser calls this routine when it sees an INSERT inside the
95116 ** body of a trigger.
95118 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
95119 sqlite3 *db, /* The database connection */
95120 Token *pTableName, /* Name of the table into which we insert */
95121 IdList *pColumn, /* List of columns in pTableName to insert into */
95122 ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
95123 Select *pSelect, /* A SELECT statement that supplies values */
95124 u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
95126 TriggerStep *pTriggerStep;
95128 assert(pEList == 0 || pSelect == 0);
95129 assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
95131 pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
95132 if( pTriggerStep ){
95133 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
95134 pTriggerStep->pIdList = pColumn;
95135 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
95136 pTriggerStep->orconf = orconf;
95137 }else{
95138 sqlite3IdListDelete(db, pColumn);
95140 sqlite3ExprListDelete(db, pEList);
95141 sqlite3SelectDelete(db, pSelect);
95143 return pTriggerStep;
95147 ** Construct a trigger step that implements an UPDATE statement and return
95148 ** a pointer to that trigger step. The parser calls this routine when it
95149 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
95151 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
95152 sqlite3 *db, /* The database connection */
95153 Token *pTableName, /* Name of the table to be updated */
95154 ExprList *pEList, /* The SET clause: list of column and new values */
95155 Expr *pWhere, /* The WHERE clause */
95156 u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
95158 TriggerStep *pTriggerStep;
95160 pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
95161 if( pTriggerStep ){
95162 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
95163 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
95164 pTriggerStep->orconf = orconf;
95166 sqlite3ExprListDelete(db, pEList);
95167 sqlite3ExprDelete(db, pWhere);
95168 return pTriggerStep;
95172 ** Construct a trigger step that implements a DELETE statement and return
95173 ** a pointer to that trigger step. The parser calls this routine when it
95174 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
95176 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
95177 sqlite3 *db, /* Database connection */
95178 Token *pTableName, /* The table from which rows are deleted */
95179 Expr *pWhere /* The WHERE clause */
95181 TriggerStep *pTriggerStep;
95183 pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
95184 if( pTriggerStep ){
95185 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
95186 pTriggerStep->orconf = OE_Default;
95188 sqlite3ExprDelete(db, pWhere);
95189 return pTriggerStep;
95193 ** Recursively delete a Trigger structure
95195 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
95196 if( pTrigger==0 ) return;
95197 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
95198 sqlite3DbFree(db, pTrigger->zName);
95199 sqlite3DbFree(db, pTrigger->table);
95200 sqlite3ExprDelete(db, pTrigger->pWhen);
95201 sqlite3IdListDelete(db, pTrigger->pColumns);
95202 sqlite3DbFree(db, pTrigger);
95206 ** This function is called to drop a trigger from the database schema.
95208 ** This may be called directly from the parser and therefore identifies
95209 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
95210 ** same job as this routine except it takes a pointer to the trigger
95211 ** instead of the trigger name.
95213 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
95214 Trigger *pTrigger = 0;
95215 int i;
95216 const char *zDb;
95217 const char *zName;
95218 int nName;
95219 sqlite3 *db = pParse->db;
95221 if( db->mallocFailed ) goto drop_trigger_cleanup;
95222 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
95223 goto drop_trigger_cleanup;
95226 assert( pName->nSrc==1 );
95227 zDb = pName->a[0].zDatabase;
95228 zName = pName->a[0].zName;
95229 nName = sqlite3Strlen30(zName);
95230 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
95231 for(i=OMIT_TEMPDB; i<db->nDb; i++){
95232 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
95233 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
95234 assert( sqlite3SchemaMutexHeld(db, j, 0) );
95235 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
95236 if( pTrigger ) break;
95238 if( !pTrigger ){
95239 if( !noErr ){
95240 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
95241 }else{
95242 sqlite3CodeVerifyNamedSchema(pParse, zDb);
95244 pParse->checkSchema = 1;
95245 goto drop_trigger_cleanup;
95247 sqlite3DropTriggerPtr(pParse, pTrigger);
95249 drop_trigger_cleanup:
95250 sqlite3SrcListDelete(db, pName);
95254 ** Return a pointer to the Table structure for the table that a trigger
95255 ** is set on.
95257 static Table *tableOfTrigger(Trigger *pTrigger){
95258 int n = sqlite3Strlen30(pTrigger->table);
95259 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
95264 ** Drop a trigger given a pointer to that trigger.
95266 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
95267 Table *pTable;
95268 Vdbe *v;
95269 sqlite3 *db = pParse->db;
95270 int iDb;
95272 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
95273 assert( iDb>=0 && iDb<db->nDb );
95274 pTable = tableOfTrigger(pTrigger);
95275 assert( pTable );
95276 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
95277 #ifndef SQLITE_OMIT_AUTHORIZATION
95279 int code = SQLITE_DROP_TRIGGER;
95280 const char *zDb = db->aDb[iDb].zName;
95281 const char *zTab = SCHEMA_TABLE(iDb);
95282 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
95283 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
95284 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
95285 return;
95288 #endif
95290 /* Generate code to destroy the database record of the trigger.
95292 assert( pTable!=0 );
95293 if( (v = sqlite3GetVdbe(pParse))!=0 ){
95294 int base;
95295 static const VdbeOpList dropTrigger[] = {
95296 { OP_Rewind, 0, ADDR(9), 0},
95297 { OP_String8, 0, 1, 0}, /* 1 */
95298 { OP_Column, 0, 1, 2},
95299 { OP_Ne, 2, ADDR(8), 1},
95300 { OP_String8, 0, 1, 0}, /* 4: "trigger" */
95301 { OP_Column, 0, 0, 2},
95302 { OP_Ne, 2, ADDR(8), 1},
95303 { OP_Delete, 0, 0, 0},
95304 { OP_Next, 0, ADDR(1), 0}, /* 8 */
95307 sqlite3BeginWriteOperation(pParse, 0, iDb);
95308 sqlite3OpenMasterTable(pParse, iDb);
95309 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
95310 sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
95311 sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
95312 sqlite3ChangeCookie(pParse, iDb);
95313 sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
95314 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
95315 if( pParse->nMem<3 ){
95316 pParse->nMem = 3;
95322 ** Remove a trigger from the hash tables of the sqlite* pointer.
95324 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
95325 Trigger *pTrigger;
95326 Hash *pHash;
95328 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95329 pHash = &(db->aDb[iDb].pSchema->trigHash);
95330 pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
95331 if( ALWAYS(pTrigger) ){
95332 if( pTrigger->pSchema==pTrigger->pTabSchema ){
95333 Table *pTab = tableOfTrigger(pTrigger);
95334 Trigger **pp;
95335 for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
95336 *pp = (*pp)->pNext;
95338 sqlite3DeleteTrigger(db, pTrigger);
95339 db->flags |= SQLITE_InternChanges;
95344 ** pEList is the SET clause of an UPDATE statement. Each entry
95345 ** in pEList is of the format <id>=<expr>. If any of the entries
95346 ** in pEList have an <id> which matches an identifier in pIdList,
95347 ** then return TRUE. If pIdList==NULL, then it is considered a
95348 ** wildcard that matches anything. Likewise if pEList==NULL then
95349 ** it matches anything so always return true. Return false only
95350 ** if there is no match.
95352 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
95353 int e;
95354 if( pIdList==0 || NEVER(pEList==0) ) return 1;
95355 for(e=0; e<pEList->nExpr; e++){
95356 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
95358 return 0;
95362 ** Return a list of all triggers on table pTab if there exists at least
95363 ** one trigger that must be fired when an operation of type 'op' is
95364 ** performed on the table, and, if that operation is an UPDATE, if at
95365 ** least one of the columns in pChanges is being modified.
95367 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
95368 Parse *pParse, /* Parse context */
95369 Table *pTab, /* The table the contains the triggers */
95370 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
95371 ExprList *pChanges, /* Columns that change in an UPDATE statement */
95372 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95374 int mask = 0;
95375 Trigger *pList = 0;
95376 Trigger *p;
95378 if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
95379 pList = sqlite3TriggerList(pParse, pTab);
95381 assert( pList==0 || IsVirtual(pTab)==0 );
95382 for(p=pList; p; p=p->pNext){
95383 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
95384 mask |= p->tr_tm;
95387 if( pMask ){
95388 *pMask = mask;
95390 return (mask ? pList : 0);
95394 ** Convert the pStep->target token into a SrcList and return a pointer
95395 ** to that SrcList.
95397 ** This routine adds a specific database name, if needed, to the target when
95398 ** forming the SrcList. This prevents a trigger in one database from
95399 ** referring to a target in another database. An exception is when the
95400 ** trigger is in TEMP in which case it can refer to any other database it
95401 ** wants.
95403 static SrcList *targetSrcList(
95404 Parse *pParse, /* The parsing context */
95405 TriggerStep *pStep /* The trigger containing the target token */
95407 int iDb; /* Index of the database to use */
95408 SrcList *pSrc; /* SrcList to be returned */
95410 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
95411 if( pSrc ){
95412 assert( pSrc->nSrc>0 );
95413 assert( pSrc->a!=0 );
95414 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
95415 if( iDb==0 || iDb>=2 ){
95416 sqlite3 *db = pParse->db;
95417 assert( iDb<pParse->db->nDb );
95418 pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
95421 return pSrc;
95425 ** Generate VDBE code for the statements inside the body of a single
95426 ** trigger.
95428 static int codeTriggerProgram(
95429 Parse *pParse, /* The parser context */
95430 TriggerStep *pStepList, /* List of statements inside the trigger body */
95431 int orconf /* Conflict algorithm. (OE_Abort, etc) */
95433 TriggerStep *pStep;
95434 Vdbe *v = pParse->pVdbe;
95435 sqlite3 *db = pParse->db;
95437 assert( pParse->pTriggerTab && pParse->pToplevel );
95438 assert( pStepList );
95439 assert( v!=0 );
95440 for(pStep=pStepList; pStep; pStep=pStep->pNext){
95441 /* Figure out the ON CONFLICT policy that will be used for this step
95442 ** of the trigger program. If the statement that caused this trigger
95443 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
95444 ** the ON CONFLICT policy that was specified as part of the trigger
95445 ** step statement. Example:
95447 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
95448 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
95449 ** END;
95451 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
95452 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
95454 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
95456 switch( pStep->op ){
95457 case TK_UPDATE: {
95458 sqlite3Update(pParse,
95459 targetSrcList(pParse, pStep),
95460 sqlite3ExprListDup(db, pStep->pExprList, 0),
95461 sqlite3ExprDup(db, pStep->pWhere, 0),
95462 pParse->eOrconf
95464 break;
95466 case TK_INSERT: {
95467 sqlite3Insert(pParse,
95468 targetSrcList(pParse, pStep),
95469 sqlite3ExprListDup(db, pStep->pExprList, 0),
95470 sqlite3SelectDup(db, pStep->pSelect, 0),
95471 sqlite3IdListDup(db, pStep->pIdList),
95472 pParse->eOrconf
95474 break;
95476 case TK_DELETE: {
95477 sqlite3DeleteFrom(pParse,
95478 targetSrcList(pParse, pStep),
95479 sqlite3ExprDup(db, pStep->pWhere, 0)
95481 break;
95483 default: assert( pStep->op==TK_SELECT ); {
95484 SelectDest sDest;
95485 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
95486 sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
95487 sqlite3Select(pParse, pSelect, &sDest);
95488 sqlite3SelectDelete(db, pSelect);
95489 break;
95492 if( pStep->op!=TK_SELECT ){
95493 sqlite3VdbeAddOp0(v, OP_ResetCount);
95497 return 0;
95500 #ifdef SQLITE_DEBUG
95502 ** This function is used to add VdbeComment() annotations to a VDBE
95503 ** program. It is not used in production code, only for debugging.
95505 static const char *onErrorText(int onError){
95506 switch( onError ){
95507 case OE_Abort: return "abort";
95508 case OE_Rollback: return "rollback";
95509 case OE_Fail: return "fail";
95510 case OE_Replace: return "replace";
95511 case OE_Ignore: return "ignore";
95512 case OE_Default: return "default";
95514 return "n/a";
95516 #endif
95519 ** Parse context structure pFrom has just been used to create a sub-vdbe
95520 ** (trigger program). If an error has occurred, transfer error information
95521 ** from pFrom to pTo.
95523 static void transferParseError(Parse *pTo, Parse *pFrom){
95524 assert( pFrom->zErrMsg==0 || pFrom->nErr );
95525 assert( pTo->zErrMsg==0 || pTo->nErr );
95526 if( pTo->nErr==0 ){
95527 pTo->zErrMsg = pFrom->zErrMsg;
95528 pTo->nErr = pFrom->nErr;
95529 }else{
95530 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
95535 ** Create and populate a new TriggerPrg object with a sub-program
95536 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
95538 static TriggerPrg *codeRowTrigger(
95539 Parse *pParse, /* Current parse context */
95540 Trigger *pTrigger, /* Trigger to code */
95541 Table *pTab, /* The table pTrigger is attached to */
95542 int orconf /* ON CONFLICT policy to code trigger program with */
95544 Parse *pTop = sqlite3ParseToplevel(pParse);
95545 sqlite3 *db = pParse->db; /* Database handle */
95546 TriggerPrg *pPrg; /* Value to return */
95547 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
95548 Vdbe *v; /* Temporary VM */
95549 NameContext sNC; /* Name context for sub-vdbe */
95550 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
95551 Parse *pSubParse; /* Parse context for sub-vdbe */
95552 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
95554 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
95555 assert( pTop->pVdbe );
95557 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
95558 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
95559 ** list of the top-level Parse object sooner rather than later. */
95560 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
95561 if( !pPrg ) return 0;
95562 pPrg->pNext = pTop->pTriggerPrg;
95563 pTop->pTriggerPrg = pPrg;
95564 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
95565 if( !pProgram ) return 0;
95566 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
95567 pPrg->pTrigger = pTrigger;
95568 pPrg->orconf = orconf;
95569 pPrg->aColmask[0] = 0xffffffff;
95570 pPrg->aColmask[1] = 0xffffffff;
95572 /* Allocate and populate a new Parse context to use for coding the
95573 ** trigger sub-program. */
95574 pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
95575 if( !pSubParse ) return 0;
95576 memset(&sNC, 0, sizeof(sNC));
95577 sNC.pParse = pSubParse;
95578 pSubParse->db = db;
95579 pSubParse->pTriggerTab = pTab;
95580 pSubParse->pToplevel = pTop;
95581 pSubParse->zAuthContext = pTrigger->zName;
95582 pSubParse->eTriggerOp = pTrigger->op;
95583 pSubParse->nQueryLoop = pParse->nQueryLoop;
95585 v = sqlite3GetVdbe(pSubParse);
95586 if( v ){
95587 VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
95588 pTrigger->zName, onErrorText(orconf),
95589 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
95590 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
95591 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
95592 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
95593 pTab->zName
95595 #ifndef SQLITE_OMIT_TRACE
95596 sqlite3VdbeChangeP4(v, -1,
95597 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
95599 #endif
95601 /* If one was specified, code the WHEN clause. If it evaluates to false
95602 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
95603 ** OP_Halt inserted at the end of the program. */
95604 if( pTrigger->pWhen ){
95605 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
95606 if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
95607 && db->mallocFailed==0
95609 iEndTrigger = sqlite3VdbeMakeLabel(v);
95610 sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
95612 sqlite3ExprDelete(db, pWhen);
95615 /* Code the trigger program into the sub-vdbe. */
95616 codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
95618 /* Insert an OP_Halt at the end of the sub-program. */
95619 if( iEndTrigger ){
95620 sqlite3VdbeResolveLabel(v, iEndTrigger);
95622 sqlite3VdbeAddOp0(v, OP_Halt);
95623 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
95625 transferParseError(pParse, pSubParse);
95626 if( db->mallocFailed==0 ){
95627 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
95629 pProgram->nMem = pSubParse->nMem;
95630 pProgram->nCsr = pSubParse->nTab;
95631 pProgram->token = (void *)pTrigger;
95632 pPrg->aColmask[0] = pSubParse->oldmask;
95633 pPrg->aColmask[1] = pSubParse->newmask;
95634 sqlite3VdbeDelete(v);
95637 assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
95638 assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
95639 sqlite3StackFree(db, pSubParse);
95641 return pPrg;
95645 ** Return a pointer to a TriggerPrg object containing the sub-program for
95646 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
95647 ** TriggerPrg object exists, a new object is allocated and populated before
95648 ** being returned.
95650 static TriggerPrg *getRowTrigger(
95651 Parse *pParse, /* Current parse context */
95652 Trigger *pTrigger, /* Trigger to code */
95653 Table *pTab, /* The table trigger pTrigger is attached to */
95654 int orconf /* ON CONFLICT algorithm. */
95656 Parse *pRoot = sqlite3ParseToplevel(pParse);
95657 TriggerPrg *pPrg;
95659 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
95661 /* It may be that this trigger has already been coded (or is in the
95662 ** process of being coded). If this is the case, then an entry with
95663 ** a matching TriggerPrg.pTrigger field will be present somewhere
95664 ** in the Parse.pTriggerPrg list. Search for such an entry. */
95665 for(pPrg=pRoot->pTriggerPrg;
95666 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
95667 pPrg=pPrg->pNext
95670 /* If an existing TriggerPrg could not be located, create a new one. */
95671 if( !pPrg ){
95672 pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
95675 return pPrg;
95679 ** Generate code for the trigger program associated with trigger p on
95680 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
95681 ** function are the same as those described in the header function for
95682 ** sqlite3CodeRowTrigger()
95684 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
95685 Parse *pParse, /* Parse context */
95686 Trigger *p, /* Trigger to code */
95687 Table *pTab, /* The table to code triggers from */
95688 int reg, /* Reg array containing OLD.* and NEW.* values */
95689 int orconf, /* ON CONFLICT policy */
95690 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
95692 Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
95693 TriggerPrg *pPrg;
95694 pPrg = getRowTrigger(pParse, p, pTab, orconf);
95695 assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
95697 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
95698 ** is a pointer to the sub-vdbe containing the trigger program. */
95699 if( pPrg ){
95700 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
95702 sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
95703 sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
95704 VdbeComment(
95705 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
95707 /* Set the P5 operand of the OP_Program instruction to non-zero if
95708 ** recursive invocation of this trigger program is disallowed. Recursive
95709 ** invocation is disallowed if (a) the sub-program is really a trigger,
95710 ** not a foreign key action, and (b) the flag to enable recursive triggers
95711 ** is clear. */
95712 sqlite3VdbeChangeP5(v, (u8)bRecursive);
95717 ** This is called to code the required FOR EACH ROW triggers for an operation
95718 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
95719 ** is given by the op paramater. The tr_tm parameter determines whether the
95720 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
95721 ** parameter pChanges is passed the list of columns being modified.
95723 ** If there are no triggers that fire at the specified time for the specified
95724 ** operation on pTab, this function is a no-op.
95726 ** The reg argument is the address of the first in an array of registers
95727 ** that contain the values substituted for the new.* and old.* references
95728 ** in the trigger program. If N is the number of columns in table pTab
95729 ** (a copy of pTab->nCol), then registers are populated as follows:
95731 ** Register Contains
95732 ** ------------------------------------------------------
95733 ** reg+0 OLD.rowid
95734 ** reg+1 OLD.* value of left-most column of pTab
95735 ** ... ...
95736 ** reg+N OLD.* value of right-most column of pTab
95737 ** reg+N+1 NEW.rowid
95738 ** reg+N+2 OLD.* value of left-most column of pTab
95739 ** ... ...
95740 ** reg+N+N+1 NEW.* value of right-most column of pTab
95742 ** For ON DELETE triggers, the registers containing the NEW.* values will
95743 ** never be accessed by the trigger program, so they are not allocated or
95744 ** populated by the caller (there is no data to populate them with anyway).
95745 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
95746 ** are never accessed, and so are not allocated by the caller. So, for an
95747 ** ON INSERT trigger, the value passed to this function as parameter reg
95748 ** is not a readable register, although registers (reg+N) through
95749 ** (reg+N+N+1) are.
95751 ** Parameter orconf is the default conflict resolution algorithm for the
95752 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
95753 ** is the instruction that control should jump to if a trigger program
95754 ** raises an IGNORE exception.
95756 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
95757 Parse *pParse, /* Parse context */
95758 Trigger *pTrigger, /* List of triggers on table pTab */
95759 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
95760 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
95761 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
95762 Table *pTab, /* The table to code triggers from */
95763 int reg, /* The first in an array of registers (see above) */
95764 int orconf, /* ON CONFLICT policy */
95765 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
95767 Trigger *p; /* Used to iterate through pTrigger list */
95769 assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
95770 assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
95771 assert( (op==TK_UPDATE)==(pChanges!=0) );
95773 for(p=pTrigger; p; p=p->pNext){
95775 /* Sanity checking: The schema for the trigger and for the table are
95776 ** always defined. The trigger must be in the same schema as the table
95777 ** or else it must be a TEMP trigger. */
95778 assert( p->pSchema!=0 );
95779 assert( p->pTabSchema!=0 );
95780 assert( p->pSchema==p->pTabSchema
95781 || p->pSchema==pParse->db->aDb[1].pSchema );
95783 /* Determine whether we should code this trigger */
95784 if( p->op==op
95785 && p->tr_tm==tr_tm
95786 && checkColumnOverlap(p->pColumns, pChanges)
95788 sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
95794 ** Triggers may access values stored in the old.* or new.* pseudo-table.
95795 ** This function returns a 32-bit bitmask indicating which columns of the
95796 ** old.* or new.* tables actually are used by triggers. This information
95797 ** may be used by the caller, for example, to avoid having to load the entire
95798 ** old.* record into memory when executing an UPDATE or DELETE command.
95800 ** Bit 0 of the returned mask is set if the left-most column of the
95801 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
95802 ** the second leftmost column value is required, and so on. If there
95803 ** are more than 32 columns in the table, and at least one of the columns
95804 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
95806 ** It is not possible to determine if the old.rowid or new.rowid column is
95807 ** accessed by triggers. The caller must always assume that it is.
95809 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
95810 ** applies to the old.* table. If 1, the new.* table.
95812 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
95813 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
95814 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
95815 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
95816 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
95818 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
95819 Parse *pParse, /* Parse context */
95820 Trigger *pTrigger, /* List of triggers on table pTab */
95821 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
95822 int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
95823 int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95824 Table *pTab, /* The table to code triggers from */
95825 int orconf /* Default ON CONFLICT policy for trigger steps */
95827 const int op = pChanges ? TK_UPDATE : TK_DELETE;
95828 u32 mask = 0;
95829 Trigger *p;
95831 assert( isNew==1 || isNew==0 );
95832 for(p=pTrigger; p; p=p->pNext){
95833 if( p->op==op && (tr_tm&p->tr_tm)
95834 && checkColumnOverlap(p->pColumns,pChanges)
95836 TriggerPrg *pPrg;
95837 pPrg = getRowTrigger(pParse, p, pTab, orconf);
95838 if( pPrg ){
95839 mask |= pPrg->aColmask[isNew];
95844 return mask;
95847 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
95849 /************** End of trigger.c *********************************************/
95850 /************** Begin file update.c ******************************************/
95852 ** 2001 September 15
95854 ** The author disclaims copyright to this source code. In place of
95855 ** a legal notice, here is a blessing:
95857 ** May you do good and not evil.
95858 ** May you find forgiveness for yourself and forgive others.
95859 ** May you share freely, never taking more than you give.
95861 *************************************************************************
95862 ** This file contains C code routines that are called by the parser
95863 ** to handle UPDATE statements.
95866 #ifndef SQLITE_OMIT_VIRTUALTABLE
95867 /* Forward declaration */
95868 static void updateVirtualTable(
95869 Parse *pParse, /* The parsing context */
95870 SrcList *pSrc, /* The virtual table to be modified */
95871 Table *pTab, /* The virtual table */
95872 ExprList *pChanges, /* The columns to change in the UPDATE statement */
95873 Expr *pRowidExpr, /* Expression used to recompute the rowid */
95874 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
95875 Expr *pWhere /* WHERE clause of the UPDATE statement */
95877 #endif /* SQLITE_OMIT_VIRTUALTABLE */
95880 ** The most recently coded instruction was an OP_Column to retrieve the
95881 ** i-th column of table pTab. This routine sets the P4 parameter of the
95882 ** OP_Column to the default value, if any.
95884 ** The default value of a column is specified by a DEFAULT clause in the
95885 ** column definition. This was either supplied by the user when the table
95886 ** was created, or added later to the table definition by an ALTER TABLE
95887 ** command. If the latter, then the row-records in the table btree on disk
95888 ** may not contain a value for the column and the default value, taken
95889 ** from the P4 parameter of the OP_Column instruction, is returned instead.
95890 ** If the former, then all row-records are guaranteed to include a value
95891 ** for the column and the P4 value is not required.
95893 ** Column definitions created by an ALTER TABLE command may only have
95894 ** literal default values specified: a number, null or a string. (If a more
95895 ** complicated default expression value was provided, it is evaluated
95896 ** when the ALTER TABLE is executed and one of the literal values written
95897 ** into the sqlite_master table.)
95899 ** Therefore, the P4 parameter is only required if the default value for
95900 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
95901 ** function is capable of transforming these types of expressions into
95902 ** sqlite3_value objects.
95904 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
95905 ** on register iReg. This is used when an equivalent integer value is
95906 ** stored in place of an 8-byte floating point value in order to save
95907 ** space.
95909 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
95910 assert( pTab!=0 );
95911 if( !pTab->pSelect ){
95912 sqlite3_value *pValue;
95913 u8 enc = ENC(sqlite3VdbeDb(v));
95914 Column *pCol = &pTab->aCol[i];
95915 VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
95916 assert( i<pTab->nCol );
95917 sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
95918 pCol->affinity, &pValue);
95919 if( pValue ){
95920 sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
95922 #ifndef SQLITE_OMIT_FLOATING_POINT
95923 if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
95924 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
95926 #endif
95931 ** Process an UPDATE statement.
95933 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
95934 ** \_______/ \________/ \______/ \________________/
95935 * onError pTabList pChanges pWhere
95937 SQLITE_PRIVATE void sqlite3Update(
95938 Parse *pParse, /* The parser context */
95939 SrcList *pTabList, /* The table in which we should change things */
95940 ExprList *pChanges, /* Things to be changed */
95941 Expr *pWhere, /* The WHERE clause. May be null */
95942 int onError /* How to handle constraint errors */
95944 int i, j; /* Loop counters */
95945 Table *pTab; /* The table to be updated */
95946 int addr = 0; /* VDBE instruction address of the start of the loop */
95947 WhereInfo *pWInfo; /* Information about the WHERE clause */
95948 Vdbe *v; /* The virtual database engine */
95949 Index *pIdx; /* For looping over indices */
95950 int nIdx; /* Number of indices that need updating */
95951 int iCur; /* VDBE Cursor number of pTab */
95952 sqlite3 *db; /* The database structure */
95953 int *aRegIdx = 0; /* One register assigned to each index to be updated */
95954 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
95955 ** an expression for the i-th column of the table.
95956 ** aXRef[i]==-1 if the i-th column is not changed. */
95957 int chngRowid; /* True if the record number is being changed */
95958 Expr *pRowidExpr = 0; /* Expression defining the new record number */
95959 int openAll = 0; /* True if all indices need to be opened */
95960 AuthContext sContext; /* The authorization context */
95961 NameContext sNC; /* The name-context to resolve expressions in */
95962 int iDb; /* Database containing the table being updated */
95963 int okOnePass; /* True for one-pass algorithm without the FIFO */
95964 int hasFK; /* True if foreign key processing is required */
95966 #ifndef SQLITE_OMIT_TRIGGER
95967 int isView; /* True when updating a view (INSTEAD OF trigger) */
95968 Trigger *pTrigger; /* List of triggers on pTab, if required */
95969 int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95970 #endif
95971 int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
95973 /* Register Allocations */
95974 int regRowCount = 0; /* A count of rows changed */
95975 int regOldRowid; /* The old rowid */
95976 int regNewRowid; /* The new rowid */
95977 int regNew;
95978 int regOld = 0;
95979 int regRowSet = 0; /* Rowset of rows to be updated */
95981 memset(&sContext, 0, sizeof(sContext));
95982 db = pParse->db;
95983 if( pParse->nErr || db->mallocFailed ){
95984 goto update_cleanup;
95986 assert( pTabList->nSrc==1 );
95988 /* Locate the table which we want to update.
95990 pTab = sqlite3SrcListLookup(pParse, pTabList);
95991 if( pTab==0 ) goto update_cleanup;
95992 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95994 /* Figure out if we have any triggers and if the table being
95995 ** updated is a view.
95997 #ifndef SQLITE_OMIT_TRIGGER
95998 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
95999 isView = pTab->pSelect!=0;
96000 assert( pTrigger || tmask==0 );
96001 #else
96002 # define pTrigger 0
96003 # define isView 0
96004 # define tmask 0
96005 #endif
96006 #ifdef SQLITE_OMIT_VIEW
96007 # undef isView
96008 # define isView 0
96009 #endif
96011 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
96012 goto update_cleanup;
96014 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
96015 goto update_cleanup;
96017 aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
96018 if( aXRef==0 ) goto update_cleanup;
96019 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
96021 /* Allocate a cursors for the main database table and for all indices.
96022 ** The index cursors might not be used, but if they are used they
96023 ** need to occur right after the database cursor. So go ahead and
96024 ** allocate enough space, just in case.
96026 pTabList->a[0].iCursor = iCur = pParse->nTab++;
96027 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96028 pParse->nTab++;
96031 /* Initialize the name-context */
96032 memset(&sNC, 0, sizeof(sNC));
96033 sNC.pParse = pParse;
96034 sNC.pSrcList = pTabList;
96036 /* Resolve the column names in all the expressions of the
96037 ** of the UPDATE statement. Also find the column index
96038 ** for each column to be updated in the pChanges array. For each
96039 ** column to be updated, make sure we have authorization to change
96040 ** that column.
96042 chngRowid = 0;
96043 for(i=0; i<pChanges->nExpr; i++){
96044 if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
96045 goto update_cleanup;
96047 for(j=0; j<pTab->nCol; j++){
96048 if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
96049 if( j==pTab->iPKey ){
96050 chngRowid = 1;
96051 pRowidExpr = pChanges->a[i].pExpr;
96053 aXRef[j] = i;
96054 break;
96057 if( j>=pTab->nCol ){
96058 if( sqlite3IsRowid(pChanges->a[i].zName) ){
96059 chngRowid = 1;
96060 pRowidExpr = pChanges->a[i].pExpr;
96061 }else{
96062 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
96063 pParse->checkSchema = 1;
96064 goto update_cleanup;
96067 #ifndef SQLITE_OMIT_AUTHORIZATION
96069 int rc;
96070 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
96071 pTab->aCol[j].zName, db->aDb[iDb].zName);
96072 if( rc==SQLITE_DENY ){
96073 goto update_cleanup;
96074 }else if( rc==SQLITE_IGNORE ){
96075 aXRef[j] = -1;
96078 #endif
96081 hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
96083 /* Allocate memory for the array aRegIdx[]. There is one entry in the
96084 ** array for each index associated with table being updated. Fill in
96085 ** the value with a register number for indices that are to be used
96086 ** and with zero for unused indices.
96088 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
96089 if( nIdx>0 ){
96090 aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
96091 if( aRegIdx==0 ) goto update_cleanup;
96093 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
96094 int reg;
96095 if( chngRowid ){
96096 reg = ++pParse->nMem;
96097 }else{
96098 reg = 0;
96099 for(i=0; i<pIdx->nColumn; i++){
96100 if( aXRef[pIdx->aiColumn[i]]>=0 ){
96101 reg = ++pParse->nMem;
96102 break;
96106 aRegIdx[j] = reg;
96109 /* Begin generating code. */
96110 v = sqlite3GetVdbe(pParse);
96111 if( v==0 ) goto update_cleanup;
96112 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
96113 sqlite3BeginWriteOperation(pParse, 1, iDb);
96115 #ifndef SQLITE_OMIT_VIRTUALTABLE
96116 /* Virtual tables must be handled separately */
96117 if( IsVirtual(pTab) ){
96118 updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
96119 pWhere);
96120 pWhere = 0;
96121 pTabList = 0;
96122 goto update_cleanup;
96124 #endif
96126 /* Allocate required registers. */
96127 regOldRowid = regNewRowid = ++pParse->nMem;
96128 if( pTrigger || hasFK ){
96129 regOld = pParse->nMem + 1;
96130 pParse->nMem += pTab->nCol;
96132 if( chngRowid || pTrigger || hasFK ){
96133 regNewRowid = ++pParse->nMem;
96135 regNew = pParse->nMem + 1;
96136 pParse->nMem += pTab->nCol;
96138 /* Start the view context. */
96139 if( isView ){
96140 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
96143 /* If we are trying to update a view, realize that view into
96144 ** a ephemeral table.
96146 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
96147 if( isView ){
96148 sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
96150 #endif
96152 /* Resolve the column names in all the expressions in the
96153 ** WHERE clause.
96155 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
96156 goto update_cleanup;
96159 /* Begin the database scan
96161 sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
96162 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
96163 if( pWInfo==0 ) goto update_cleanup;
96164 okOnePass = pWInfo->okOnePass;
96166 /* Remember the rowid of every item to be updated.
96168 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
96169 if( !okOnePass ){
96170 regRowSet = ++pParse->nMem;
96171 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
96174 /* End the database scan loop.
96176 sqlite3WhereEnd(pWInfo);
96178 /* Initialize the count of updated rows
96180 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
96181 regRowCount = ++pParse->nMem;
96182 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
96185 if( !isView ){
96187 ** Open every index that needs updating. Note that if any
96188 ** index could potentially invoke a REPLACE conflict resolution
96189 ** action, then we need to open all indices because we might need
96190 ** to be deleting some records.
96192 if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
96193 if( onError==OE_Replace ){
96194 openAll = 1;
96195 }else{
96196 openAll = 0;
96197 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96198 if( pIdx->onError==OE_Replace ){
96199 openAll = 1;
96200 break;
96204 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
96205 if( openAll || aRegIdx[i]>0 ){
96206 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
96207 sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
96208 (char*)pKey, P4_KEYINFO_HANDOFF);
96209 assert( pParse->nTab>iCur+i+1 );
96214 /* Top of the update loop */
96215 if( okOnePass ){
96216 int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
96217 addr = sqlite3VdbeAddOp0(v, OP_Goto);
96218 sqlite3VdbeJumpHere(v, a1);
96219 }else{
96220 addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
96223 /* Make cursor iCur point to the record that is being updated. If
96224 ** this record does not exist for some reason (deleted by a trigger,
96225 ** for example, then jump to the next iteration of the RowSet loop. */
96226 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
96228 /* If the record number will change, set register regNewRowid to
96229 ** contain the new value. If the record number is not being modified,
96230 ** then regNewRowid is the same register as regOldRowid, which is
96231 ** already populated. */
96232 assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
96233 if( chngRowid ){
96234 sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
96235 sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
96238 /* If there are triggers on this table, populate an array of registers
96239 ** with the required old.* column data. */
96240 if( hasFK || pTrigger ){
96241 u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
96242 oldmask |= sqlite3TriggerColmask(pParse,
96243 pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
96245 for(i=0; i<pTab->nCol; i++){
96246 if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
96247 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
96248 }else{
96249 sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
96252 if( chngRowid==0 ){
96253 sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
96257 /* Populate the array of registers beginning at regNew with the new
96258 ** row data. This array is used to check constaints, create the new
96259 ** table and index records, and as the values for any new.* references
96260 ** made by triggers.
96262 ** If there are one or more BEFORE triggers, then do not populate the
96263 ** registers associated with columns that are (a) not modified by
96264 ** this UPDATE statement and (b) not accessed by new.* references. The
96265 ** values for registers not modified by the UPDATE must be reloaded from
96266 ** the database after the BEFORE triggers are fired anyway (as the trigger
96267 ** may have modified them). So not loading those that are not going to
96268 ** be used eliminates some redundant opcodes.
96270 newmask = sqlite3TriggerColmask(
96271 pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
96273 for(i=0; i<pTab->nCol; i++){
96274 if( i==pTab->iPKey ){
96275 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
96276 }else{
96277 j = aXRef[i];
96278 if( j>=0 ){
96279 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
96280 }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
96281 /* This branch loads the value of a column that will not be changed
96282 ** into a register. This is done if there are no BEFORE triggers, or
96283 ** if there are one or more BEFORE triggers that use this value via
96284 ** a new.* reference in a trigger program.
96286 testcase( i==31 );
96287 testcase( i==32 );
96288 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96289 sqlite3ColumnDefault(v, pTab, i, regNew+i);
96294 /* Fire any BEFORE UPDATE triggers. This happens before constraints are
96295 ** verified. One could argue that this is wrong.
96297 if( tmask&TRIGGER_BEFORE ){
96298 sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
96299 sqlite3TableAffinityStr(v, pTab);
96300 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
96301 TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
96303 /* The row-trigger may have deleted the row being updated. In this
96304 ** case, jump to the next row. No updates or AFTER triggers are
96305 ** required. This behaviour - what happens when the row being updated
96306 ** is deleted or renamed by a BEFORE trigger - is left undefined in the
96307 ** documentation.
96309 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
96311 /* If it did not delete it, the row-trigger may still have modified
96312 ** some of the columns of the row being updated. Load the values for
96313 ** all columns not modified by the update statement into their
96314 ** registers in case this has happened.
96316 for(i=0; i<pTab->nCol; i++){
96317 if( aXRef[i]<0 && i!=pTab->iPKey ){
96318 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96319 sqlite3ColumnDefault(v, pTab, i, regNew+i);
96324 if( !isView ){
96325 int j1; /* Address of jump instruction */
96327 /* Do constraint checks. */
96328 sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
96329 aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
96331 /* Do FK constraint checks. */
96332 if( hasFK ){
96333 sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
96336 /* Delete the index entries associated with the current record. */
96337 j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
96338 sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
96340 /* If changing the record number, delete the old record. */
96341 if( hasFK || chngRowid ){
96342 sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
96344 sqlite3VdbeJumpHere(v, j1);
96346 if( hasFK ){
96347 sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
96350 /* Insert the new index entries and the new record. */
96351 sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
96353 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
96354 ** handle rows (possibly in other tables) that refer via a foreign key
96355 ** to the row just updated. */
96356 if( hasFK ){
96357 sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
96361 /* Increment the row counter
96363 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
96364 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
96367 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
96368 TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
96370 /* Repeat the above with the next record to be updated, until
96371 ** all record selected by the WHERE clause have been updated.
96373 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
96374 sqlite3VdbeJumpHere(v, addr);
96376 /* Close all tables */
96377 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
96378 if( openAll || aRegIdx[i]>0 ){
96379 sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
96382 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
96384 /* Update the sqlite_sequence table by storing the content of the
96385 ** maximum rowid counter values recorded while inserting into
96386 ** autoincrement tables.
96388 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
96389 sqlite3AutoincrementEnd(pParse);
96393 ** Return the number of rows that were changed. If this routine is
96394 ** generating code because of a call to sqlite3NestedParse(), do not
96395 ** invoke the callback function.
96397 if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
96398 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
96399 sqlite3VdbeSetNumCols(v, 1);
96400 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
96403 update_cleanup:
96404 sqlite3AuthContextPop(&sContext);
96405 sqlite3DbFree(db, aRegIdx);
96406 sqlite3DbFree(db, aXRef);
96407 sqlite3SrcListDelete(db, pTabList);
96408 sqlite3ExprListDelete(db, pChanges);
96409 sqlite3ExprDelete(db, pWhere);
96410 return;
96412 /* Make sure "isView" and other macros defined above are undefined. Otherwise
96413 ** thely may interfere with compilation of other functions in this file
96414 ** (or in another file, if this file becomes part of the amalgamation). */
96415 #ifdef isView
96416 #undef isView
96417 #endif
96418 #ifdef pTrigger
96419 #undef pTrigger
96420 #endif
96422 #ifndef SQLITE_OMIT_VIRTUALTABLE
96424 ** Generate code for an UPDATE of a virtual table.
96426 ** The strategy is that we create an ephemerial table that contains
96427 ** for each row to be changed:
96429 ** (A) The original rowid of that row.
96430 ** (B) The revised rowid for the row. (note1)
96431 ** (C) The content of every column in the row.
96433 ** Then we loop over this ephemeral table and for each row in
96434 ** the ephermeral table call VUpdate.
96436 ** When finished, drop the ephemeral table.
96438 ** (note1) Actually, if we know in advance that (A) is always the same
96439 ** as (B) we only store (A), then duplicate (A) when pulling
96440 ** it out of the ephemeral table before calling VUpdate.
96442 static void updateVirtualTable(
96443 Parse *pParse, /* The parsing context */
96444 SrcList *pSrc, /* The virtual table to be modified */
96445 Table *pTab, /* The virtual table */
96446 ExprList *pChanges, /* The columns to change in the UPDATE statement */
96447 Expr *pRowid, /* Expression used to recompute the rowid */
96448 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
96449 Expr *pWhere /* WHERE clause of the UPDATE statement */
96451 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
96452 ExprList *pEList = 0; /* The result set of the SELECT statement */
96453 Select *pSelect = 0; /* The SELECT statement */
96454 Expr *pExpr; /* Temporary expression */
96455 int ephemTab; /* Table holding the result of the SELECT */
96456 int i; /* Loop counter */
96457 int addr; /* Address of top of loop */
96458 int iReg; /* First register in set passed to OP_VUpdate */
96459 sqlite3 *db = pParse->db; /* Database connection */
96460 const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
96461 SelectDest dest;
96463 /* Construct the SELECT statement that will find the new values for
96464 ** all updated rows.
96466 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
96467 if( pRowid ){
96468 pEList = sqlite3ExprListAppend(pParse, pEList,
96469 sqlite3ExprDup(db, pRowid, 0));
96471 assert( pTab->iPKey<0 );
96472 for(i=0; i<pTab->nCol; i++){
96473 if( aXRef[i]>=0 ){
96474 pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
96475 }else{
96476 pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
96478 pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
96480 pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
96482 /* Create the ephemeral table into which the update results will
96483 ** be stored.
96485 assert( v );
96486 ephemTab = pParse->nTab++;
96487 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
96488 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96490 /* fill the ephemeral table
96492 sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
96493 sqlite3Select(pParse, pSelect, &dest);
96495 /* Generate code to scan the ephemeral table and call VUpdate. */
96496 iReg = ++pParse->nMem;
96497 pParse->nMem += pTab->nCol+1;
96498 addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
96499 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
96500 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
96501 for(i=0; i<pTab->nCol; i++){
96502 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
96504 sqlite3VtabMakeWritable(pParse, pTab);
96505 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
96506 sqlite3MayAbort(pParse);
96507 sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
96508 sqlite3VdbeJumpHere(v, addr);
96509 sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
96511 /* Cleanup */
96512 sqlite3SelectDelete(db, pSelect);
96514 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96516 /************** End of update.c **********************************************/
96517 /************** Begin file vacuum.c ******************************************/
96519 ** 2003 April 6
96521 ** The author disclaims copyright to this source code. In place of
96522 ** a legal notice, here is a blessing:
96524 ** May you do good and not evil.
96525 ** May you find forgiveness for yourself and forgive others.
96526 ** May you share freely, never taking more than you give.
96528 *************************************************************************
96529 ** This file contains code used to implement the VACUUM command.
96531 ** Most of the code in this file may be omitted by defining the
96532 ** SQLITE_OMIT_VACUUM macro.
96535 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
96537 ** Finalize a prepared statement. If there was an error, store the
96538 ** text of the error message in *pzErrMsg. Return the result code.
96540 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
96541 int rc;
96542 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
96543 if( rc ){
96544 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96546 return rc;
96550 ** Execute zSql on database db. Return an error code.
96552 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96553 sqlite3_stmt *pStmt;
96554 VVA_ONLY( int rc; )
96555 if( !zSql ){
96556 return SQLITE_NOMEM;
96558 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
96559 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96560 return sqlite3_errcode(db);
96562 VVA_ONLY( rc = ) sqlite3_step(pStmt);
96563 assert( rc!=SQLITE_ROW );
96564 return vacuumFinalize(db, pStmt, pzErrMsg);
96568 ** Execute zSql on database db. The statement returns exactly
96569 ** one column. Execute this as SQL on the same database.
96571 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96572 sqlite3_stmt *pStmt;
96573 int rc;
96575 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96576 if( rc!=SQLITE_OK ) return rc;
96578 while( SQLITE_ROW==sqlite3_step(pStmt) ){
96579 rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
96580 if( rc!=SQLITE_OK ){
96581 vacuumFinalize(db, pStmt, pzErrMsg);
96582 return rc;
96586 return vacuumFinalize(db, pStmt, pzErrMsg);
96590 ** The non-standard VACUUM command is used to clean up the database,
96591 ** collapse free space, etc. It is modelled after the VACUUM command
96592 ** in PostgreSQL.
96594 ** In version 1.0.x of SQLite, the VACUUM command would call
96595 ** gdbm_reorganize() on all the database tables. But beginning
96596 ** with 2.0.0, SQLite no longer uses GDBM so this command has
96597 ** become a no-op.
96599 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
96600 Vdbe *v = sqlite3GetVdbe(pParse);
96601 if( v ){
96602 sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
96604 return;
96608 ** This routine implements the OP_Vacuum opcode of the VDBE.
96610 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
96611 int rc = SQLITE_OK; /* Return code from service routines */
96612 Btree *pMain; /* The database being vacuumed */
96613 Btree *pTemp; /* The temporary database we vacuum into */
96614 char *zSql = 0; /* SQL statements */
96615 int saved_flags; /* Saved value of the db->flags */
96616 int saved_nChange; /* Saved value of db->nChange */
96617 int saved_nTotalChange; /* Saved value of db->nTotalChange */
96618 void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
96619 Db *pDb = 0; /* Database to detach at end of vacuum */
96620 int isMemDb; /* True if vacuuming a :memory: database */
96621 int nRes; /* Bytes of reserved space at the end of each page */
96622 int nDb; /* Number of attached databases */
96624 if( !db->autoCommit ){
96625 sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
96626 return SQLITE_ERROR;
96628 if( db->activeVdbeCnt>1 ){
96629 sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
96630 return SQLITE_ERROR;
96633 /* Save the current value of the database flags so that it can be
96634 ** restored before returning. Then set the writable-schema flag, and
96635 ** disable CHECK and foreign key constraints. */
96636 saved_flags = db->flags;
96637 saved_nChange = db->nChange;
96638 saved_nTotalChange = db->nTotalChange;
96639 saved_xTrace = db->xTrace;
96640 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
96641 db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
96642 db->xTrace = 0;
96644 pMain = db->aDb[0].pBt;
96645 isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
96647 /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
96648 ** can be set to 'off' for this file, as it is not recovered if a crash
96649 ** occurs anyway. The integrity of the database is maintained by a
96650 ** (possibly synchronous) transaction opened on the main database before
96651 ** sqlite3BtreeCopyFile() is called.
96653 ** An optimisation would be to use a non-journaled pager.
96654 ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
96655 ** that actually made the VACUUM run slower. Very little journalling
96656 ** actually occurs when doing a vacuum since the vacuum_db is initially
96657 ** empty. Only the journal header is written. Apparently it takes more
96658 ** time to parse and run the PRAGMA to turn journalling off than it does
96659 ** to write the journal header file.
96661 nDb = db->nDb;
96662 if( sqlite3TempInMemory(db) ){
96663 zSql = "ATTACH ':memory:' AS vacuum_db;";
96664 }else{
96665 zSql = "ATTACH '' AS vacuum_db;";
96667 rc = execSql(db, pzErrMsg, zSql);
96668 if( db->nDb>nDb ){
96669 pDb = &db->aDb[db->nDb-1];
96670 assert( strcmp(pDb->zName,"vacuum_db")==0 );
96672 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96673 pTemp = db->aDb[db->nDb-1].pBt;
96675 /* The call to execSql() to attach the temp database has left the file
96676 ** locked (as there was more than one active statement when the transaction
96677 ** to read the schema was concluded. Unlock it here so that this doesn't
96678 ** cause problems for the call to BtreeSetPageSize() below. */
96679 sqlite3BtreeCommit(pTemp);
96681 nRes = sqlite3BtreeGetReserve(pMain);
96683 /* A VACUUM cannot change the pagesize of an encrypted database. */
96684 #ifdef SQLITE_HAS_CODEC
96685 if( db->nextPagesize ){
96686 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
96687 int nKey;
96688 char *zKey;
96689 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
96690 if( nKey ) db->nextPagesize = 0;
96692 #endif
96694 /* Do not attempt to change the page size for a WAL database */
96695 if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
96696 ==PAGER_JOURNALMODE_WAL ){
96697 db->nextPagesize = 0;
96700 if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
96701 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
96702 || NEVER(db->mallocFailed)
96704 rc = SQLITE_NOMEM;
96705 goto end_of_vacuum;
96707 rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
96708 if( rc!=SQLITE_OK ){
96709 goto end_of_vacuum;
96712 #ifndef SQLITE_OMIT_AUTOVACUUM
96713 sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
96714 sqlite3BtreeGetAutoVacuum(pMain));
96715 #endif
96717 /* Begin a transaction */
96718 rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
96719 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96721 /* Query the schema of the main database. Create a mirror schema
96722 ** in the temporary database.
96724 rc = execExecSql(db, pzErrMsg,
96725 "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
96726 " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
96727 " AND rootpage>0"
96729 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96730 rc = execExecSql(db, pzErrMsg,
96731 "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
96732 " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
96733 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96734 rc = execExecSql(db, pzErrMsg,
96735 "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
96736 " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
96737 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96739 /* Loop through the tables in the main database. For each, do
96740 ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
96741 ** the contents to the temporary database.
96743 rc = execExecSql(db, pzErrMsg,
96744 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
96745 "|| ' SELECT * FROM main.' || quote(name) || ';'"
96746 "FROM main.sqlite_master "
96747 "WHERE type = 'table' AND name!='sqlite_sequence' "
96748 " AND rootpage>0"
96750 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96752 /* Copy over the sequence table
96754 rc = execExecSql(db, pzErrMsg,
96755 "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
96756 "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
96758 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96759 rc = execExecSql(db, pzErrMsg,
96760 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
96761 "|| ' SELECT * FROM main.' || quote(name) || ';' "
96762 "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
96764 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96767 /* Copy the triggers, views, and virtual tables from the main database
96768 ** over to the temporary database. None of these objects has any
96769 ** associated storage, so all we have to do is copy their entries
96770 ** from the SQLITE_MASTER table.
96772 rc = execSql(db, pzErrMsg,
96773 "INSERT INTO vacuum_db.sqlite_master "
96774 " SELECT type, name, tbl_name, rootpage, sql"
96775 " FROM main.sqlite_master"
96776 " WHERE type='view' OR type='trigger'"
96777 " OR (type='table' AND rootpage=0)"
96779 if( rc ) goto end_of_vacuum;
96781 /* At this point, unless the main db was completely empty, there is now a
96782 ** transaction open on the vacuum database, but not on the main database.
96783 ** Open a btree level transaction on the main database. This allows a
96784 ** call to sqlite3BtreeCopyFile(). The main database btree level
96785 ** transaction is then committed, so the SQL level never knows it was
96786 ** opened for writing. This way, the SQL transaction used to create the
96787 ** temporary database never needs to be committed.
96790 u32 meta;
96791 int i;
96793 /* This array determines which meta meta values are preserved in the
96794 ** vacuum. Even entries are the meta value number and odd entries
96795 ** are an increment to apply to the meta value after the vacuum.
96796 ** The increment is used to increase the schema cookie so that other
96797 ** connections to the same database will know to reread the schema.
96799 static const unsigned char aCopy[] = {
96800 BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
96801 BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
96802 BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
96803 BTREE_USER_VERSION, 0, /* Preserve the user version */
96806 assert( 1==sqlite3BtreeIsInTrans(pTemp) );
96807 assert( 1==sqlite3BtreeIsInTrans(pMain) );
96809 /* Copy Btree meta values */
96810 for(i=0; i<ArraySize(aCopy); i+=2){
96811 /* GetMeta() and UpdateMeta() cannot fail in this context because
96812 ** we already have page 1 loaded into cache and marked dirty. */
96813 sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
96814 rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
96815 if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
96818 rc = sqlite3BtreeCopyFile(pMain, pTemp);
96819 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96820 rc = sqlite3BtreeCommit(pTemp);
96821 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96822 #ifndef SQLITE_OMIT_AUTOVACUUM
96823 sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
96824 #endif
96827 assert( rc==SQLITE_OK );
96828 rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
96830 end_of_vacuum:
96831 /* Restore the original value of db->flags */
96832 db->flags = saved_flags;
96833 db->nChange = saved_nChange;
96834 db->nTotalChange = saved_nTotalChange;
96835 db->xTrace = saved_xTrace;
96836 sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
96838 /* Currently there is an SQL level transaction open on the vacuum
96839 ** database. No locks are held on any other files (since the main file
96840 ** was committed at the btree level). So it safe to end the transaction
96841 ** by manually setting the autoCommit flag to true and detaching the
96842 ** vacuum database. The vacuum_db journal file is deleted when the pager
96843 ** is closed by the DETACH.
96845 db->autoCommit = 1;
96847 if( pDb ){
96848 sqlite3BtreeClose(pDb->pBt);
96849 pDb->pBt = 0;
96850 pDb->pSchema = 0;
96853 /* This both clears the schemas and reduces the size of the db->aDb[]
96854 ** array. */
96855 sqlite3ResetInternalSchema(db, -1);
96857 return rc;
96860 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
96862 /************** End of vacuum.c **********************************************/
96863 /************** Begin file vtab.c ********************************************/
96865 ** 2006 June 10
96867 ** The author disclaims copyright to this source code. In place of
96868 ** a legal notice, here is a blessing:
96870 ** May you do good and not evil.
96871 ** May you find forgiveness for yourself and forgive others.
96872 ** May you share freely, never taking more than you give.
96874 *************************************************************************
96875 ** This file contains code used to help implement virtual tables.
96877 #ifndef SQLITE_OMIT_VIRTUALTABLE
96880 ** The actual function that does the work of creating a new module.
96881 ** This function implements the sqlite3_create_module() and
96882 ** sqlite3_create_module_v2() interfaces.
96884 static int createModule(
96885 sqlite3 *db, /* Database in which module is registered */
96886 const char *zName, /* Name assigned to this module */
96887 const sqlite3_module *pModule, /* The definition of the module */
96888 void *pAux, /* Context pointer for xCreate/xConnect */
96889 void (*xDestroy)(void *) /* Module destructor function */
96891 int rc, nName;
96892 Module *pMod;
96894 sqlite3_mutex_enter(db->mutex);
96895 nName = sqlite3Strlen30(zName);
96896 pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
96897 if( pMod ){
96898 Module *pDel;
96899 char *zCopy = (char *)(&pMod[1]);
96900 memcpy(zCopy, zName, nName+1);
96901 pMod->zName = zCopy;
96902 pMod->pModule = pModule;
96903 pMod->pAux = pAux;
96904 pMod->xDestroy = xDestroy;
96905 pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
96906 if( pDel && pDel->xDestroy ){
96907 pDel->xDestroy(pDel->pAux);
96909 sqlite3DbFree(db, pDel);
96910 if( pDel==pMod ){
96911 db->mallocFailed = 1;
96913 sqlite3ResetInternalSchema(db, -1);
96914 }else if( xDestroy ){
96915 xDestroy(pAux);
96917 rc = sqlite3ApiExit(db, SQLITE_OK);
96918 sqlite3_mutex_leave(db->mutex);
96919 return rc;
96924 ** External API function used to create a new virtual-table module.
96926 SQLITE_API int sqlite3_create_module(
96927 sqlite3 *db, /* Database in which module is registered */
96928 const char *zName, /* Name assigned to this module */
96929 const sqlite3_module *pModule, /* The definition of the module */
96930 void *pAux /* Context pointer for xCreate/xConnect */
96932 return createModule(db, zName, pModule, pAux, 0);
96936 ** External API function used to create a new virtual-table module.
96938 SQLITE_API int sqlite3_create_module_v2(
96939 sqlite3 *db, /* Database in which module is registered */
96940 const char *zName, /* Name assigned to this module */
96941 const sqlite3_module *pModule, /* The definition of the module */
96942 void *pAux, /* Context pointer for xCreate/xConnect */
96943 void (*xDestroy)(void *) /* Module destructor function */
96945 return createModule(db, zName, pModule, pAux, xDestroy);
96949 ** Lock the virtual table so that it cannot be disconnected.
96950 ** Locks nest. Every lock should have a corresponding unlock.
96951 ** If an unlock is omitted, resources leaks will occur.
96953 ** If a disconnect is attempted while a virtual table is locked,
96954 ** the disconnect is deferred until all locks have been removed.
96956 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
96957 pVTab->nRef++;
96962 ** pTab is a pointer to a Table structure representing a virtual-table.
96963 ** Return a pointer to the VTable object used by connection db to access
96964 ** this virtual-table, if one has been created, or NULL otherwise.
96966 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
96967 VTable *pVtab;
96968 assert( IsVirtual(pTab) );
96969 for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
96970 return pVtab;
96974 ** Decrement the ref-count on a virtual table object. When the ref-count
96975 ** reaches zero, call the xDisconnect() method to delete the object.
96977 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
96978 sqlite3 *db = pVTab->db;
96980 assert( db );
96981 assert( pVTab->nRef>0 );
96982 assert( sqlite3SafetyCheckOk(db) );
96984 pVTab->nRef--;
96985 if( pVTab->nRef==0 ){
96986 sqlite3_vtab *p = pVTab->pVtab;
96987 if( p ){
96988 p->pModule->xDisconnect(p);
96990 sqlite3DbFree(db, pVTab);
96995 ** Table p is a virtual table. This function moves all elements in the
96996 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
96997 ** database connections to be disconnected at the next opportunity.
96998 ** Except, if argument db is not NULL, then the entry associated with
96999 ** connection db is left in the p->pVTable list.
97001 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
97002 VTable *pRet = 0;
97003 VTable *pVTable = p->pVTable;
97004 p->pVTable = 0;
97006 /* Assert that the mutex (if any) associated with the BtShared database
97007 ** that contains table p is held by the caller. See header comments
97008 ** above function sqlite3VtabUnlockList() for an explanation of why
97009 ** this makes it safe to access the sqlite3.pDisconnect list of any
97010 ** database connection that may have an entry in the p->pVTable list.
97012 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
97014 while( pVTable ){
97015 sqlite3 *db2 = pVTable->db;
97016 VTable *pNext = pVTable->pNext;
97017 assert( db2 );
97018 if( db2==db ){
97019 pRet = pVTable;
97020 p->pVTable = pRet;
97021 pRet->pNext = 0;
97022 }else{
97023 pVTable->pNext = db2->pDisconnect;
97024 db2->pDisconnect = pVTable;
97026 pVTable = pNext;
97029 assert( !db || pRet );
97030 return pRet;
97035 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
97037 ** This function may only be called when the mutexes associated with all
97038 ** shared b-tree databases opened using connection db are held by the
97039 ** caller. This is done to protect the sqlite3.pDisconnect list. The
97040 ** sqlite3.pDisconnect list is accessed only as follows:
97042 ** 1) By this function. In this case, all BtShared mutexes and the mutex
97043 ** associated with the database handle itself must be held.
97045 ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
97046 ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
97047 ** associated with the database the virtual table is stored in is held
97048 ** or, if the virtual table is stored in a non-sharable database, then
97049 ** the database handle mutex is held.
97051 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
97052 ** by multiple threads. It is thread-safe.
97054 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
97055 VTable *p = db->pDisconnect;
97056 db->pDisconnect = 0;
97058 assert( sqlite3BtreeHoldsAllMutexes(db) );
97059 assert( sqlite3_mutex_held(db->mutex) );
97061 if( p ){
97062 sqlite3ExpirePreparedStatements(db);
97063 do {
97064 VTable *pNext = p->pNext;
97065 sqlite3VtabUnlock(p);
97066 p = pNext;
97067 }while( p );
97072 ** Clear any and all virtual-table information from the Table record.
97073 ** This routine is called, for example, just before deleting the Table
97074 ** record.
97076 ** Since it is a virtual-table, the Table structure contains a pointer
97077 ** to the head of a linked list of VTable structures. Each VTable
97078 ** structure is associated with a single sqlite3* user of the schema.
97079 ** The reference count of the VTable structure associated with database
97080 ** connection db is decremented immediately (which may lead to the
97081 ** structure being xDisconnected and free). Any other VTable structures
97082 ** in the list are moved to the sqlite3.pDisconnect list of the associated
97083 ** database connection.
97085 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
97086 if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
97087 if( p->azModuleArg ){
97088 int i;
97089 for(i=0; i<p->nModuleArg; i++){
97090 sqlite3DbFree(db, p->azModuleArg[i]);
97092 sqlite3DbFree(db, p->azModuleArg);
97097 ** Add a new module argument to pTable->azModuleArg[].
97098 ** The string is not copied - the pointer is stored. The
97099 ** string will be freed automatically when the table is
97100 ** deleted.
97102 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
97103 int i = pTable->nModuleArg++;
97104 int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
97105 char **azModuleArg;
97106 azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
97107 if( azModuleArg==0 ){
97108 int j;
97109 for(j=0; j<i; j++){
97110 sqlite3DbFree(db, pTable->azModuleArg[j]);
97112 sqlite3DbFree(db, zArg);
97113 sqlite3DbFree(db, pTable->azModuleArg);
97114 pTable->nModuleArg = 0;
97115 }else{
97116 azModuleArg[i] = zArg;
97117 azModuleArg[i+1] = 0;
97119 pTable->azModuleArg = azModuleArg;
97123 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
97124 ** statement. The module name has been parsed, but the optional list
97125 ** of parameters that follow the module name are still pending.
97127 SQLITE_PRIVATE void sqlite3VtabBeginParse(
97128 Parse *pParse, /* Parsing context */
97129 Token *pName1, /* Name of new table, or database name */
97130 Token *pName2, /* Name of new table or NULL */
97131 Token *pModuleName /* Name of the module for the virtual table */
97133 int iDb; /* The database the table is being created in */
97134 Table *pTable; /* The new virtual table */
97135 sqlite3 *db; /* Database connection */
97137 sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
97138 pTable = pParse->pNewTable;
97139 if( pTable==0 ) return;
97140 assert( 0==pTable->pIndex );
97142 db = pParse->db;
97143 iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
97144 assert( iDb>=0 );
97146 pTable->tabFlags |= TF_Virtual;
97147 pTable->nModuleArg = 0;
97148 addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
97149 addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
97150 addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
97151 pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
97153 #ifndef SQLITE_OMIT_AUTHORIZATION
97154 /* Creating a virtual table invokes the authorization callback twice.
97155 ** The first invocation, to obtain permission to INSERT a row into the
97156 ** sqlite_master table, has already been made by sqlite3StartTable().
97157 ** The second call, to obtain permission to create the table, is made now.
97159 if( pTable->azModuleArg ){
97160 sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
97161 pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
97163 #endif
97167 ** This routine takes the module argument that has been accumulating
97168 ** in pParse->zArg[] and appends it to the list of arguments on the
97169 ** virtual table currently under construction in pParse->pTable.
97171 static void addArgumentToVtab(Parse *pParse){
97172 if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
97173 const char *z = (const char*)pParse->sArg.z;
97174 int n = pParse->sArg.n;
97175 sqlite3 *db = pParse->db;
97176 addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
97181 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
97182 ** has been completely parsed.
97184 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
97185 Table *pTab = pParse->pNewTable; /* The table being constructed */
97186 sqlite3 *db = pParse->db; /* The database connection */
97188 if( pTab==0 ) return;
97189 addArgumentToVtab(pParse);
97190 pParse->sArg.z = 0;
97191 if( pTab->nModuleArg<1 ) return;
97193 /* If the CREATE VIRTUAL TABLE statement is being entered for the
97194 ** first time (in other words if the virtual table is actually being
97195 ** created now instead of just being read out of sqlite_master) then
97196 ** do additional initialization work and store the statement text
97197 ** in the sqlite_master table.
97199 if( !db->init.busy ){
97200 char *zStmt;
97201 char *zWhere;
97202 int iDb;
97203 Vdbe *v;
97205 /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
97206 if( pEnd ){
97207 pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
97209 zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
97211 /* A slot for the record has already been allocated in the
97212 ** SQLITE_MASTER table. We just need to update that slot with all
97213 ** the information we've collected.
97215 ** The VM register number pParse->regRowid holds the rowid of an
97216 ** entry in the sqlite_master table tht was created for this vtab
97217 ** by sqlite3StartTable().
97219 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97220 sqlite3NestedParse(pParse,
97221 "UPDATE %Q.%s "
97222 "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
97223 "WHERE rowid=#%d",
97224 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
97225 pTab->zName,
97226 pTab->zName,
97227 zStmt,
97228 pParse->regRowid
97230 sqlite3DbFree(db, zStmt);
97231 v = sqlite3GetVdbe(pParse);
97232 sqlite3ChangeCookie(pParse, iDb);
97234 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
97235 zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
97236 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
97237 sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
97238 pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
97241 /* If we are rereading the sqlite_master table create the in-memory
97242 ** record of the table. The xConnect() method is not called until
97243 ** the first time the virtual table is used in an SQL statement. This
97244 ** allows a schema that contains virtual tables to be loaded before
97245 ** the required virtual table implementations are registered. */
97246 else {
97247 Table *pOld;
97248 Schema *pSchema = pTab->pSchema;
97249 const char *zName = pTab->zName;
97250 int nName = sqlite3Strlen30(zName);
97251 assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
97252 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
97253 if( pOld ){
97254 db->mallocFailed = 1;
97255 assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
97256 return;
97258 pParse->pNewTable = 0;
97263 ** The parser calls this routine when it sees the first token
97264 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
97266 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
97267 addArgumentToVtab(pParse);
97268 pParse->sArg.z = 0;
97269 pParse->sArg.n = 0;
97273 ** The parser calls this routine for each token after the first token
97274 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
97276 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
97277 Token *pArg = &pParse->sArg;
97278 if( pArg->z==0 ){
97279 pArg->z = p->z;
97280 pArg->n = p->n;
97281 }else{
97282 assert(pArg->z < p->z);
97283 pArg->n = (int)(&p->z[p->n] - pArg->z);
97288 ** Invoke a virtual table constructor (either xCreate or xConnect). The
97289 ** pointer to the function to invoke is passed as the fourth parameter
97290 ** to this procedure.
97292 static int vtabCallConstructor(
97293 sqlite3 *db,
97294 Table *pTab,
97295 Module *pMod,
97296 int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
97297 char **pzErr
97299 VTable *pVTable;
97300 int rc;
97301 const char *const*azArg = (const char *const*)pTab->azModuleArg;
97302 int nArg = pTab->nModuleArg;
97303 char *zErr = 0;
97304 char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
97306 if( !zModuleName ){
97307 return SQLITE_NOMEM;
97310 pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
97311 if( !pVTable ){
97312 sqlite3DbFree(db, zModuleName);
97313 return SQLITE_NOMEM;
97315 pVTable->db = db;
97316 pVTable->pMod = pMod;
97318 assert( !db->pVTab );
97319 assert( xConstruct );
97320 db->pVTab = pTab;
97322 /* Invoke the virtual table constructor */
97323 rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
97324 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
97326 if( SQLITE_OK!=rc ){
97327 if( zErr==0 ){
97328 *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
97329 }else {
97330 *pzErr = sqlite3MPrintf(db, "%s", zErr);
97331 sqlite3_free(zErr);
97333 sqlite3DbFree(db, pVTable);
97334 }else if( ALWAYS(pVTable->pVtab) ){
97335 /* Justification of ALWAYS(): A correct vtab constructor must allocate
97336 ** the sqlite3_vtab object if successful. */
97337 pVTable->pVtab->pModule = pMod->pModule;
97338 pVTable->nRef = 1;
97339 if( db->pVTab ){
97340 const char *zFormat = "vtable constructor did not declare schema: %s";
97341 *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
97342 sqlite3VtabUnlock(pVTable);
97343 rc = SQLITE_ERROR;
97344 }else{
97345 int iCol;
97346 /* If everything went according to plan, link the new VTable structure
97347 ** into the linked list headed by pTab->pVTable. Then loop through the
97348 ** columns of the table to see if any of them contain the token "hidden".
97349 ** If so, set the Column.isHidden flag and remove the token from
97350 ** the type string. */
97351 pVTable->pNext = pTab->pVTable;
97352 pTab->pVTable = pVTable;
97354 for(iCol=0; iCol<pTab->nCol; iCol++){
97355 char *zType = pTab->aCol[iCol].zType;
97356 int nType;
97357 int i = 0;
97358 if( !zType ) continue;
97359 nType = sqlite3Strlen30(zType);
97360 if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
97361 for(i=0; i<nType; i++){
97362 if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
97363 && (zType[i+7]=='\0' || zType[i+7]==' ')
97365 i++;
97366 break;
97370 if( i<nType ){
97371 int j;
97372 int nDel = 6 + (zType[i+6] ? 1 : 0);
97373 for(j=i; (j+nDel)<=nType; j++){
97374 zType[j] = zType[j+nDel];
97376 if( zType[i]=='\0' && i>0 ){
97377 assert(zType[i-1]==' ');
97378 zType[i-1] = '\0';
97380 pTab->aCol[iCol].isHidden = 1;
97386 sqlite3DbFree(db, zModuleName);
97387 db->pVTab = 0;
97388 return rc;
97392 ** This function is invoked by the parser to call the xConnect() method
97393 ** of the virtual table pTab. If an error occurs, an error code is returned
97394 ** and an error left in pParse.
97396 ** This call is a no-op if table pTab is not a virtual table.
97398 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
97399 sqlite3 *db = pParse->db;
97400 const char *zMod;
97401 Module *pMod;
97402 int rc;
97404 assert( pTab );
97405 if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
97406 return SQLITE_OK;
97409 /* Locate the required virtual table module */
97410 zMod = pTab->azModuleArg[0];
97411 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97413 if( !pMod ){
97414 const char *zModule = pTab->azModuleArg[0];
97415 sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
97416 rc = SQLITE_ERROR;
97417 }else{
97418 char *zErr = 0;
97419 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
97420 if( rc!=SQLITE_OK ){
97421 sqlite3ErrorMsg(pParse, "%s", zErr);
97423 sqlite3DbFree(db, zErr);
97426 return rc;
97430 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
97432 static int addToVTrans(sqlite3 *db, VTable *pVTab){
97433 const int ARRAY_INCR = 5;
97435 /* Grow the sqlite3.aVTrans array if required */
97436 if( (db->nVTrans%ARRAY_INCR)==0 ){
97437 VTable **aVTrans;
97438 int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
97439 aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
97440 if( !aVTrans ){
97441 return SQLITE_NOMEM;
97443 memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
97444 db->aVTrans = aVTrans;
97447 /* Add pVtab to the end of sqlite3.aVTrans */
97448 db->aVTrans[db->nVTrans++] = pVTab;
97449 sqlite3VtabLock(pVTab);
97450 return SQLITE_OK;
97454 ** This function is invoked by the vdbe to call the xCreate method
97455 ** of the virtual table named zTab in database iDb.
97457 ** If an error occurs, *pzErr is set to point an an English language
97458 ** description of the error and an SQLITE_XXX error code is returned.
97459 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
97461 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
97462 int rc = SQLITE_OK;
97463 Table *pTab;
97464 Module *pMod;
97465 const char *zMod;
97467 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97468 assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
97470 /* Locate the required virtual table module */
97471 zMod = pTab->azModuleArg[0];
97472 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97474 /* If the module has been registered and includes a Create method,
97475 ** invoke it now. If the module has not been registered, return an
97476 ** error. Otherwise, do nothing.
97478 if( !pMod ){
97479 *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
97480 rc = SQLITE_ERROR;
97481 }else{
97482 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
97485 /* Justification of ALWAYS(): The xConstructor method is required to
97486 ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
97487 if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
97488 rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
97491 return rc;
97495 ** This function is used to set the schema of a virtual table. It is only
97496 ** valid to call this function from within the xCreate() or xConnect() of a
97497 ** virtual table module.
97499 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
97500 Parse *pParse;
97502 int rc = SQLITE_OK;
97503 Table *pTab;
97504 char *zErr = 0;
97506 sqlite3_mutex_enter(db->mutex);
97507 pTab = db->pVTab;
97508 if( !pTab ){
97509 sqlite3Error(db, SQLITE_MISUSE, 0);
97510 sqlite3_mutex_leave(db->mutex);
97511 return SQLITE_MISUSE_BKPT;
97513 assert( (pTab->tabFlags & TF_Virtual)!=0 );
97515 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
97516 if( pParse==0 ){
97517 rc = SQLITE_NOMEM;
97518 }else{
97519 pParse->declareVtab = 1;
97520 pParse->db = db;
97521 pParse->nQueryLoop = 1;
97523 if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
97524 && pParse->pNewTable
97525 && !db->mallocFailed
97526 && !pParse->pNewTable->pSelect
97527 && (pParse->pNewTable->tabFlags & TF_Virtual)==0
97529 if( !pTab->aCol ){
97530 pTab->aCol = pParse->pNewTable->aCol;
97531 pTab->nCol = pParse->pNewTable->nCol;
97532 pParse->pNewTable->nCol = 0;
97533 pParse->pNewTable->aCol = 0;
97535 db->pVTab = 0;
97536 }else{
97537 sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
97538 sqlite3DbFree(db, zErr);
97539 rc = SQLITE_ERROR;
97541 pParse->declareVtab = 0;
97543 if( pParse->pVdbe ){
97544 sqlite3VdbeFinalize(pParse->pVdbe);
97546 sqlite3DeleteTable(db, pParse->pNewTable);
97547 sqlite3StackFree(db, pParse);
97550 assert( (rc&0xff)==rc );
97551 rc = sqlite3ApiExit(db, rc);
97552 sqlite3_mutex_leave(db->mutex);
97553 return rc;
97557 ** This function is invoked by the vdbe to call the xDestroy method
97558 ** of the virtual table named zTab in database iDb. This occurs
97559 ** when a DROP TABLE is mentioned.
97561 ** This call is a no-op if zTab is not a virtual table.
97563 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
97564 int rc = SQLITE_OK;
97565 Table *pTab;
97567 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97568 if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
97569 VTable *p = vtabDisconnectAll(db, pTab);
97571 assert( rc==SQLITE_OK );
97572 rc = p->pMod->pModule->xDestroy(p->pVtab);
97574 /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
97575 if( rc==SQLITE_OK ){
97576 assert( pTab->pVTable==p && p->pNext==0 );
97577 p->pVtab = 0;
97578 pTab->pVTable = 0;
97579 sqlite3VtabUnlock(p);
97583 return rc;
97587 ** This function invokes either the xRollback or xCommit method
97588 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
97589 ** called is identified by the second argument, "offset", which is
97590 ** the offset of the method to call in the sqlite3_module structure.
97592 ** The array is cleared after invoking the callbacks.
97594 static void callFinaliser(sqlite3 *db, int offset){
97595 int i;
97596 if( db->aVTrans ){
97597 for(i=0; i<db->nVTrans; i++){
97598 VTable *pVTab = db->aVTrans[i];
97599 sqlite3_vtab *p = pVTab->pVtab;
97600 if( p ){
97601 int (*x)(sqlite3_vtab *);
97602 x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
97603 if( x ) x(p);
97605 sqlite3VtabUnlock(pVTab);
97607 sqlite3DbFree(db, db->aVTrans);
97608 db->nVTrans = 0;
97609 db->aVTrans = 0;
97614 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
97615 ** array. Return the error code for the first error that occurs, or
97616 ** SQLITE_OK if all xSync operations are successful.
97618 ** Set *pzErrmsg to point to a buffer that should be released using
97619 ** sqlite3DbFree() containing an error message, if one is available.
97621 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
97622 int i;
97623 int rc = SQLITE_OK;
97624 VTable **aVTrans = db->aVTrans;
97626 db->aVTrans = 0;
97627 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
97628 int (*x)(sqlite3_vtab *);
97629 sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
97630 if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
97631 rc = x(pVtab);
97632 sqlite3DbFree(db, *pzErrmsg);
97633 *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
97634 sqlite3_free(pVtab->zErrMsg);
97637 db->aVTrans = aVTrans;
97638 return rc;
97642 ** Invoke the xRollback method of all virtual tables in the
97643 ** sqlite3.aVTrans array. Then clear the array itself.
97645 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
97646 callFinaliser(db, offsetof(sqlite3_module,xRollback));
97647 return SQLITE_OK;
97651 ** Invoke the xCommit method of all virtual tables in the
97652 ** sqlite3.aVTrans array. Then clear the array itself.
97654 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
97655 callFinaliser(db, offsetof(sqlite3_module,xCommit));
97656 return SQLITE_OK;
97660 ** If the virtual table pVtab supports the transaction interface
97661 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
97662 ** not currently open, invoke the xBegin method now.
97664 ** If the xBegin call is successful, place the sqlite3_vtab pointer
97665 ** in the sqlite3.aVTrans array.
97667 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
97668 int rc = SQLITE_OK;
97669 const sqlite3_module *pModule;
97671 /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
97672 ** than zero, then this function is being called from within a
97673 ** virtual module xSync() callback. It is illegal to write to
97674 ** virtual module tables in this case, so return SQLITE_LOCKED.
97676 if( sqlite3VtabInSync(db) ){
97677 return SQLITE_LOCKED;
97679 if( !pVTab ){
97680 return SQLITE_OK;
97682 pModule = pVTab->pVtab->pModule;
97684 if( pModule->xBegin ){
97685 int i;
97688 /* If pVtab is already in the aVTrans array, return early */
97689 for(i=0; i<db->nVTrans; i++){
97690 if( db->aVTrans[i]==pVTab ){
97691 return SQLITE_OK;
97695 /* Invoke the xBegin method */
97696 rc = pModule->xBegin(pVTab->pVtab);
97697 if( rc==SQLITE_OK ){
97698 rc = addToVTrans(db, pVTab);
97701 return rc;
97705 ** The first parameter (pDef) is a function implementation. The
97706 ** second parameter (pExpr) is the first argument to this function.
97707 ** If pExpr is a column in a virtual table, then let the virtual
97708 ** table implementation have an opportunity to overload the function.
97710 ** This routine is used to allow virtual table implementations to
97711 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
97713 ** Return either the pDef argument (indicating no change) or a
97714 ** new FuncDef structure that is marked as ephemeral using the
97715 ** SQLITE_FUNC_EPHEM flag.
97717 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
97718 sqlite3 *db, /* Database connection for reporting malloc problems */
97719 FuncDef *pDef, /* Function to possibly overload */
97720 int nArg, /* Number of arguments to the function */
97721 Expr *pExpr /* First argument to the function */
97723 Table *pTab;
97724 sqlite3_vtab *pVtab;
97725 sqlite3_module *pMod;
97726 void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
97727 void *pArg = 0;
97728 FuncDef *pNew;
97729 int rc = 0;
97730 char *zLowerName;
97731 unsigned char *z;
97734 /* Check to see the left operand is a column in a virtual table */
97735 if( NEVER(pExpr==0) ) return pDef;
97736 if( pExpr->op!=TK_COLUMN ) return pDef;
97737 pTab = pExpr->pTab;
97738 if( NEVER(pTab==0) ) return pDef;
97739 if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
97740 pVtab = sqlite3GetVTable(db, pTab)->pVtab;
97741 assert( pVtab!=0 );
97742 assert( pVtab->pModule!=0 );
97743 pMod = (sqlite3_module *)pVtab->pModule;
97744 if( pMod->xFindFunction==0 ) return pDef;
97746 /* Call the xFindFunction method on the virtual table implementation
97747 ** to see if the implementation wants to overload this function
97749 zLowerName = sqlite3DbStrDup(db, pDef->zName);
97750 if( zLowerName ){
97751 for(z=(unsigned char*)zLowerName; *z; z++){
97752 *z = sqlite3UpperToLower[*z];
97754 rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
97755 sqlite3DbFree(db, zLowerName);
97757 if( rc==0 ){
97758 return pDef;
97761 /* Create a new ephemeral function definition for the overloaded
97762 ** function */
97763 pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
97764 + sqlite3Strlen30(pDef->zName) + 1);
97765 if( pNew==0 ){
97766 return pDef;
97768 *pNew = *pDef;
97769 pNew->zName = (char *)&pNew[1];
97770 memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
97771 pNew->xFunc = xFunc;
97772 pNew->pUserData = pArg;
97773 pNew->flags |= SQLITE_FUNC_EPHEM;
97774 return pNew;
97778 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
97779 ** array so that an OP_VBegin will get generated for it. Add pTab to the
97780 ** array if it is missing. If pTab is already in the array, this routine
97781 ** is a no-op.
97783 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
97784 Parse *pToplevel = sqlite3ParseToplevel(pParse);
97785 int i, n;
97786 Table **apVtabLock;
97788 assert( IsVirtual(pTab) );
97789 for(i=0; i<pToplevel->nVtabLock; i++){
97790 if( pTab==pToplevel->apVtabLock[i] ) return;
97792 n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
97793 apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
97794 if( apVtabLock ){
97795 pToplevel->apVtabLock = apVtabLock;
97796 pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
97797 }else{
97798 pToplevel->db->mallocFailed = 1;
97802 #endif /* SQLITE_OMIT_VIRTUALTABLE */
97804 /************** End of vtab.c ************************************************/
97805 /************** Begin file where.c *******************************************/
97807 ** 2001 September 15
97809 ** The author disclaims copyright to this source code. In place of
97810 ** a legal notice, here is a blessing:
97812 ** May you do good and not evil.
97813 ** May you find forgiveness for yourself and forgive others.
97814 ** May you share freely, never taking more than you give.
97816 *************************************************************************
97817 ** This module contains C code that generates VDBE code used to process
97818 ** the WHERE clause of SQL statements. This module is responsible for
97819 ** generating the code that loops through a table looking for applicable
97820 ** rows. Indices are selected and used to speed the search when doing
97821 ** so is applicable. Because this module is responsible for selecting
97822 ** indices, you might also think of this module as the "query optimizer".
97827 ** Trace output macros
97829 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
97830 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
97831 #endif
97832 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
97833 # define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
97834 #else
97835 # define WHERETRACE(X)
97836 #endif
97838 /* Forward reference
97840 typedef struct WhereClause WhereClause;
97841 typedef struct WhereMaskSet WhereMaskSet;
97842 typedef struct WhereOrInfo WhereOrInfo;
97843 typedef struct WhereAndInfo WhereAndInfo;
97844 typedef struct WhereCost WhereCost;
97847 ** The query generator uses an array of instances of this structure to
97848 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
97849 ** clause subexpression is separated from the others by AND operators,
97850 ** usually, or sometimes subexpressions separated by OR.
97852 ** All WhereTerms are collected into a single WhereClause structure.
97853 ** The following identity holds:
97855 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
97857 ** When a term is of the form:
97859 ** X <op> <expr>
97861 ** where X is a column name and <op> is one of certain operators,
97862 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
97863 ** cursor number and column number for X. WhereTerm.eOperator records
97864 ** the <op> using a bitmask encoding defined by WO_xxx below. The
97865 ** use of a bitmask encoding for the operator allows us to search
97866 ** quickly for terms that match any of several different operators.
97868 ** A WhereTerm might also be two or more subterms connected by OR:
97870 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
97872 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
97873 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
97874 ** is collected about the
97876 ** If a term in the WHERE clause does not match either of the two previous
97877 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
97878 ** to the original subexpression content and wtFlags is set up appropriately
97879 ** but no other fields in the WhereTerm object are meaningful.
97881 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
97882 ** but they do so indirectly. A single WhereMaskSet structure translates
97883 ** cursor number into bits and the translated bit is stored in the prereq
97884 ** fields. The translation is used in order to maximize the number of
97885 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
97886 ** spread out over the non-negative integers. For example, the cursor
97887 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
97888 ** translates these sparse cursor numbers into consecutive integers
97889 ** beginning with 0 in order to make the best possible use of the available
97890 ** bits in the Bitmask. So, in the example above, the cursor numbers
97891 ** would be mapped into integers 0 through 7.
97893 ** The number of terms in a join is limited by the number of bits
97894 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
97895 ** is only able to process joins with 64 or fewer tables.
97897 typedef struct WhereTerm WhereTerm;
97898 struct WhereTerm {
97899 Expr *pExpr; /* Pointer to the subexpression that is this term */
97900 int iParent; /* Disable pWC->a[iParent] when this term disabled */
97901 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
97902 union {
97903 int leftColumn; /* Column number of X in "X <op> <expr>" */
97904 WhereOrInfo *pOrInfo; /* Extra information if eOperator==WO_OR */
97905 WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
97906 } u;
97907 u16 eOperator; /* A WO_xx value describing <op> */
97908 u8 wtFlags; /* TERM_xxx bit flags. See below */
97909 u8 nChild; /* Number of children that must disable us */
97910 WhereClause *pWC; /* The clause this term is part of */
97911 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
97912 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
97916 ** Allowed values of WhereTerm.wtFlags
97918 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
97919 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
97920 #define TERM_CODED 0x04 /* This term is already coded */
97921 #define TERM_COPIED 0x08 /* Has a child */
97922 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
97923 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
97924 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
97925 #ifdef SQLITE_ENABLE_STAT2
97926 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
97927 #else
97928 # define TERM_VNULL 0x00 /* Disabled if not using stat2 */
97929 #endif
97932 ** An instance of the following structure holds all information about a
97933 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
97935 struct WhereClause {
97936 Parse *pParse; /* The parser context */
97937 WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
97938 Bitmask vmask; /* Bitmask identifying virtual table cursors */
97939 u8 op; /* Split operator. TK_AND or TK_OR */
97940 int nTerm; /* Number of terms */
97941 int nSlot; /* Number of entries in a[] */
97942 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
97943 #if defined(SQLITE_SMALL_STACK)
97944 WhereTerm aStatic[1]; /* Initial static space for a[] */
97945 #else
97946 WhereTerm aStatic[8]; /* Initial static space for a[] */
97947 #endif
97951 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
97952 ** a dynamically allocated instance of the following structure.
97954 struct WhereOrInfo {
97955 WhereClause wc; /* Decomposition into subterms */
97956 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
97960 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
97961 ** a dynamically allocated instance of the following structure.
97963 struct WhereAndInfo {
97964 WhereClause wc; /* The subexpression broken out */
97968 ** An instance of the following structure keeps track of a mapping
97969 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
97971 ** The VDBE cursor numbers are small integers contained in
97972 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
97973 ** clause, the cursor numbers might not begin with 0 and they might
97974 ** contain gaps in the numbering sequence. But we want to make maximum
97975 ** use of the bits in our bitmasks. This structure provides a mapping
97976 ** from the sparse cursor numbers into consecutive integers beginning
97977 ** with 0.
97979 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
97980 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
97982 ** For example, if the WHERE clause expression used these VDBE
97983 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
97984 ** would map those cursor numbers into bits 0 through 5.
97986 ** Note that the mapping is not necessarily ordered. In the example
97987 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
97988 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
97989 ** does not really matter. What is important is that sparse cursor
97990 ** numbers all get mapped into bit numbers that begin with 0 and contain
97991 ** no gaps.
97993 struct WhereMaskSet {
97994 int n; /* Number of assigned cursor values */
97995 int ix[BMS]; /* Cursor assigned to each bit */
97999 ** A WhereCost object records a lookup strategy and the estimated
98000 ** cost of pursuing that strategy.
98002 struct WhereCost {
98003 WherePlan plan; /* The lookup strategy */
98004 double rCost; /* Overall cost of pursuing this search strategy */
98005 Bitmask used; /* Bitmask of cursors used by this plan */
98009 ** Bitmasks for the operators that indices are able to exploit. An
98010 ** OR-ed combination of these values can be used when searching for
98011 ** terms in the where clause.
98013 #define WO_IN 0x001
98014 #define WO_EQ 0x002
98015 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
98016 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
98017 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
98018 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
98019 #define WO_MATCH 0x040
98020 #define WO_ISNULL 0x080
98021 #define WO_OR 0x100 /* Two or more OR-connected terms */
98022 #define WO_AND 0x200 /* Two or more AND-connected terms */
98023 #define WO_NOOP 0x800 /* This term does not restrict search space */
98025 #define WO_ALL 0xfff /* Mask of all possible WO_* values */
98026 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
98029 ** Value for wsFlags returned by bestIndex() and stored in
98030 ** WhereLevel.wsFlags. These flags determine which search
98031 ** strategies are appropriate.
98033 ** The least significant 12 bits is reserved as a mask for WO_ values above.
98034 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
98035 ** But if the table is the right table of a left join, WhereLevel.wsFlags
98036 ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
98037 ** the "op" parameter to findTerm when we are resolving equality constraints.
98038 ** ISNULL constraints will then not be used on the right table of a left
98039 ** join. Tickets #2177 and #2189.
98041 #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
98042 #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
98043 #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
98044 #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
98045 #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
98046 #define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
98047 #define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
98048 #define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
98049 #define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */
98050 #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
98051 #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
98052 #define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
98053 #define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
98054 #define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
98055 #define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
98056 #define WHERE_UNIQUE 0x04000000 /* Selects no more than one row */
98057 #define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
98058 #define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
98059 #define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
98062 ** Initialize a preallocated WhereClause structure.
98064 static void whereClauseInit(
98065 WhereClause *pWC, /* The WhereClause to be initialized */
98066 Parse *pParse, /* The parsing context */
98067 WhereMaskSet *pMaskSet /* Mapping from table cursor numbers to bitmasks */
98069 pWC->pParse = pParse;
98070 pWC->pMaskSet = pMaskSet;
98071 pWC->nTerm = 0;
98072 pWC->nSlot = ArraySize(pWC->aStatic);
98073 pWC->a = pWC->aStatic;
98074 pWC->vmask = 0;
98077 /* Forward reference */
98078 static void whereClauseClear(WhereClause*);
98081 ** Deallocate all memory associated with a WhereOrInfo object.
98083 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
98084 whereClauseClear(&p->wc);
98085 sqlite3DbFree(db, p);
98089 ** Deallocate all memory associated with a WhereAndInfo object.
98091 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
98092 whereClauseClear(&p->wc);
98093 sqlite3DbFree(db, p);
98097 ** Deallocate a WhereClause structure. The WhereClause structure
98098 ** itself is not freed. This routine is the inverse of whereClauseInit().
98100 static void whereClauseClear(WhereClause *pWC){
98101 int i;
98102 WhereTerm *a;
98103 sqlite3 *db = pWC->pParse->db;
98104 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
98105 if( a->wtFlags & TERM_DYNAMIC ){
98106 sqlite3ExprDelete(db, a->pExpr);
98108 if( a->wtFlags & TERM_ORINFO ){
98109 whereOrInfoDelete(db, a->u.pOrInfo);
98110 }else if( a->wtFlags & TERM_ANDINFO ){
98111 whereAndInfoDelete(db, a->u.pAndInfo);
98114 if( pWC->a!=pWC->aStatic ){
98115 sqlite3DbFree(db, pWC->a);
98120 ** Add a single new WhereTerm entry to the WhereClause object pWC.
98121 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
98122 ** The index in pWC->a[] of the new WhereTerm is returned on success.
98123 ** 0 is returned if the new WhereTerm could not be added due to a memory
98124 ** allocation error. The memory allocation failure will be recorded in
98125 ** the db->mallocFailed flag so that higher-level functions can detect it.
98127 ** This routine will increase the size of the pWC->a[] array as necessary.
98129 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
98130 ** for freeing the expression p is assumed by the WhereClause object pWC.
98131 ** This is true even if this routine fails to allocate a new WhereTerm.
98133 ** WARNING: This routine might reallocate the space used to store
98134 ** WhereTerms. All pointers to WhereTerms should be invalidated after
98135 ** calling this routine. Such pointers may be reinitialized by referencing
98136 ** the pWC->a[] array.
98138 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
98139 WhereTerm *pTerm;
98140 int idx;
98141 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
98142 if( pWC->nTerm>=pWC->nSlot ){
98143 WhereTerm *pOld = pWC->a;
98144 sqlite3 *db = pWC->pParse->db;
98145 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
98146 if( pWC->a==0 ){
98147 if( wtFlags & TERM_DYNAMIC ){
98148 sqlite3ExprDelete(db, p);
98150 pWC->a = pOld;
98151 return 0;
98153 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
98154 if( pOld!=pWC->aStatic ){
98155 sqlite3DbFree(db, pOld);
98157 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
98159 pTerm = &pWC->a[idx = pWC->nTerm++];
98160 pTerm->pExpr = p;
98161 pTerm->wtFlags = wtFlags;
98162 pTerm->pWC = pWC;
98163 pTerm->iParent = -1;
98164 return idx;
98168 ** This routine identifies subexpressions in the WHERE clause where
98169 ** each subexpression is separated by the AND operator or some other
98170 ** operator specified in the op parameter. The WhereClause structure
98171 ** is filled with pointers to subexpressions. For example:
98173 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
98174 ** \________/ \_______________/ \________________/
98175 ** slot[0] slot[1] slot[2]
98177 ** The original WHERE clause in pExpr is unaltered. All this routine
98178 ** does is make slot[] entries point to substructure within pExpr.
98180 ** In the previous sentence and in the diagram, "slot[]" refers to
98181 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
98182 ** all terms of the WHERE clause.
98184 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
98185 pWC->op = (u8)op;
98186 if( pExpr==0 ) return;
98187 if( pExpr->op!=op ){
98188 whereClauseInsert(pWC, pExpr, 0);
98189 }else{
98190 whereSplit(pWC, pExpr->pLeft, op);
98191 whereSplit(pWC, pExpr->pRight, op);
98196 ** Initialize an expression mask set (a WhereMaskSet object)
98198 #define initMaskSet(P) memset(P, 0, sizeof(*P))
98201 ** Return the bitmask for the given cursor number. Return 0 if
98202 ** iCursor is not in the set.
98204 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
98205 int i;
98206 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
98207 for(i=0; i<pMaskSet->n; i++){
98208 if( pMaskSet->ix[i]==iCursor ){
98209 return ((Bitmask)1)<<i;
98212 return 0;
98216 ** Create a new mask for cursor iCursor.
98218 ** There is one cursor per table in the FROM clause. The number of
98219 ** tables in the FROM clause is limited by a test early in the
98220 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
98221 ** array will never overflow.
98223 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
98224 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
98225 pMaskSet->ix[pMaskSet->n++] = iCursor;
98229 ** This routine walks (recursively) an expression tree and generates
98230 ** a bitmask indicating which tables are used in that expression
98231 ** tree.
98233 ** In order for this routine to work, the calling function must have
98234 ** previously invoked sqlite3ResolveExprNames() on the expression. See
98235 ** the header comment on that routine for additional information.
98236 ** The sqlite3ResolveExprNames() routines looks for column names and
98237 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
98238 ** the VDBE cursor number of the table. This routine just has to
98239 ** translate the cursor numbers into bitmask values and OR all
98240 ** the bitmasks together.
98242 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
98243 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
98244 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
98245 Bitmask mask = 0;
98246 if( p==0 ) return 0;
98247 if( p->op==TK_COLUMN ){
98248 mask = getMask(pMaskSet, p->iTable);
98249 return mask;
98251 mask = exprTableUsage(pMaskSet, p->pRight);
98252 mask |= exprTableUsage(pMaskSet, p->pLeft);
98253 if( ExprHasProperty(p, EP_xIsSelect) ){
98254 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
98255 }else{
98256 mask |= exprListTableUsage(pMaskSet, p->x.pList);
98258 return mask;
98260 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
98261 int i;
98262 Bitmask mask = 0;
98263 if( pList ){
98264 for(i=0; i<pList->nExpr; i++){
98265 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
98268 return mask;
98270 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
98271 Bitmask mask = 0;
98272 while( pS ){
98273 mask |= exprListTableUsage(pMaskSet, pS->pEList);
98274 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
98275 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
98276 mask |= exprTableUsage(pMaskSet, pS->pWhere);
98277 mask |= exprTableUsage(pMaskSet, pS->pHaving);
98278 pS = pS->pPrior;
98280 return mask;
98284 ** Return TRUE if the given operator is one of the operators that is
98285 ** allowed for an indexable WHERE clause term. The allowed operators are
98286 ** "=", "<", ">", "<=", ">=", and "IN".
98288 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
98289 ** of one of the following forms: column = expression column > expression
98290 ** column >= expression column < expression column <= expression
98291 ** expression = column expression > column expression >= column
98292 ** expression < column expression <= column column IN
98293 ** (expression-list) column IN (subquery) column IS NULL
98295 static int allowedOp(int op){
98296 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
98297 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
98298 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
98299 assert( TK_GE==TK_EQ+4 );
98300 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
98304 ** Swap two objects of type TYPE.
98306 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
98309 ** Commute a comparison operator. Expressions of the form "X op Y"
98310 ** are converted into "Y op X".
98312 ** If a collation sequence is associated with either the left or right
98313 ** side of the comparison, it remains associated with the same side after
98314 ** the commutation. So "Y collate NOCASE op X" becomes
98315 ** "X collate NOCASE op Y". This is because any collation sequence on
98316 ** the left hand side of a comparison overrides any collation sequence
98317 ** attached to the right. For the same reason the EP_ExpCollate flag
98318 ** is not commuted.
98320 static void exprCommute(Parse *pParse, Expr *pExpr){
98321 u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
98322 u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
98323 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
98324 pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
98325 pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
98326 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
98327 pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
98328 pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
98329 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
98330 if( pExpr->op>=TK_GT ){
98331 assert( TK_LT==TK_GT+2 );
98332 assert( TK_GE==TK_LE+2 );
98333 assert( TK_GT>TK_EQ );
98334 assert( TK_GT<TK_LE );
98335 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
98336 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
98341 ** Translate from TK_xx operator to WO_xx bitmask.
98343 static u16 operatorMask(int op){
98344 u16 c;
98345 assert( allowedOp(op) );
98346 if( op==TK_IN ){
98347 c = WO_IN;
98348 }else if( op==TK_ISNULL ){
98349 c = WO_ISNULL;
98350 }else{
98351 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
98352 c = (u16)(WO_EQ<<(op-TK_EQ));
98354 assert( op!=TK_ISNULL || c==WO_ISNULL );
98355 assert( op!=TK_IN || c==WO_IN );
98356 assert( op!=TK_EQ || c==WO_EQ );
98357 assert( op!=TK_LT || c==WO_LT );
98358 assert( op!=TK_LE || c==WO_LE );
98359 assert( op!=TK_GT || c==WO_GT );
98360 assert( op!=TK_GE || c==WO_GE );
98361 return c;
98365 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
98366 ** where X is a reference to the iColumn of table iCur and <op> is one of
98367 ** the WO_xx operator codes specified by the op parameter.
98368 ** Return a pointer to the term. Return 0 if not found.
98370 static WhereTerm *findTerm(
98371 WhereClause *pWC, /* The WHERE clause to be searched */
98372 int iCur, /* Cursor number of LHS */
98373 int iColumn, /* Column number of LHS */
98374 Bitmask notReady, /* RHS must not overlap with this mask */
98375 u32 op, /* Mask of WO_xx values describing operator */
98376 Index *pIdx /* Must be compatible with this index, if not NULL */
98378 WhereTerm *pTerm;
98379 int k;
98380 assert( iCur>=0 );
98381 op &= WO_ALL;
98382 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
98383 if( pTerm->leftCursor==iCur
98384 && (pTerm->prereqRight & notReady)==0
98385 && pTerm->u.leftColumn==iColumn
98386 && (pTerm->eOperator & op)!=0
98388 if( pIdx && pTerm->eOperator!=WO_ISNULL ){
98389 Expr *pX = pTerm->pExpr;
98390 CollSeq *pColl;
98391 char idxaff;
98392 int j;
98393 Parse *pParse = pWC->pParse;
98395 idxaff = pIdx->pTable->aCol[iColumn].affinity;
98396 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
98398 /* Figure out the collation sequence required from an index for
98399 ** it to be useful for optimising expression pX. Store this
98400 ** value in variable pColl.
98402 assert(pX->pLeft);
98403 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
98404 assert(pColl || pParse->nErr);
98406 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
98407 if( NEVER(j>=pIdx->nColumn) ) return 0;
98409 if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
98411 return pTerm;
98414 return 0;
98417 /* Forward reference */
98418 static void exprAnalyze(SrcList*, WhereClause*, int);
98421 ** Call exprAnalyze on all terms in a WHERE clause.
98425 static void exprAnalyzeAll(
98426 SrcList *pTabList, /* the FROM clause */
98427 WhereClause *pWC /* the WHERE clause to be analyzed */
98429 int i;
98430 for(i=pWC->nTerm-1; i>=0; i--){
98431 exprAnalyze(pTabList, pWC, i);
98435 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
98437 ** Check to see if the given expression is a LIKE or GLOB operator that
98438 ** can be optimized using inequality constraints. Return TRUE if it is
98439 ** so and false if not.
98441 ** In order for the operator to be optimizible, the RHS must be a string
98442 ** literal that does not begin with a wildcard.
98444 static int isLikeOrGlob(
98445 Parse *pParse, /* Parsing and code generating context */
98446 Expr *pExpr, /* Test this expression */
98447 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
98448 int *pisComplete, /* True if the only wildcard is % in the last character */
98449 int *pnoCase /* True if uppercase is equivalent to lowercase */
98451 const char *z = 0; /* String on RHS of LIKE operator */
98452 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
98453 ExprList *pList; /* List of operands to the LIKE operator */
98454 int c; /* One character in z[] */
98455 int cnt; /* Number of non-wildcard prefix characters */
98456 char wc[3]; /* Wildcard characters */
98457 sqlite3 *db = pParse->db; /* Database connection */
98458 sqlite3_value *pVal = 0;
98459 int op; /* Opcode of pRight */
98461 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
98462 return 0;
98464 #ifdef SQLITE_EBCDIC
98465 if( *pnoCase ) return 0;
98466 #endif
98467 pList = pExpr->x.pList;
98468 pLeft = pList->a[1].pExpr;
98469 if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
98470 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
98471 ** be the name of an indexed column with TEXT affinity. */
98472 return 0;
98474 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
98476 pRight = pList->a[0].pExpr;
98477 op = pRight->op;
98478 if( op==TK_REGISTER ){
98479 op = pRight->op2;
98481 if( op==TK_VARIABLE ){
98482 Vdbe *pReprepare = pParse->pReprepare;
98483 int iCol = pRight->iColumn;
98484 pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
98485 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
98486 z = (char *)sqlite3_value_text(pVal);
98488 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
98489 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
98490 }else if( op==TK_STRING ){
98491 z = pRight->u.zToken;
98493 if( z ){
98494 cnt = 0;
98495 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
98496 cnt++;
98498 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
98499 Expr *pPrefix;
98500 *pisComplete = c==wc[0] && z[cnt+1]==0;
98501 pPrefix = sqlite3Expr(db, TK_STRING, z);
98502 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
98503 *ppPrefix = pPrefix;
98504 if( op==TK_VARIABLE ){
98505 Vdbe *v = pParse->pVdbe;
98506 sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
98507 if( *pisComplete && pRight->u.zToken[1] ){
98508 /* If the rhs of the LIKE expression is a variable, and the current
98509 ** value of the variable means there is no need to invoke the LIKE
98510 ** function, then no OP_Variable will be added to the program.
98511 ** This causes problems for the sqlite3_bind_parameter_name()
98512 ** API. To workaround them, add a dummy OP_Variable here.
98514 int r1 = sqlite3GetTempReg(pParse);
98515 sqlite3ExprCodeTarget(pParse, pRight, r1);
98516 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
98517 sqlite3ReleaseTempReg(pParse, r1);
98520 }else{
98521 z = 0;
98525 sqlite3ValueFree(pVal);
98526 return (z!=0);
98528 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
98531 #ifndef SQLITE_OMIT_VIRTUALTABLE
98533 ** Check to see if the given expression is of the form
98535 ** column MATCH expr
98537 ** If it is then return TRUE. If not, return FALSE.
98539 static int isMatchOfColumn(
98540 Expr *pExpr /* Test this expression */
98542 ExprList *pList;
98544 if( pExpr->op!=TK_FUNCTION ){
98545 return 0;
98547 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
98548 return 0;
98550 pList = pExpr->x.pList;
98551 if( pList->nExpr!=2 ){
98552 return 0;
98554 if( pList->a[1].pExpr->op != TK_COLUMN ){
98555 return 0;
98557 return 1;
98559 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98562 ** If the pBase expression originated in the ON or USING clause of
98563 ** a join, then transfer the appropriate markings over to derived.
98565 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
98566 pDerived->flags |= pBase->flags & EP_FromJoin;
98567 pDerived->iRightJoinTable = pBase->iRightJoinTable;
98570 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
98572 ** Analyze a term that consists of two or more OR-connected
98573 ** subterms. So in:
98575 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
98576 ** ^^^^^^^^^^^^^^^^^^^^
98578 ** This routine analyzes terms such as the middle term in the above example.
98579 ** A WhereOrTerm object is computed and attached to the term under
98580 ** analysis, regardless of the outcome of the analysis. Hence:
98582 ** WhereTerm.wtFlags |= TERM_ORINFO
98583 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
98585 ** The term being analyzed must have two or more of OR-connected subterms.
98586 ** A single subterm might be a set of AND-connected sub-subterms.
98587 ** Examples of terms under analysis:
98589 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
98590 ** (B) x=expr1 OR expr2=x OR x=expr3
98591 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
98592 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
98593 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
98595 ** CASE 1:
98597 ** If all subterms are of the form T.C=expr for some single column of C
98598 ** a single table T (as shown in example B above) then create a new virtual
98599 ** term that is an equivalent IN expression. In other words, if the term
98600 ** being analyzed is:
98602 ** x = expr1 OR expr2 = x OR x = expr3
98604 ** then create a new virtual term like this:
98606 ** x IN (expr1,expr2,expr3)
98608 ** CASE 2:
98610 ** If all subterms are indexable by a single table T, then set
98612 ** WhereTerm.eOperator = WO_OR
98613 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
98615 ** A subterm is "indexable" if it is of the form
98616 ** "T.C <op> <expr>" where C is any column of table T and
98617 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
98618 ** A subterm is also indexable if it is an AND of two or more
98619 ** subsubterms at least one of which is indexable. Indexable AND
98620 ** subterms have their eOperator set to WO_AND and they have
98621 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
98623 ** From another point of view, "indexable" means that the subterm could
98624 ** potentially be used with an index if an appropriate index exists.
98625 ** This analysis does not consider whether or not the index exists; that
98626 ** is something the bestIndex() routine will determine. This analysis
98627 ** only looks at whether subterms appropriate for indexing exist.
98629 ** All examples A through E above all satisfy case 2. But if a term
98630 ** also statisfies case 1 (such as B) we know that the optimizer will
98631 ** always prefer case 1, so in that case we pretend that case 2 is not
98632 ** satisfied.
98634 ** It might be the case that multiple tables are indexable. For example,
98635 ** (E) above is indexable on tables P, Q, and R.
98637 ** Terms that satisfy case 2 are candidates for lookup by using
98638 ** separate indices to find rowids for each subterm and composing
98639 ** the union of all rowids using a RowSet object. This is similar
98640 ** to "bitmap indices" in other database engines.
98642 ** OTHERWISE:
98644 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
98645 ** zero. This term is not useful for search.
98647 static void exprAnalyzeOrTerm(
98648 SrcList *pSrc, /* the FROM clause */
98649 WhereClause *pWC, /* the complete WHERE clause */
98650 int idxTerm /* Index of the OR-term to be analyzed */
98652 Parse *pParse = pWC->pParse; /* Parser context */
98653 sqlite3 *db = pParse->db; /* Database connection */
98654 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
98655 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
98656 WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
98657 int i; /* Loop counters */
98658 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
98659 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
98660 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
98661 Bitmask chngToIN; /* Tables that might satisfy case 1 */
98662 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
98665 ** Break the OR clause into its separate subterms. The subterms are
98666 ** stored in a WhereClause structure containing within the WhereOrInfo
98667 ** object that is attached to the original OR clause term.
98669 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
98670 assert( pExpr->op==TK_OR );
98671 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
98672 if( pOrInfo==0 ) return;
98673 pTerm->wtFlags |= TERM_ORINFO;
98674 pOrWc = &pOrInfo->wc;
98675 whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
98676 whereSplit(pOrWc, pExpr, TK_OR);
98677 exprAnalyzeAll(pSrc, pOrWc);
98678 if( db->mallocFailed ) return;
98679 assert( pOrWc->nTerm>=2 );
98682 ** Compute the set of tables that might satisfy cases 1 or 2.
98684 indexable = ~(Bitmask)0;
98685 chngToIN = ~(pWC->vmask);
98686 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
98687 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
98688 WhereAndInfo *pAndInfo;
98689 assert( pOrTerm->eOperator==0 );
98690 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
98691 chngToIN = 0;
98692 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
98693 if( pAndInfo ){
98694 WhereClause *pAndWC;
98695 WhereTerm *pAndTerm;
98696 int j;
98697 Bitmask b = 0;
98698 pOrTerm->u.pAndInfo = pAndInfo;
98699 pOrTerm->wtFlags |= TERM_ANDINFO;
98700 pOrTerm->eOperator = WO_AND;
98701 pAndWC = &pAndInfo->wc;
98702 whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
98703 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
98704 exprAnalyzeAll(pSrc, pAndWC);
98705 testcase( db->mallocFailed );
98706 if( !db->mallocFailed ){
98707 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
98708 assert( pAndTerm->pExpr );
98709 if( allowedOp(pAndTerm->pExpr->op) ){
98710 b |= getMask(pMaskSet, pAndTerm->leftCursor);
98714 indexable &= b;
98716 }else if( pOrTerm->wtFlags & TERM_COPIED ){
98717 /* Skip this term for now. We revisit it when we process the
98718 ** corresponding TERM_VIRTUAL term */
98719 }else{
98720 Bitmask b;
98721 b = getMask(pMaskSet, pOrTerm->leftCursor);
98722 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
98723 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
98724 b |= getMask(pMaskSet, pOther->leftCursor);
98726 indexable &= b;
98727 if( pOrTerm->eOperator!=WO_EQ ){
98728 chngToIN = 0;
98729 }else{
98730 chngToIN &= b;
98736 ** Record the set of tables that satisfy case 2. The set might be
98737 ** empty.
98739 pOrInfo->indexable = indexable;
98740 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
98743 ** chngToIN holds a set of tables that *might* satisfy case 1. But
98744 ** we have to do some additional checking to see if case 1 really
98745 ** is satisfied.
98747 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
98748 ** that there is no possibility of transforming the OR clause into an
98749 ** IN operator because one or more terms in the OR clause contain
98750 ** something other than == on a column in the single table. The 1-bit
98751 ** case means that every term of the OR clause is of the form
98752 ** "table.column=expr" for some single table. The one bit that is set
98753 ** will correspond to the common table. We still need to check to make
98754 ** sure the same column is used on all terms. The 2-bit case is when
98755 ** the all terms are of the form "table1.column=table2.column". It
98756 ** might be possible to form an IN operator with either table1.column
98757 ** or table2.column as the LHS if either is common to every term of
98758 ** the OR clause.
98760 ** Note that terms of the form "table.column1=table.column2" (the
98761 ** same table on both sizes of the ==) cannot be optimized.
98763 if( chngToIN ){
98764 int okToChngToIN = 0; /* True if the conversion to IN is valid */
98765 int iColumn = -1; /* Column index on lhs of IN operator */
98766 int iCursor = -1; /* Table cursor common to all terms */
98767 int j = 0; /* Loop counter */
98769 /* Search for a table and column that appears on one side or the
98770 ** other of the == operator in every subterm. That table and column
98771 ** will be recorded in iCursor and iColumn. There might not be any
98772 ** such table and column. Set okToChngToIN if an appropriate table
98773 ** and column is found but leave okToChngToIN false if not found.
98775 for(j=0; j<2 && !okToChngToIN; j++){
98776 pOrTerm = pOrWc->a;
98777 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
98778 assert( pOrTerm->eOperator==WO_EQ );
98779 pOrTerm->wtFlags &= ~TERM_OR_OK;
98780 if( pOrTerm->leftCursor==iCursor ){
98781 /* This is the 2-bit case and we are on the second iteration and
98782 ** current term is from the first iteration. So skip this term. */
98783 assert( j==1 );
98784 continue;
98786 if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
98787 /* This term must be of the form t1.a==t2.b where t2 is in the
98788 ** chngToIN set but t1 is not. This term will be either preceeded
98789 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
98790 ** and use its inversion. */
98791 testcase( pOrTerm->wtFlags & TERM_COPIED );
98792 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
98793 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
98794 continue;
98796 iColumn = pOrTerm->u.leftColumn;
98797 iCursor = pOrTerm->leftCursor;
98798 break;
98800 if( i<0 ){
98801 /* No candidate table+column was found. This can only occur
98802 ** on the second iteration */
98803 assert( j==1 );
98804 assert( (chngToIN&(chngToIN-1))==0 );
98805 assert( chngToIN==getMask(pMaskSet, iCursor) );
98806 break;
98808 testcase( j==1 );
98810 /* We have found a candidate table and column. Check to see if that
98811 ** table and column is common to every term in the OR clause */
98812 okToChngToIN = 1;
98813 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
98814 assert( pOrTerm->eOperator==WO_EQ );
98815 if( pOrTerm->leftCursor!=iCursor ){
98816 pOrTerm->wtFlags &= ~TERM_OR_OK;
98817 }else if( pOrTerm->u.leftColumn!=iColumn ){
98818 okToChngToIN = 0;
98819 }else{
98820 int affLeft, affRight;
98821 /* If the right-hand side is also a column, then the affinities
98822 ** of both right and left sides must be such that no type
98823 ** conversions are required on the right. (Ticket #2249)
98825 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
98826 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
98827 if( affRight!=0 && affRight!=affLeft ){
98828 okToChngToIN = 0;
98829 }else{
98830 pOrTerm->wtFlags |= TERM_OR_OK;
98836 /* At this point, okToChngToIN is true if original pTerm satisfies
98837 ** case 1. In that case, construct a new virtual term that is
98838 ** pTerm converted into an IN operator.
98840 ** EV: R-00211-15100
98842 if( okToChngToIN ){
98843 Expr *pDup; /* A transient duplicate expression */
98844 ExprList *pList = 0; /* The RHS of the IN operator */
98845 Expr *pLeft = 0; /* The LHS of the IN operator */
98846 Expr *pNew; /* The complete IN operator */
98848 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
98849 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
98850 assert( pOrTerm->eOperator==WO_EQ );
98851 assert( pOrTerm->leftCursor==iCursor );
98852 assert( pOrTerm->u.leftColumn==iColumn );
98853 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
98854 pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
98855 pLeft = pOrTerm->pExpr->pLeft;
98857 assert( pLeft!=0 );
98858 pDup = sqlite3ExprDup(db, pLeft, 0);
98859 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
98860 if( pNew ){
98861 int idxNew;
98862 transferJoinMarkings(pNew, pExpr);
98863 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
98864 pNew->x.pList = pList;
98865 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
98866 testcase( idxNew==0 );
98867 exprAnalyze(pSrc, pWC, idxNew);
98868 pTerm = &pWC->a[idxTerm];
98869 pWC->a[idxNew].iParent = idxTerm;
98870 pTerm->nChild = 1;
98871 }else{
98872 sqlite3ExprListDelete(db, pList);
98874 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
98878 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
98882 ** The input to this routine is an WhereTerm structure with only the
98883 ** "pExpr" field filled in. The job of this routine is to analyze the
98884 ** subexpression and populate all the other fields of the WhereTerm
98885 ** structure.
98887 ** If the expression is of the form "<expr> <op> X" it gets commuted
98888 ** to the standard form of "X <op> <expr>".
98890 ** If the expression is of the form "X <op> Y" where both X and Y are
98891 ** columns, then the original expression is unchanged and a new virtual
98892 ** term of the form "Y <op> X" is added to the WHERE clause and
98893 ** analyzed separately. The original term is marked with TERM_COPIED
98894 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
98895 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
98896 ** is a commuted copy of a prior term.) The original term has nChild=1
98897 ** and the copy has idxParent set to the index of the original term.
98899 static void exprAnalyze(
98900 SrcList *pSrc, /* the FROM clause */
98901 WhereClause *pWC, /* the WHERE clause */
98902 int idxTerm /* Index of the term to be analyzed */
98904 WhereTerm *pTerm; /* The term to be analyzed */
98905 WhereMaskSet *pMaskSet; /* Set of table index masks */
98906 Expr *pExpr; /* The expression to be analyzed */
98907 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
98908 Bitmask prereqAll; /* Prerequesites of pExpr */
98909 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
98910 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
98911 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
98912 int noCase = 0; /* LIKE/GLOB distinguishes case */
98913 int op; /* Top-level operator. pExpr->op */
98914 Parse *pParse = pWC->pParse; /* Parsing context */
98915 sqlite3 *db = pParse->db; /* Database connection */
98917 if( db->mallocFailed ){
98918 return;
98920 pTerm = &pWC->a[idxTerm];
98921 pMaskSet = pWC->pMaskSet;
98922 pExpr = pTerm->pExpr;
98923 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
98924 op = pExpr->op;
98925 if( op==TK_IN ){
98926 assert( pExpr->pRight==0 );
98927 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
98928 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
98929 }else{
98930 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
98932 }else if( op==TK_ISNULL ){
98933 pTerm->prereqRight = 0;
98934 }else{
98935 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
98937 prereqAll = exprTableUsage(pMaskSet, pExpr);
98938 if( ExprHasProperty(pExpr, EP_FromJoin) ){
98939 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
98940 prereqAll |= x;
98941 extraRight = x-1; /* ON clause terms may not be used with an index
98942 ** on left table of a LEFT JOIN. Ticket #3015 */
98944 pTerm->prereqAll = prereqAll;
98945 pTerm->leftCursor = -1;
98946 pTerm->iParent = -1;
98947 pTerm->eOperator = 0;
98948 if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
98949 Expr *pLeft = pExpr->pLeft;
98950 Expr *pRight = pExpr->pRight;
98951 if( pLeft->op==TK_COLUMN ){
98952 pTerm->leftCursor = pLeft->iTable;
98953 pTerm->u.leftColumn = pLeft->iColumn;
98954 pTerm->eOperator = operatorMask(op);
98956 if( pRight && pRight->op==TK_COLUMN ){
98957 WhereTerm *pNew;
98958 Expr *pDup;
98959 if( pTerm->leftCursor>=0 ){
98960 int idxNew;
98961 pDup = sqlite3ExprDup(db, pExpr, 0);
98962 if( db->mallocFailed ){
98963 sqlite3ExprDelete(db, pDup);
98964 return;
98966 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
98967 if( idxNew==0 ) return;
98968 pNew = &pWC->a[idxNew];
98969 pNew->iParent = idxTerm;
98970 pTerm = &pWC->a[idxTerm];
98971 pTerm->nChild = 1;
98972 pTerm->wtFlags |= TERM_COPIED;
98973 }else{
98974 pDup = pExpr;
98975 pNew = pTerm;
98977 exprCommute(pParse, pDup);
98978 pLeft = pDup->pLeft;
98979 pNew->leftCursor = pLeft->iTable;
98980 pNew->u.leftColumn = pLeft->iColumn;
98981 testcase( (prereqLeft | extraRight) != prereqLeft );
98982 pNew->prereqRight = prereqLeft | extraRight;
98983 pNew->prereqAll = prereqAll;
98984 pNew->eOperator = operatorMask(pDup->op);
98988 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
98989 /* If a term is the BETWEEN operator, create two new virtual terms
98990 ** that define the range that the BETWEEN implements. For example:
98992 ** a BETWEEN b AND c
98994 ** is converted into:
98996 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
98998 ** The two new terms are added onto the end of the WhereClause object.
98999 ** The new terms are "dynamic" and are children of the original BETWEEN
99000 ** term. That means that if the BETWEEN term is coded, the children are
99001 ** skipped. Or, if the children are satisfied by an index, the original
99002 ** BETWEEN term is skipped.
99004 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
99005 ExprList *pList = pExpr->x.pList;
99006 int i;
99007 static const u8 ops[] = {TK_GE, TK_LE};
99008 assert( pList!=0 );
99009 assert( pList->nExpr==2 );
99010 for(i=0; i<2; i++){
99011 Expr *pNewExpr;
99012 int idxNew;
99013 pNewExpr = sqlite3PExpr(pParse, ops[i],
99014 sqlite3ExprDup(db, pExpr->pLeft, 0),
99015 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
99016 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
99017 testcase( idxNew==0 );
99018 exprAnalyze(pSrc, pWC, idxNew);
99019 pTerm = &pWC->a[idxTerm];
99020 pWC->a[idxNew].iParent = idxTerm;
99022 pTerm->nChild = 2;
99024 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
99026 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
99027 /* Analyze a term that is composed of two or more subterms connected by
99028 ** an OR operator.
99030 else if( pExpr->op==TK_OR ){
99031 assert( pWC->op==TK_AND );
99032 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
99033 pTerm = &pWC->a[idxTerm];
99035 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
99037 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
99038 /* Add constraints to reduce the search space on a LIKE or GLOB
99039 ** operator.
99041 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
99043 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
99045 ** The last character of the prefix "abc" is incremented to form the
99046 ** termination condition "abd".
99048 if( pWC->op==TK_AND
99049 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
99051 Expr *pLeft; /* LHS of LIKE/GLOB operator */
99052 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
99053 Expr *pNewExpr1;
99054 Expr *pNewExpr2;
99055 int idxNew1;
99056 int idxNew2;
99057 CollSeq *pColl; /* Collating sequence to use */
99059 pLeft = pExpr->x.pList->a[1].pExpr;
99060 pStr2 = sqlite3ExprDup(db, pStr1, 0);
99061 if( !db->mallocFailed ){
99062 u8 c, *pC; /* Last character before the first wildcard */
99063 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
99064 c = *pC;
99065 if( noCase ){
99066 /* The point is to increment the last character before the first
99067 ** wildcard. But if we increment '@', that will push it into the
99068 ** alphabetic range where case conversions will mess up the
99069 ** inequality. To avoid this, make sure to also run the full
99070 ** LIKE on all candidate expressions by clearing the isComplete flag
99072 if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */
99075 c = sqlite3UpperToLower[c];
99077 *pC = c + 1;
99079 pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
99080 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
99081 sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
99082 pStr1, 0);
99083 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
99084 testcase( idxNew1==0 );
99085 exprAnalyze(pSrc, pWC, idxNew1);
99086 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
99087 sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
99088 pStr2, 0);
99089 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
99090 testcase( idxNew2==0 );
99091 exprAnalyze(pSrc, pWC, idxNew2);
99092 pTerm = &pWC->a[idxTerm];
99093 if( isComplete ){
99094 pWC->a[idxNew1].iParent = idxTerm;
99095 pWC->a[idxNew2].iParent = idxTerm;
99096 pTerm->nChild = 2;
99099 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
99101 #ifndef SQLITE_OMIT_VIRTUALTABLE
99102 /* Add a WO_MATCH auxiliary term to the constraint set if the
99103 ** current expression is of the form: column MATCH expr.
99104 ** This information is used by the xBestIndex methods of
99105 ** virtual tables. The native query optimizer does not attempt
99106 ** to do anything with MATCH functions.
99108 if( isMatchOfColumn(pExpr) ){
99109 int idxNew;
99110 Expr *pRight, *pLeft;
99111 WhereTerm *pNewTerm;
99112 Bitmask prereqColumn, prereqExpr;
99114 pRight = pExpr->x.pList->a[0].pExpr;
99115 pLeft = pExpr->x.pList->a[1].pExpr;
99116 prereqExpr = exprTableUsage(pMaskSet, pRight);
99117 prereqColumn = exprTableUsage(pMaskSet, pLeft);
99118 if( (prereqExpr & prereqColumn)==0 ){
99119 Expr *pNewExpr;
99120 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
99121 0, sqlite3ExprDup(db, pRight, 0), 0);
99122 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
99123 testcase( idxNew==0 );
99124 pNewTerm = &pWC->a[idxNew];
99125 pNewTerm->prereqRight = prereqExpr;
99126 pNewTerm->leftCursor = pLeft->iTable;
99127 pNewTerm->u.leftColumn = pLeft->iColumn;
99128 pNewTerm->eOperator = WO_MATCH;
99129 pNewTerm->iParent = idxTerm;
99130 pTerm = &pWC->a[idxTerm];
99131 pTerm->nChild = 1;
99132 pTerm->wtFlags |= TERM_COPIED;
99133 pNewTerm->prereqAll = pTerm->prereqAll;
99136 #endif /* SQLITE_OMIT_VIRTUALTABLE */
99138 #ifdef SQLITE_ENABLE_STAT2
99139 /* When sqlite_stat2 histogram data is available an operator of the
99140 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
99141 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
99142 ** virtual term of that form.
99144 ** Note that the virtual term must be tagged with TERM_VNULL. This
99145 ** TERM_VNULL tag will suppress the not-null check at the beginning
99146 ** of the loop. Without the TERM_VNULL flag, the not-null check at
99147 ** the start of the loop will prevent any results from being returned.
99149 if( pExpr->op==TK_NOTNULL
99150 && pExpr->pLeft->op==TK_COLUMN
99151 && pExpr->pLeft->iColumn>=0
99153 Expr *pNewExpr;
99154 Expr *pLeft = pExpr->pLeft;
99155 int idxNew;
99156 WhereTerm *pNewTerm;
99158 pNewExpr = sqlite3PExpr(pParse, TK_GT,
99159 sqlite3ExprDup(db, pLeft, 0),
99160 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
99162 idxNew = whereClauseInsert(pWC, pNewExpr,
99163 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
99164 if( idxNew ){
99165 pNewTerm = &pWC->a[idxNew];
99166 pNewTerm->prereqRight = 0;
99167 pNewTerm->leftCursor = pLeft->iTable;
99168 pNewTerm->u.leftColumn = pLeft->iColumn;
99169 pNewTerm->eOperator = WO_GT;
99170 pNewTerm->iParent = idxTerm;
99171 pTerm = &pWC->a[idxTerm];
99172 pTerm->nChild = 1;
99173 pTerm->wtFlags |= TERM_COPIED;
99174 pNewTerm->prereqAll = pTerm->prereqAll;
99177 #endif /* SQLITE_ENABLE_STAT2 */
99179 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
99180 ** an index for tables to the left of the join.
99182 pTerm->prereqRight |= extraRight;
99186 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
99187 ** a reference to any table other than the iBase table.
99189 static int referencesOtherTables(
99190 ExprList *pList, /* Search expressions in ths list */
99191 WhereMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
99192 int iFirst, /* Be searching with the iFirst-th expression */
99193 int iBase /* Ignore references to this table */
99195 Bitmask allowed = ~getMask(pMaskSet, iBase);
99196 while( iFirst<pList->nExpr ){
99197 if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
99198 return 1;
99201 return 0;
99206 ** This routine decides if pIdx can be used to satisfy the ORDER BY
99207 ** clause. If it can, it returns 1. If pIdx cannot satisfy the
99208 ** ORDER BY clause, this routine returns 0.
99210 ** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
99211 ** left-most table in the FROM clause of that same SELECT statement and
99212 ** the table has a cursor number of "base". pIdx is an index on pTab.
99214 ** nEqCol is the number of columns of pIdx that are used as equality
99215 ** constraints. Any of these columns may be missing from the ORDER BY
99216 ** clause and the match can still be a success.
99218 ** All terms of the ORDER BY that match against the index must be either
99219 ** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
99220 ** index do not need to satisfy this constraint.) The *pbRev value is
99221 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
99222 ** the ORDER BY clause is all ASC.
99224 static int isSortingIndex(
99225 Parse *pParse, /* Parsing context */
99226 WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
99227 Index *pIdx, /* The index we are testing */
99228 int base, /* Cursor number for the table to be sorted */
99229 ExprList *pOrderBy, /* The ORDER BY clause */
99230 int nEqCol, /* Number of index columns with == constraints */
99231 int wsFlags, /* Index usages flags */
99232 int *pbRev /* Set to 1 if ORDER BY is DESC */
99234 int i, j; /* Loop counters */
99235 int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
99236 int nTerm; /* Number of ORDER BY terms */
99237 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
99238 sqlite3 *db = pParse->db;
99240 assert( pOrderBy!=0 );
99241 nTerm = pOrderBy->nExpr;
99242 assert( nTerm>0 );
99244 /* Argument pIdx must either point to a 'real' named index structure,
99245 ** or an index structure allocated on the stack by bestBtreeIndex() to
99246 ** represent the rowid index that is part of every table. */
99247 assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
99249 /* Match terms of the ORDER BY clause against columns of
99250 ** the index.
99252 ** Note that indices have pIdx->nColumn regular columns plus
99253 ** one additional column containing the rowid. The rowid column
99254 ** of the index is also allowed to match against the ORDER BY
99255 ** clause.
99257 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
99258 Expr *pExpr; /* The expression of the ORDER BY pTerm */
99259 CollSeq *pColl; /* The collating sequence of pExpr */
99260 int termSortOrder; /* Sort order for this term */
99261 int iColumn; /* The i-th column of the index. -1 for rowid */
99262 int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
99263 const char *zColl; /* Name of the collating sequence for i-th index term */
99265 pExpr = pTerm->pExpr;
99266 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
99267 /* Can not use an index sort on anything that is not a column in the
99268 ** left-most table of the FROM clause */
99269 break;
99271 pColl = sqlite3ExprCollSeq(pParse, pExpr);
99272 if( !pColl ){
99273 pColl = db->pDfltColl;
99275 if( pIdx->zName && i<pIdx->nColumn ){
99276 iColumn = pIdx->aiColumn[i];
99277 if( iColumn==pIdx->pTable->iPKey ){
99278 iColumn = -1;
99280 iSortOrder = pIdx->aSortOrder[i];
99281 zColl = pIdx->azColl[i];
99282 }else{
99283 iColumn = -1;
99284 iSortOrder = 0;
99285 zColl = pColl->zName;
99287 if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
99288 /* Term j of the ORDER BY clause does not match column i of the index */
99289 if( i<nEqCol ){
99290 /* If an index column that is constrained by == fails to match an
99291 ** ORDER BY term, that is OK. Just ignore that column of the index
99293 continue;
99294 }else if( i==pIdx->nColumn ){
99295 /* Index column i is the rowid. All other terms match. */
99296 break;
99297 }else{
99298 /* If an index column fails to match and is not constrained by ==
99299 ** then the index cannot satisfy the ORDER BY constraint.
99301 return 0;
99304 assert( pIdx->aSortOrder!=0 || iColumn==-1 );
99305 assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
99306 assert( iSortOrder==0 || iSortOrder==1 );
99307 termSortOrder = iSortOrder ^ pTerm->sortOrder;
99308 if( i>nEqCol ){
99309 if( termSortOrder!=sortOrder ){
99310 /* Indices can only be used if all ORDER BY terms past the
99311 ** equality constraints are all either DESC or ASC. */
99312 return 0;
99314 }else{
99315 sortOrder = termSortOrder;
99317 j++;
99318 pTerm++;
99319 if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99320 /* If the indexed column is the primary key and everything matches
99321 ** so far and none of the ORDER BY terms to the right reference other
99322 ** tables in the join, then we are assured that the index can be used
99323 ** to sort because the primary key is unique and so none of the other
99324 ** columns will make any difference
99326 j = nTerm;
99330 *pbRev = sortOrder!=0;
99331 if( j>=nTerm ){
99332 /* All terms of the ORDER BY clause are covered by this index so
99333 ** this index can be used for sorting. */
99334 return 1;
99336 if( pIdx->onError!=OE_None && i==pIdx->nColumn
99337 && (wsFlags & WHERE_COLUMN_NULL)==0
99338 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99339 /* All terms of this index match some prefix of the ORDER BY clause
99340 ** and the index is UNIQUE and no terms on the tail of the ORDER BY
99341 ** clause reference other tables in a join. If this is all true then
99342 ** the order by clause is superfluous. Not that if the matching
99343 ** condition is IS NULL then the result is not necessarily unique
99344 ** even on a UNIQUE index, so disallow those cases. */
99345 return 1;
99347 return 0;
99351 ** Prepare a crude estimate of the logarithm of the input value.
99352 ** The results need not be exact. This is only used for estimating
99353 ** the total cost of performing operations with O(logN) or O(NlogN)
99354 ** complexity. Because N is just a guess, it is no great tragedy if
99355 ** logN is a little off.
99357 static double estLog(double N){
99358 double logN = 1;
99359 double x = 10;
99360 while( N>x ){
99361 logN += 1;
99362 x *= 10;
99364 return logN;
99368 ** Two routines for printing the content of an sqlite3_index_info
99369 ** structure. Used for testing and debugging only. If neither
99370 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
99371 ** are no-ops.
99373 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
99374 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
99375 int i;
99376 if( !sqlite3WhereTrace ) return;
99377 for(i=0; i<p->nConstraint; i++){
99378 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
99380 p->aConstraint[i].iColumn,
99381 p->aConstraint[i].iTermOffset,
99382 p->aConstraint[i].op,
99383 p->aConstraint[i].usable);
99385 for(i=0; i<p->nOrderBy; i++){
99386 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
99388 p->aOrderBy[i].iColumn,
99389 p->aOrderBy[i].desc);
99392 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
99393 int i;
99394 if( !sqlite3WhereTrace ) return;
99395 for(i=0; i<p->nConstraint; i++){
99396 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
99398 p->aConstraintUsage[i].argvIndex,
99399 p->aConstraintUsage[i].omit);
99401 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
99402 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
99403 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
99404 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
99406 #else
99407 #define TRACE_IDX_INPUTS(A)
99408 #define TRACE_IDX_OUTPUTS(A)
99409 #endif
99412 ** Required because bestIndex() is called by bestOrClauseIndex()
99414 static void bestIndex(
99415 Parse*, WhereClause*, struct SrcList_item*,
99416 Bitmask, Bitmask, ExprList*, WhereCost*);
99419 ** This routine attempts to find an scanning strategy that can be used
99420 ** to optimize an 'OR' expression that is part of a WHERE clause.
99422 ** The table associated with FROM clause term pSrc may be either a
99423 ** regular B-Tree table or a virtual table.
99425 static void bestOrClauseIndex(
99426 Parse *pParse, /* The parsing context */
99427 WhereClause *pWC, /* The WHERE clause */
99428 struct SrcList_item *pSrc, /* The FROM clause term to search */
99429 Bitmask notReady, /* Mask of cursors not available for indexing */
99430 Bitmask notValid, /* Cursors not available for any purpose */
99431 ExprList *pOrderBy, /* The ORDER BY clause */
99432 WhereCost *pCost /* Lowest cost query plan */
99434 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
99435 const int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
99436 const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
99437 WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
99438 WhereTerm *pTerm; /* A single term of the WHERE clause */
99440 /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
99441 ** are used */
99442 if( pSrc->notIndexed || pSrc->pIndex!=0 ){
99443 return;
99446 /* Search the WHERE clause terms for a usable WO_OR term. */
99447 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99448 if( pTerm->eOperator==WO_OR
99449 && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
99450 && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
99452 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
99453 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
99454 WhereTerm *pOrTerm;
99455 int flags = WHERE_MULTI_OR;
99456 double rTotal = 0;
99457 double nRow = 0;
99458 Bitmask used = 0;
99460 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
99461 WhereCost sTermCost;
99462 WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
99463 (pOrTerm - pOrWC->a), (pTerm - pWC->a)
99465 if( pOrTerm->eOperator==WO_AND ){
99466 WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
99467 bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
99468 }else if( pOrTerm->leftCursor==iCur ){
99469 WhereClause tempWC;
99470 tempWC.pParse = pWC->pParse;
99471 tempWC.pMaskSet = pWC->pMaskSet;
99472 tempWC.op = TK_AND;
99473 tempWC.a = pOrTerm;
99474 tempWC.nTerm = 1;
99475 bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
99476 }else{
99477 continue;
99479 rTotal += sTermCost.rCost;
99480 nRow += sTermCost.plan.nRow;
99481 used |= sTermCost.used;
99482 if( rTotal>=pCost->rCost ) break;
99485 /* If there is an ORDER BY clause, increase the scan cost to account
99486 ** for the cost of the sort. */
99487 if( pOrderBy!=0 ){
99488 WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
99489 rTotal, rTotal+nRow*estLog(nRow)));
99490 rTotal += nRow*estLog(nRow);
99493 /* If the cost of scanning using this OR term for optimization is
99494 ** less than the current cost stored in pCost, replace the contents
99495 ** of pCost. */
99496 WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
99497 if( rTotal<pCost->rCost ){
99498 pCost->rCost = rTotal;
99499 pCost->used = used;
99500 pCost->plan.nRow = nRow;
99501 pCost->plan.wsFlags = flags;
99502 pCost->plan.u.pTerm = pTerm;
99506 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
99509 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99511 ** Return TRUE if the WHERE clause term pTerm is of a form where it
99512 ** could be used with an index to access pSrc, assuming an appropriate
99513 ** index existed.
99515 static int termCanDriveIndex(
99516 WhereTerm *pTerm, /* WHERE clause term to check */
99517 struct SrcList_item *pSrc, /* Table we are trying to access */
99518 Bitmask notReady /* Tables in outer loops of the join */
99520 char aff;
99521 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
99522 if( pTerm->eOperator!=WO_EQ ) return 0;
99523 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
99524 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
99525 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
99526 return 1;
99528 #endif
99530 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99532 ** If the query plan for pSrc specified in pCost is a full table scan
99533 ** and indexing is allows (if there is no NOT INDEXED clause) and it
99534 ** possible to construct a transient index that would perform better
99535 ** than a full table scan even when the cost of constructing the index
99536 ** is taken into account, then alter the query plan to use the
99537 ** transient index.
99539 static void bestAutomaticIndex(
99540 Parse *pParse, /* The parsing context */
99541 WhereClause *pWC, /* The WHERE clause */
99542 struct SrcList_item *pSrc, /* The FROM clause term to search */
99543 Bitmask notReady, /* Mask of cursors that are not available */
99544 WhereCost *pCost /* Lowest cost query plan */
99546 double nTableRow; /* Rows in the input table */
99547 double logN; /* log(nTableRow) */
99548 double costTempIdx; /* per-query cost of the transient index */
99549 WhereTerm *pTerm; /* A single term of the WHERE clause */
99550 WhereTerm *pWCEnd; /* End of pWC->a[] */
99551 Table *pTable; /* Table tht might be indexed */
99553 if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
99554 /* Automatic indices are disabled at run-time */
99555 return;
99557 if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
99558 /* We already have some kind of index in use for this query. */
99559 return;
99561 if( pSrc->notIndexed ){
99562 /* The NOT INDEXED clause appears in the SQL. */
99563 return;
99566 assert( pParse->nQueryLoop >= (double)1 );
99567 pTable = pSrc->pTab;
99568 nTableRow = pTable->nRowEst;
99569 logN = estLog(nTableRow);
99570 costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
99571 if( costTempIdx>=pCost->rCost ){
99572 /* The cost of creating the transient table would be greater than
99573 ** doing the full table scan */
99574 return;
99577 /* Search for any equality comparison term */
99578 pWCEnd = &pWC->a[pWC->nTerm];
99579 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99580 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99581 WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
99582 pCost->rCost, costTempIdx));
99583 pCost->rCost = costTempIdx;
99584 pCost->plan.nRow = logN + 1;
99585 pCost->plan.wsFlags = WHERE_TEMP_INDEX;
99586 pCost->used = pTerm->prereqRight;
99587 break;
99591 #else
99592 # define bestAutomaticIndex(A,B,C,D,E) /* no-op */
99593 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
99596 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99598 ** Generate code to construct the Index object for an automatic index
99599 ** and to set up the WhereLevel object pLevel so that the code generator
99600 ** makes use of the automatic index.
99602 static void constructAutomaticIndex(
99603 Parse *pParse, /* The parsing context */
99604 WhereClause *pWC, /* The WHERE clause */
99605 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
99606 Bitmask notReady, /* Mask of cursors that are not available */
99607 WhereLevel *pLevel /* Write new index here */
99609 int nColumn; /* Number of columns in the constructed index */
99610 WhereTerm *pTerm; /* A single term of the WHERE clause */
99611 WhereTerm *pWCEnd; /* End of pWC->a[] */
99612 int nByte; /* Byte of memory needed for pIdx */
99613 Index *pIdx; /* Object describing the transient index */
99614 Vdbe *v; /* Prepared statement under construction */
99615 int regIsInit; /* Register set by initialization */
99616 int addrInit; /* Address of the initialization bypass jump */
99617 Table *pTable; /* The table being indexed */
99618 KeyInfo *pKeyinfo; /* Key information for the index */
99619 int addrTop; /* Top of the index fill loop */
99620 int regRecord; /* Register holding an index record */
99621 int n; /* Column counter */
99622 int i; /* Loop counter */
99623 int mxBitCol; /* Maximum column in pSrc->colUsed */
99624 CollSeq *pColl; /* Collating sequence to on a column */
99625 Bitmask idxCols; /* Bitmap of columns used for indexing */
99626 Bitmask extraCols; /* Bitmap of additional columns */
99628 /* Generate code to skip over the creation and initialization of the
99629 ** transient index on 2nd and subsequent iterations of the loop. */
99630 v = pParse->pVdbe;
99631 assert( v!=0 );
99632 regIsInit = ++pParse->nMem;
99633 addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
99634 sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
99636 /* Count the number of columns that will be added to the index
99637 ** and used to match WHERE clause constraints */
99638 nColumn = 0;
99639 pTable = pSrc->pTab;
99640 pWCEnd = &pWC->a[pWC->nTerm];
99641 idxCols = 0;
99642 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99643 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99644 int iCol = pTerm->u.leftColumn;
99645 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
99646 testcase( iCol==BMS );
99647 testcase( iCol==BMS-1 );
99648 if( (idxCols & cMask)==0 ){
99649 nColumn++;
99650 idxCols |= cMask;
99654 assert( nColumn>0 );
99655 pLevel->plan.nEq = nColumn;
99657 /* Count the number of additional columns needed to create a
99658 ** covering index. A "covering index" is an index that contains all
99659 ** columns that are needed by the query. With a covering index, the
99660 ** original table never needs to be accessed. Automatic indices must
99661 ** be a covering index because the index will not be updated if the
99662 ** original table changes and the index and table cannot both be used
99663 ** if they go out of sync.
99665 extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
99666 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
99667 testcase( pTable->nCol==BMS-1 );
99668 testcase( pTable->nCol==BMS-2 );
99669 for(i=0; i<mxBitCol; i++){
99670 if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
99672 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
99673 nColumn += pTable->nCol - BMS + 1;
99675 pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
99677 /* Construct the Index object to describe this index */
99678 nByte = sizeof(Index);
99679 nByte += nColumn*sizeof(int); /* Index.aiColumn */
99680 nByte += nColumn*sizeof(char*); /* Index.azColl */
99681 nByte += nColumn; /* Index.aSortOrder */
99682 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
99683 if( pIdx==0 ) return;
99684 pLevel->plan.u.pIdx = pIdx;
99685 pIdx->azColl = (char**)&pIdx[1];
99686 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
99687 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
99688 pIdx->zName = "auto-index";
99689 pIdx->nColumn = nColumn;
99690 pIdx->pTable = pTable;
99691 n = 0;
99692 idxCols = 0;
99693 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99694 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99695 int iCol = pTerm->u.leftColumn;
99696 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
99697 if( (idxCols & cMask)==0 ){
99698 Expr *pX = pTerm->pExpr;
99699 idxCols |= cMask;
99700 pIdx->aiColumn[n] = pTerm->u.leftColumn;
99701 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
99702 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
99703 n++;
99707 assert( (u32)n==pLevel->plan.nEq );
99709 /* Add additional columns needed to make the automatic index into
99710 ** a covering index */
99711 for(i=0; i<mxBitCol; i++){
99712 if( extraCols & (((Bitmask)1)<<i) ){
99713 pIdx->aiColumn[n] = i;
99714 pIdx->azColl[n] = "BINARY";
99715 n++;
99718 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
99719 for(i=BMS-1; i<pTable->nCol; i++){
99720 pIdx->aiColumn[n] = i;
99721 pIdx->azColl[n] = "BINARY";
99722 n++;
99725 assert( n==nColumn );
99727 /* Create the automatic index */
99728 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
99729 assert( pLevel->iIdxCur>=0 );
99730 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
99731 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
99732 VdbeComment((v, "for %s", pTable->zName));
99734 /* Fill the automatic index with content */
99735 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
99736 regRecord = sqlite3GetTempReg(pParse);
99737 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
99738 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
99739 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
99740 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
99741 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
99742 sqlite3VdbeJumpHere(v, addrTop);
99743 sqlite3ReleaseTempReg(pParse, regRecord);
99745 /* Jump here when skipping the initialization */
99746 sqlite3VdbeJumpHere(v, addrInit);
99748 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
99750 #ifndef SQLITE_OMIT_VIRTUALTABLE
99752 ** Allocate and populate an sqlite3_index_info structure. It is the
99753 ** responsibility of the caller to eventually release the structure
99754 ** by passing the pointer returned by this function to sqlite3_free().
99756 static sqlite3_index_info *allocateIndexInfo(
99757 Parse *pParse,
99758 WhereClause *pWC,
99759 struct SrcList_item *pSrc,
99760 ExprList *pOrderBy
99762 int i, j;
99763 int nTerm;
99764 struct sqlite3_index_constraint *pIdxCons;
99765 struct sqlite3_index_orderby *pIdxOrderBy;
99766 struct sqlite3_index_constraint_usage *pUsage;
99767 WhereTerm *pTerm;
99768 int nOrderBy;
99769 sqlite3_index_info *pIdxInfo;
99771 WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
99773 /* Count the number of possible WHERE clause constraints referring
99774 ** to this virtual table */
99775 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
99776 if( pTerm->leftCursor != pSrc->iCursor ) continue;
99777 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
99778 testcase( pTerm->eOperator==WO_IN );
99779 testcase( pTerm->eOperator==WO_ISNULL );
99780 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
99781 nTerm++;
99784 /* If the ORDER BY clause contains only columns in the current
99785 ** virtual table then allocate space for the aOrderBy part of
99786 ** the sqlite3_index_info structure.
99788 nOrderBy = 0;
99789 if( pOrderBy ){
99790 for(i=0; i<pOrderBy->nExpr; i++){
99791 Expr *pExpr = pOrderBy->a[i].pExpr;
99792 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
99794 if( i==pOrderBy->nExpr ){
99795 nOrderBy = pOrderBy->nExpr;
99799 /* Allocate the sqlite3_index_info structure
99801 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
99802 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
99803 + sizeof(*pIdxOrderBy)*nOrderBy );
99804 if( pIdxInfo==0 ){
99805 sqlite3ErrorMsg(pParse, "out of memory");
99806 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
99807 return 0;
99810 /* Initialize the structure. The sqlite3_index_info structure contains
99811 ** many fields that are declared "const" to prevent xBestIndex from
99812 ** changing them. We have to do some funky casting in order to
99813 ** initialize those fields.
99815 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
99816 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
99817 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
99818 *(int*)&pIdxInfo->nConstraint = nTerm;
99819 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
99820 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
99821 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
99822 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
99823 pUsage;
99825 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
99826 if( pTerm->leftCursor != pSrc->iCursor ) continue;
99827 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
99828 testcase( pTerm->eOperator==WO_IN );
99829 testcase( pTerm->eOperator==WO_ISNULL );
99830 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
99831 pIdxCons[j].iColumn = pTerm->u.leftColumn;
99832 pIdxCons[j].iTermOffset = i;
99833 pIdxCons[j].op = (u8)pTerm->eOperator;
99834 /* The direct assignment in the previous line is possible only because
99835 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
99836 ** following asserts verify this fact. */
99837 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
99838 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
99839 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
99840 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
99841 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
99842 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
99843 assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
99844 j++;
99846 for(i=0; i<nOrderBy; i++){
99847 Expr *pExpr = pOrderBy->a[i].pExpr;
99848 pIdxOrderBy[i].iColumn = pExpr->iColumn;
99849 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
99852 return pIdxInfo;
99856 ** The table object reference passed as the second argument to this function
99857 ** must represent a virtual table. This function invokes the xBestIndex()
99858 ** method of the virtual table with the sqlite3_index_info pointer passed
99859 ** as the argument.
99861 ** If an error occurs, pParse is populated with an error message and a
99862 ** non-zero value is returned. Otherwise, 0 is returned and the output
99863 ** part of the sqlite3_index_info structure is left populated.
99865 ** Whether or not an error is returned, it is the responsibility of the
99866 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
99867 ** that this is required.
99869 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
99870 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
99871 int i;
99872 int rc;
99874 WHERETRACE(("xBestIndex for %s\n", pTab->zName));
99875 TRACE_IDX_INPUTS(p);
99876 rc = pVtab->pModule->xBestIndex(pVtab, p);
99877 TRACE_IDX_OUTPUTS(p);
99879 if( rc!=SQLITE_OK ){
99880 if( rc==SQLITE_NOMEM ){
99881 pParse->db->mallocFailed = 1;
99882 }else if( !pVtab->zErrMsg ){
99883 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
99884 }else{
99885 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
99888 sqlite3_free(pVtab->zErrMsg);
99889 pVtab->zErrMsg = 0;
99891 for(i=0; i<p->nConstraint; i++){
99892 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
99893 sqlite3ErrorMsg(pParse,
99894 "table %s: xBestIndex returned an invalid plan", pTab->zName);
99898 return pParse->nErr;
99903 ** Compute the best index for a virtual table.
99905 ** The best index is computed by the xBestIndex method of the virtual
99906 ** table module. This routine is really just a wrapper that sets up
99907 ** the sqlite3_index_info structure that is used to communicate with
99908 ** xBestIndex.
99910 ** In a join, this routine might be called multiple times for the
99911 ** same virtual table. The sqlite3_index_info structure is created
99912 ** and initialized on the first invocation and reused on all subsequent
99913 ** invocations. The sqlite3_index_info structure is also used when
99914 ** code is generated to access the virtual table. The whereInfoDelete()
99915 ** routine takes care of freeing the sqlite3_index_info structure after
99916 ** everybody has finished with it.
99918 static void bestVirtualIndex(
99919 Parse *pParse, /* The parsing context */
99920 WhereClause *pWC, /* The WHERE clause */
99921 struct SrcList_item *pSrc, /* The FROM clause term to search */
99922 Bitmask notReady, /* Mask of cursors not available for index */
99923 Bitmask notValid, /* Cursors not valid for any purpose */
99924 ExprList *pOrderBy, /* The order by clause */
99925 WhereCost *pCost, /* Lowest cost query plan */
99926 sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
99928 Table *pTab = pSrc->pTab;
99929 sqlite3_index_info *pIdxInfo;
99930 struct sqlite3_index_constraint *pIdxCons;
99931 struct sqlite3_index_constraint_usage *pUsage;
99932 WhereTerm *pTerm;
99933 int i, j;
99934 int nOrderBy;
99935 double rCost;
99937 /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
99938 ** malloc in allocateIndexInfo() fails and this function returns leaving
99939 ** wsFlags in an uninitialized state, the caller may behave unpredictably.
99941 memset(pCost, 0, sizeof(*pCost));
99942 pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
99944 /* If the sqlite3_index_info structure has not been previously
99945 ** allocated and initialized, then allocate and initialize it now.
99947 pIdxInfo = *ppIdxInfo;
99948 if( pIdxInfo==0 ){
99949 *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
99951 if( pIdxInfo==0 ){
99952 return;
99955 /* At this point, the sqlite3_index_info structure that pIdxInfo points
99956 ** to will have been initialized, either during the current invocation or
99957 ** during some prior invocation. Now we just have to customize the
99958 ** details of pIdxInfo for the current invocation and pass it to
99959 ** xBestIndex.
99962 /* The module name must be defined. Also, by this point there must
99963 ** be a pointer to an sqlite3_vtab structure. Otherwise
99964 ** sqlite3ViewGetColumnNames() would have picked up the error.
99966 assert( pTab->azModuleArg && pTab->azModuleArg[0] );
99967 assert( sqlite3GetVTable(pParse->db, pTab) );
99969 /* Set the aConstraint[].usable fields and initialize all
99970 ** output variables to zero.
99972 ** aConstraint[].usable is true for constraints where the right-hand
99973 ** side contains only references to tables to the left of the current
99974 ** table. In other words, if the constraint is of the form:
99976 ** column = expr
99978 ** and we are evaluating a join, then the constraint on column is
99979 ** only valid if all tables referenced in expr occur to the left
99980 ** of the table containing column.
99982 ** The aConstraints[] array contains entries for all constraints
99983 ** on the current table. That way we only have to compute it once
99984 ** even though we might try to pick the best index multiple times.
99985 ** For each attempt at picking an index, the order of tables in the
99986 ** join might be different so we have to recompute the usable flag
99987 ** each time.
99989 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
99990 pUsage = pIdxInfo->aConstraintUsage;
99991 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
99992 j = pIdxCons->iTermOffset;
99993 pTerm = &pWC->a[j];
99994 pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
99996 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
99997 if( pIdxInfo->needToFreeIdxStr ){
99998 sqlite3_free(pIdxInfo->idxStr);
100000 pIdxInfo->idxStr = 0;
100001 pIdxInfo->idxNum = 0;
100002 pIdxInfo->needToFreeIdxStr = 0;
100003 pIdxInfo->orderByConsumed = 0;
100004 /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
100005 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
100006 nOrderBy = pIdxInfo->nOrderBy;
100007 if( !pOrderBy ){
100008 pIdxInfo->nOrderBy = 0;
100011 if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
100012 return;
100015 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
100016 for(i=0; i<pIdxInfo->nConstraint; i++){
100017 if( pUsage[i].argvIndex>0 ){
100018 pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
100022 /* If there is an ORDER BY clause, and the selected virtual table index
100023 ** does not satisfy it, increase the cost of the scan accordingly. This
100024 ** matches the processing for non-virtual tables in bestBtreeIndex().
100026 rCost = pIdxInfo->estimatedCost;
100027 if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
100028 rCost += estLog(rCost)*rCost;
100031 /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
100032 ** inital value of lowestCost in this loop. If it is, then the
100033 ** (cost<lowestCost) test below will never be true.
100035 ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
100036 ** is defined.
100038 if( (SQLITE_BIG_DBL/((double)2))<rCost ){
100039 pCost->rCost = (SQLITE_BIG_DBL/((double)2));
100040 }else{
100041 pCost->rCost = rCost;
100043 pCost->plan.u.pVtabIdx = pIdxInfo;
100044 if( pIdxInfo->orderByConsumed ){
100045 pCost->plan.wsFlags |= WHERE_ORDERBY;
100047 pCost->plan.nEq = 0;
100048 pIdxInfo->nOrderBy = nOrderBy;
100050 /* Try to find a more efficient access pattern by using multiple indexes
100051 ** to optimize an OR expression within the WHERE clause.
100053 bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100055 #endif /* SQLITE_OMIT_VIRTUALTABLE */
100058 ** Argument pIdx is a pointer to an index structure that has an array of
100059 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
100060 ** stored in Index.aSample. These samples divide the domain of values stored
100061 ** the index into (SQLITE_INDEX_SAMPLES+1) regions.
100062 ** Region 0 contains all values less than the first sample value. Region
100063 ** 1 contains values between the first and second samples. Region 2 contains
100064 ** values between samples 2 and 3. And so on. Region SQLITE_INDEX_SAMPLES
100065 ** contains values larger than the last sample.
100067 ** If the index contains many duplicates of a single value, then it is
100068 ** possible that two or more adjacent samples can hold the same value.
100069 ** When that is the case, the smallest possible region code is returned
100070 ** when roundUp is false and the largest possible region code is returned
100071 ** when roundUp is true.
100073 ** If successful, this function determines which of the regions value
100074 ** pVal lies in, sets *piRegion to the region index (a value between 0
100075 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
100076 ** Or, if an OOM occurs while converting text values between encodings,
100077 ** SQLITE_NOMEM is returned and *piRegion is undefined.
100079 #ifdef SQLITE_ENABLE_STAT2
100080 static int whereRangeRegion(
100081 Parse *pParse, /* Database connection */
100082 Index *pIdx, /* Index to consider domain of */
100083 sqlite3_value *pVal, /* Value to consider */
100084 int roundUp, /* Return largest valid region if true */
100085 int *piRegion /* OUT: Region of domain in which value lies */
100087 assert( roundUp==0 || roundUp==1 );
100088 if( ALWAYS(pVal) ){
100089 IndexSample *aSample = pIdx->aSample;
100090 int i = 0;
100091 int eType = sqlite3_value_type(pVal);
100093 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
100094 double r = sqlite3_value_double(pVal);
100095 for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
100096 if( aSample[i].eType==SQLITE_NULL ) continue;
100097 if( aSample[i].eType>=SQLITE_TEXT ) break;
100098 if( roundUp ){
100099 if( aSample[i].u.r>r ) break;
100100 }else{
100101 if( aSample[i].u.r>=r ) break;
100104 }else if( eType==SQLITE_NULL ){
100105 i = 0;
100106 if( roundUp ){
100107 while( i<SQLITE_INDEX_SAMPLES && aSample[i].eType==SQLITE_NULL ) i++;
100109 }else{
100110 sqlite3 *db = pParse->db;
100111 CollSeq *pColl;
100112 const u8 *z;
100113 int n;
100115 /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
100116 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
100118 if( eType==SQLITE_BLOB ){
100119 z = (const u8 *)sqlite3_value_blob(pVal);
100120 pColl = db->pDfltColl;
100121 assert( pColl->enc==SQLITE_UTF8 );
100122 }else{
100123 pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
100124 if( pColl==0 ){
100125 sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
100126 *pIdx->azColl);
100127 return SQLITE_ERROR;
100129 z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
100130 if( !z ){
100131 return SQLITE_NOMEM;
100133 assert( z && pColl && pColl->xCmp );
100135 n = sqlite3ValueBytes(pVal, pColl->enc);
100137 for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
100138 int c;
100139 int eSampletype = aSample[i].eType;
100140 if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
100141 if( (eSampletype!=eType) ) break;
100142 #ifndef SQLITE_OMIT_UTF16
100143 if( pColl->enc!=SQLITE_UTF8 ){
100144 int nSample;
100145 char *zSample = sqlite3Utf8to16(
100146 db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
100148 if( !zSample ){
100149 assert( db->mallocFailed );
100150 return SQLITE_NOMEM;
100152 c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
100153 sqlite3DbFree(db, zSample);
100154 }else
100155 #endif
100157 c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
100159 if( c-roundUp>=0 ) break;
100163 assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
100164 *piRegion = i;
100166 return SQLITE_OK;
100168 #endif /* #ifdef SQLITE_ENABLE_STAT2 */
100171 ** If expression pExpr represents a literal value, set *pp to point to
100172 ** an sqlite3_value structure containing the same value, with affinity
100173 ** aff applied to it, before returning. It is the responsibility of the
100174 ** caller to eventually release this structure by passing it to
100175 ** sqlite3ValueFree().
100177 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
100178 ** is an SQL variable that currently has a non-NULL value bound to it,
100179 ** create an sqlite3_value structure containing this value, again with
100180 ** affinity aff applied to it, instead.
100182 ** If neither of the above apply, set *pp to NULL.
100184 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
100186 #ifdef SQLITE_ENABLE_STAT2
100187 static int valueFromExpr(
100188 Parse *pParse,
100189 Expr *pExpr,
100190 u8 aff,
100191 sqlite3_value **pp
100193 if( pExpr->op==TK_VARIABLE
100194 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
100196 int iVar = pExpr->iColumn;
100197 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
100198 *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
100199 return SQLITE_OK;
100201 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
100203 #endif
100206 ** This function is used to estimate the number of rows that will be visited
100207 ** by scanning an index for a range of values. The range may have an upper
100208 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
100209 ** and lower bounds are represented by pLower and pUpper respectively. For
100210 ** example, assuming that index p is on t1(a):
100212 ** ... FROM t1 WHERE a > ? AND a < ? ...
100213 ** |_____| |_____|
100214 ** | |
100215 ** pLower pUpper
100217 ** If either of the upper or lower bound is not present, then NULL is passed in
100218 ** place of the corresponding WhereTerm.
100220 ** The nEq parameter is passed the index of the index column subject to the
100221 ** range constraint. Or, equivalently, the number of equality constraints
100222 ** optimized by the proposed index scan. For example, assuming index p is
100223 ** on t1(a, b), and the SQL query is:
100225 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
100227 ** then nEq should be passed the value 1 (as the range restricted column,
100228 ** b, is the second left-most column of the index). Or, if the query is:
100230 ** ... FROM t1 WHERE a > ? AND a < ? ...
100232 ** then nEq should be passed 0.
100234 ** The returned value is an integer between 1 and 100, inclusive. A return
100235 ** value of 1 indicates that the proposed range scan is expected to visit
100236 ** approximately 1/100th (1%) of the rows selected by the nEq equality
100237 ** constraints (if any). A return value of 100 indicates that it is expected
100238 ** that the range scan will visit every row (100%) selected by the equality
100239 ** constraints.
100241 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
100242 ** reduces the search space by 3/4ths. Hence a single constraint (x>?)
100243 ** results in a return of 25 and a range constraint (x>? AND x<?) results
100244 ** in a return of 6.
100246 static int whereRangeScanEst(
100247 Parse *pParse, /* Parsing & code generating context */
100248 Index *p, /* The index containing the range-compared column; "x" */
100249 int nEq, /* index into p->aCol[] of the range-compared column */
100250 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
100251 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
100252 int *piEst /* OUT: Return value */
100254 int rc = SQLITE_OK;
100256 #ifdef SQLITE_ENABLE_STAT2
100258 if( nEq==0 && p->aSample ){
100259 sqlite3_value *pLowerVal = 0;
100260 sqlite3_value *pUpperVal = 0;
100261 int iEst;
100262 int iLower = 0;
100263 int iUpper = SQLITE_INDEX_SAMPLES;
100264 int roundUpUpper = 0;
100265 int roundUpLower = 0;
100266 u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100268 if( pLower ){
100269 Expr *pExpr = pLower->pExpr->pRight;
100270 rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
100271 assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
100272 roundUpLower = (pLower->eOperator==WO_GT) ?1:0;
100274 if( rc==SQLITE_OK && pUpper ){
100275 Expr *pExpr = pUpper->pExpr->pRight;
100276 rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
100277 assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
100278 roundUpUpper = (pUpper->eOperator==WO_LE) ?1:0;
100281 if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
100282 sqlite3ValueFree(pLowerVal);
100283 sqlite3ValueFree(pUpperVal);
100284 goto range_est_fallback;
100285 }else if( pLowerVal==0 ){
100286 rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100287 if( pLower ) iLower = iUpper/2;
100288 }else if( pUpperVal==0 ){
100289 rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100290 if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
100291 }else{
100292 rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100293 if( rc==SQLITE_OK ){
100294 rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100297 WHERETRACE(("range scan regions: %d..%d\n", iLower, iUpper));
100299 iEst = iUpper - iLower;
100300 testcase( iEst==SQLITE_INDEX_SAMPLES );
100301 assert( iEst<=SQLITE_INDEX_SAMPLES );
100302 if( iEst<1 ){
100303 *piEst = 50/SQLITE_INDEX_SAMPLES;
100304 }else{
100305 *piEst = (iEst*100)/SQLITE_INDEX_SAMPLES;
100307 sqlite3ValueFree(pLowerVal);
100308 sqlite3ValueFree(pUpperVal);
100309 return rc;
100311 range_est_fallback:
100312 #else
100313 UNUSED_PARAMETER(pParse);
100314 UNUSED_PARAMETER(p);
100315 UNUSED_PARAMETER(nEq);
100316 #endif
100317 assert( pLower || pUpper );
100318 *piEst = 100;
100319 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *piEst /= 4;
100320 if( pUpper ) *piEst /= 4;
100321 return rc;
100324 #ifdef SQLITE_ENABLE_STAT2
100326 ** Estimate the number of rows that will be returned based on
100327 ** an equality constraint x=VALUE and where that VALUE occurs in
100328 ** the histogram data. This only works when x is the left-most
100329 ** column of an index and sqlite_stat2 histogram data is available
100330 ** for that index. When pExpr==NULL that means the constraint is
100331 ** "x IS NULL" instead of "x=VALUE".
100333 ** Write the estimated row count into *pnRow and return SQLITE_OK.
100334 ** If unable to make an estimate, leave *pnRow unchanged and return
100335 ** non-zero.
100337 ** This routine can fail if it is unable to load a collating sequence
100338 ** required for string comparison, or if unable to allocate memory
100339 ** for a UTF conversion required for comparison. The error is stored
100340 ** in the pParse structure.
100342 static int whereEqualScanEst(
100343 Parse *pParse, /* Parsing & code generating context */
100344 Index *p, /* The index whose left-most column is pTerm */
100345 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
100346 double *pnRow /* Write the revised row estimate here */
100348 sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
100349 int iLower, iUpper; /* Range of histogram regions containing pRhs */
100350 u8 aff; /* Column affinity */
100351 int rc; /* Subfunction return code */
100352 double nRowEst; /* New estimate of the number of rows */
100354 assert( p->aSample!=0 );
100355 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100356 if( pExpr ){
100357 rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
100358 if( rc ) goto whereEqualScanEst_cancel;
100359 }else{
100360 pRhs = sqlite3ValueNew(pParse->db);
100362 if( pRhs==0 ) return SQLITE_NOTFOUND;
100363 rc = whereRangeRegion(pParse, p, pRhs, 0, &iLower);
100364 if( rc ) goto whereEqualScanEst_cancel;
100365 rc = whereRangeRegion(pParse, p, pRhs, 1, &iUpper);
100366 if( rc ) goto whereEqualScanEst_cancel;
100367 WHERETRACE(("equality scan regions: %d..%d\n", iLower, iUpper));
100368 if( iLower>=iUpper ){
100369 nRowEst = p->aiRowEst[0]/(SQLITE_INDEX_SAMPLES*2);
100370 if( nRowEst<*pnRow ) *pnRow = nRowEst;
100371 }else{
100372 nRowEst = (iUpper-iLower)*p->aiRowEst[0]/SQLITE_INDEX_SAMPLES;
100373 *pnRow = nRowEst;
100376 whereEqualScanEst_cancel:
100377 sqlite3ValueFree(pRhs);
100378 return rc;
100380 #endif /* defined(SQLITE_ENABLE_STAT2) */
100382 #ifdef SQLITE_ENABLE_STAT2
100384 ** Estimate the number of rows that will be returned based on
100385 ** an IN constraint where the right-hand side of the IN operator
100386 ** is a list of values. Example:
100388 ** WHERE x IN (1,2,3,4)
100390 ** Write the estimated row count into *pnRow and return SQLITE_OK.
100391 ** If unable to make an estimate, leave *pnRow unchanged and return
100392 ** non-zero.
100394 ** This routine can fail if it is unable to load a collating sequence
100395 ** required for string comparison, or if unable to allocate memory
100396 ** for a UTF conversion required for comparison. The error is stored
100397 ** in the pParse structure.
100399 static int whereInScanEst(
100400 Parse *pParse, /* Parsing & code generating context */
100401 Index *p, /* The index whose left-most column is pTerm */
100402 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
100403 double *pnRow /* Write the revised row estimate here */
100405 sqlite3_value *pVal = 0; /* One value from list */
100406 int iLower, iUpper; /* Range of histogram regions containing pRhs */
100407 u8 aff; /* Column affinity */
100408 int rc = SQLITE_OK; /* Subfunction return code */
100409 double nRowEst; /* New estimate of the number of rows */
100410 int nSpan = 0; /* Number of histogram regions spanned */
100411 int nSingle = 0; /* Histogram regions hit by a single value */
100412 int nNotFound = 0; /* Count of values that are not constants */
100413 int i; /* Loop counter */
100414 u8 aSpan[SQLITE_INDEX_SAMPLES+1]; /* Histogram regions that are spanned */
100415 u8 aSingle[SQLITE_INDEX_SAMPLES+1]; /* Histogram regions hit once */
100417 assert( p->aSample!=0 );
100418 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100419 memset(aSpan, 0, sizeof(aSpan));
100420 memset(aSingle, 0, sizeof(aSingle));
100421 for(i=0; i<pList->nExpr; i++){
100422 sqlite3ValueFree(pVal);
100423 rc = valueFromExpr(pParse, pList->a[i].pExpr, aff, &pVal);
100424 if( rc ) break;
100425 if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
100426 nNotFound++;
100427 continue;
100429 rc = whereRangeRegion(pParse, p, pVal, 0, &iLower);
100430 if( rc ) break;
100431 rc = whereRangeRegion(pParse, p, pVal, 1, &iUpper);
100432 if( rc ) break;
100433 if( iLower>=iUpper ){
100434 aSingle[iLower] = 1;
100435 }else{
100436 assert( iLower>=0 && iUpper<=SQLITE_INDEX_SAMPLES );
100437 while( iLower<iUpper ) aSpan[iLower++] = 1;
100440 if( rc==SQLITE_OK ){
100441 for(i=nSpan=0; i<=SQLITE_INDEX_SAMPLES; i++){
100442 if( aSpan[i] ){
100443 nSpan++;
100444 }else if( aSingle[i] ){
100445 nSingle++;
100448 nRowEst = (nSpan*2+nSingle)*p->aiRowEst[0]/(2*SQLITE_INDEX_SAMPLES)
100449 + nNotFound*p->aiRowEst[1];
100450 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
100451 *pnRow = nRowEst;
100452 WHERETRACE(("IN row estimate: nSpan=%d, nSingle=%d, nNotFound=%d, est=%g\n",
100453 nSpan, nSingle, nNotFound, nRowEst));
100455 sqlite3ValueFree(pVal);
100456 return rc;
100458 #endif /* defined(SQLITE_ENABLE_STAT2) */
100462 ** Find the best query plan for accessing a particular table. Write the
100463 ** best query plan and its cost into the WhereCost object supplied as the
100464 ** last parameter.
100466 ** The lowest cost plan wins. The cost is an estimate of the amount of
100467 ** CPU and disk I/O needed to process the requested result.
100468 ** Factors that influence cost include:
100470 ** * The estimated number of rows that will be retrieved. (The
100471 ** fewer the better.)
100473 ** * Whether or not sorting must occur.
100475 ** * Whether or not there must be separate lookups in the
100476 ** index and in the main table.
100478 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
100479 ** the SQL statement, then this function only considers plans using the
100480 ** named index. If no such plan is found, then the returned cost is
100481 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
100482 ** then the cost is calculated in the usual way.
100484 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
100485 ** in the SELECT statement, then no indexes are considered. However, the
100486 ** selected plan may still take advantage of the built-in rowid primary key
100487 ** index.
100489 static void bestBtreeIndex(
100490 Parse *pParse, /* The parsing context */
100491 WhereClause *pWC, /* The WHERE clause */
100492 struct SrcList_item *pSrc, /* The FROM clause term to search */
100493 Bitmask notReady, /* Mask of cursors not available for indexing */
100494 Bitmask notValid, /* Cursors not available for any purpose */
100495 ExprList *pOrderBy, /* The ORDER BY clause */
100496 WhereCost *pCost /* Lowest cost query plan */
100498 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
100499 Index *pProbe; /* An index we are evaluating */
100500 Index *pIdx; /* Copy of pProbe, or zero for IPK index */
100501 int eqTermMask; /* Current mask of valid equality operators */
100502 int idxEqTermMask; /* Index mask of valid equality operators */
100503 Index sPk; /* A fake index object for the primary key */
100504 unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
100505 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
100506 int wsFlagMask; /* Allowed flags in pCost->plan.wsFlag */
100508 /* Initialize the cost to a worst-case value */
100509 memset(pCost, 0, sizeof(*pCost));
100510 pCost->rCost = SQLITE_BIG_DBL;
100512 /* If the pSrc table is the right table of a LEFT JOIN then we may not
100513 ** use an index to satisfy IS NULL constraints on that table. This is
100514 ** because columns might end up being NULL if the table does not match -
100515 ** a circumstance which the index cannot help us discover. Ticket #2177.
100517 if( pSrc->jointype & JT_LEFT ){
100518 idxEqTermMask = WO_EQ|WO_IN;
100519 }else{
100520 idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
100523 if( pSrc->pIndex ){
100524 /* An INDEXED BY clause specifies a particular index to use */
100525 pIdx = pProbe = pSrc->pIndex;
100526 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
100527 eqTermMask = idxEqTermMask;
100528 }else{
100529 /* There is no INDEXED BY clause. Create a fake Index object in local
100530 ** variable sPk to represent the rowid primary key index. Make this
100531 ** fake index the first in a chain of Index objects with all of the real
100532 ** indices to follow */
100533 Index *pFirst; /* First of real indices on the table */
100534 memset(&sPk, 0, sizeof(Index));
100535 sPk.nColumn = 1;
100536 sPk.aiColumn = &aiColumnPk;
100537 sPk.aiRowEst = aiRowEstPk;
100538 sPk.onError = OE_Replace;
100539 sPk.pTable = pSrc->pTab;
100540 aiRowEstPk[0] = pSrc->pTab->nRowEst;
100541 aiRowEstPk[1] = 1;
100542 pFirst = pSrc->pTab->pIndex;
100543 if( pSrc->notIndexed==0 ){
100544 /* The real indices of the table are only considered if the
100545 ** NOT INDEXED qualifier is omitted from the FROM clause */
100546 sPk.pNext = pFirst;
100548 pProbe = &sPk;
100549 wsFlagMask = ~(
100550 WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
100552 eqTermMask = WO_EQ|WO_IN;
100553 pIdx = 0;
100556 /* Loop over all indices looking for the best one to use
100558 for(; pProbe; pIdx=pProbe=pProbe->pNext){
100559 const unsigned int * const aiRowEst = pProbe->aiRowEst;
100560 double cost; /* Cost of using pProbe */
100561 double nRow; /* Estimated number of rows in result set */
100562 double log10N; /* base-10 logarithm of nRow (inexact) */
100563 int rev; /* True to scan in reverse order */
100564 int wsFlags = 0;
100565 Bitmask used = 0;
100567 /* The following variables are populated based on the properties of
100568 ** index being evaluated. They are then used to determine the expected
100569 ** cost and number of rows returned.
100571 ** nEq:
100572 ** Number of equality terms that can be implemented using the index.
100573 ** In other words, the number of initial fields in the index that
100574 ** are used in == or IN or NOT NULL constraints of the WHERE clause.
100576 ** nInMul:
100577 ** The "in-multiplier". This is an estimate of how many seek operations
100578 ** SQLite must perform on the index in question. For example, if the
100579 ** WHERE clause is:
100581 ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
100583 ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is
100584 ** set to 9. Given the same schema and either of the following WHERE
100585 ** clauses:
100587 ** WHERE a = 1
100588 ** WHERE a >= 2
100590 ** nInMul is set to 1.
100592 ** If there exists a WHERE term of the form "x IN (SELECT ...)", then
100593 ** the sub-select is assumed to return 25 rows for the purposes of
100594 ** determining nInMul.
100596 ** bInEst:
100597 ** Set to true if there was at least one "x IN (SELECT ...)" term used
100598 ** in determining the value of nInMul. Note that the RHS of the
100599 ** IN operator must be a SELECT, not a value list, for this variable
100600 ** to be true.
100602 ** estBound:
100603 ** An estimate on the amount of the table that must be searched. A
100604 ** value of 100 means the entire table is searched. Range constraints
100605 ** might reduce this to a value less than 100 to indicate that only
100606 ** a fraction of the table needs searching. In the absence of
100607 ** sqlite_stat2 ANALYZE data, a single inequality reduces the search
100608 ** space to 1/4rd its original size. So an x>? constraint reduces
100609 ** estBound to 25. Two constraints (x>? AND x<?) reduce estBound to 6.
100611 ** bSort:
100612 ** Boolean. True if there is an ORDER BY clause that will require an
100613 ** external sort (i.e. scanning the index being evaluated will not
100614 ** correctly order records).
100616 ** bLookup:
100617 ** Boolean. True if a table lookup is required for each index entry
100618 ** visited. In other words, true if this is not a covering index.
100619 ** This is always false for the rowid primary key index of a table.
100620 ** For other indexes, it is true unless all the columns of the table
100621 ** used by the SELECT statement are present in the index (such an
100622 ** index is sometimes described as a covering index).
100623 ** For example, given the index on (a, b), the second of the following
100624 ** two queries requires table b-tree lookups in order to find the value
100625 ** of column c, but the first does not because columns a and b are
100626 ** both available in the index.
100628 ** SELECT a, b FROM tbl WHERE a = 1;
100629 ** SELECT a, b, c FROM tbl WHERE a = 1;
100631 int nEq; /* Number of == or IN terms matching index */
100632 int bInEst = 0; /* True if "x IN (SELECT...)" seen */
100633 int nInMul = 1; /* Number of distinct equalities to lookup */
100634 int estBound = 100; /* Estimated reduction in search space */
100635 int nBound = 0; /* Number of range constraints seen */
100636 int bSort = 0; /* True if external sort required */
100637 int bLookup = 0; /* True if not a covering index */
100638 WhereTerm *pTerm; /* A single term of the WHERE clause */
100639 #ifdef SQLITE_ENABLE_STAT2
100640 WhereTerm *pFirstTerm = 0; /* First term matching the index */
100641 #endif
100643 /* Determine the values of nEq and nInMul */
100644 for(nEq=0; nEq<pProbe->nColumn; nEq++){
100645 int j = pProbe->aiColumn[nEq];
100646 pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
100647 if( pTerm==0 ) break;
100648 wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
100649 if( pTerm->eOperator & WO_IN ){
100650 Expr *pExpr = pTerm->pExpr;
100651 wsFlags |= WHERE_COLUMN_IN;
100652 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
100653 /* "x IN (SELECT ...)": Assume the SELECT returns 25 rows */
100654 nInMul *= 25;
100655 bInEst = 1;
100656 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
100657 /* "x IN (value, value, ...)" */
100658 nInMul *= pExpr->x.pList->nExpr;
100660 }else if( pTerm->eOperator & WO_ISNULL ){
100661 wsFlags |= WHERE_COLUMN_NULL;
100663 #ifdef SQLITE_ENABLE_STAT2
100664 if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
100665 #endif
100666 used |= pTerm->prereqRight;
100669 /* Determine the value of estBound. */
100670 if( nEq<pProbe->nColumn && pProbe->bUnordered==0 ){
100671 int j = pProbe->aiColumn[nEq];
100672 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
100673 WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
100674 WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
100675 whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
100676 if( pTop ){
100677 nBound = 1;
100678 wsFlags |= WHERE_TOP_LIMIT;
100679 used |= pTop->prereqRight;
100681 if( pBtm ){
100682 nBound++;
100683 wsFlags |= WHERE_BTM_LIMIT;
100684 used |= pBtm->prereqRight;
100686 wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
100688 }else if( pProbe->onError!=OE_None ){
100689 testcase( wsFlags & WHERE_COLUMN_IN );
100690 testcase( wsFlags & WHERE_COLUMN_NULL );
100691 if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
100692 wsFlags |= WHERE_UNIQUE;
100696 /* If there is an ORDER BY clause and the index being considered will
100697 ** naturally scan rows in the required order, set the appropriate flags
100698 ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
100699 ** will scan rows in a different order, set the bSort variable. */
100700 if( pOrderBy ){
100701 if( (wsFlags & WHERE_COLUMN_IN)==0
100702 && pProbe->bUnordered==0
100703 && isSortingIndex(pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy,
100704 nEq, wsFlags, &rev)
100706 wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
100707 wsFlags |= (rev ? WHERE_REVERSE : 0);
100708 }else{
100709 bSort = 1;
100713 /* If currently calculating the cost of using an index (not the IPK
100714 ** index), determine if all required column data may be obtained without
100715 ** using the main table (i.e. if the index is a covering
100716 ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
100717 ** wsFlags. Otherwise, set the bLookup variable to true. */
100718 if( pIdx && wsFlags ){
100719 Bitmask m = pSrc->colUsed;
100720 int j;
100721 for(j=0; j<pIdx->nColumn; j++){
100722 int x = pIdx->aiColumn[j];
100723 if( x<BMS-1 ){
100724 m &= ~(((Bitmask)1)<<x);
100727 if( m==0 ){
100728 wsFlags |= WHERE_IDX_ONLY;
100729 }else{
100730 bLookup = 1;
100735 ** Estimate the number of rows of output. For an "x IN (SELECT...)"
100736 ** constraint, do not let the estimate exceed half the rows in the table.
100738 nRow = (double)(aiRowEst[nEq] * nInMul);
100739 if( bInEst && nRow*2>aiRowEst[0] ){
100740 nRow = aiRowEst[0]/2;
100741 nInMul = (int)(nRow / aiRowEst[nEq]);
100744 #ifdef SQLITE_ENABLE_STAT2
100745 /* If the constraint is of the form x=VALUE and histogram
100746 ** data is available for column x, then it might be possible
100747 ** to get a better estimate on the number of rows based on
100748 ** VALUE and how common that value is according to the histogram.
100750 if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 ){
100751 if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
100752 testcase( pFirstTerm->eOperator==WO_EQ );
100753 testcase( pFirstTerm->eOperator==WO_ISNULL );
100754 whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
100755 }else if( pFirstTerm->eOperator==WO_IN && bInEst==0 ){
100756 whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
100759 #endif /* SQLITE_ENABLE_STAT2 */
100761 /* Adjust the number of output rows and downward to reflect rows
100762 ** that are excluded by range constraints.
100764 nRow = (nRow * (double)estBound) / (double)100;
100765 if( nRow<1 ) nRow = 1;
100767 /* Experiments run on real SQLite databases show that the time needed
100768 ** to do a binary search to locate a row in a table or index is roughly
100769 ** log10(N) times the time to move from one row to the next row within
100770 ** a table or index. The actual times can vary, with the size of
100771 ** records being an important factor. Both moves and searches are
100772 ** slower with larger records, presumably because fewer records fit
100773 ** on one page and hence more pages have to be fetched.
100775 ** The ANALYZE command and the sqlite_stat1 and sqlite_stat2 tables do
100776 ** not give us data on the relative sizes of table and index records.
100777 ** So this computation assumes table records are about twice as big
100778 ** as index records
100780 if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
100781 /* The cost of a full table scan is a number of move operations equal
100782 ** to the number of rows in the table.
100784 ** We add an additional 4x penalty to full table scans. This causes
100785 ** the cost function to err on the side of choosing an index over
100786 ** choosing a full scan. This 4x full-scan penalty is an arguable
100787 ** decision and one which we expect to revisit in the future. But
100788 ** it seems to be working well enough at the moment.
100790 cost = aiRowEst[0]*4;
100791 }else{
100792 log10N = estLog(aiRowEst[0]);
100793 cost = nRow;
100794 if( pIdx ){
100795 if( bLookup ){
100796 /* For an index lookup followed by a table lookup:
100797 ** nInMul index searches to find the start of each index range
100798 ** + nRow steps through the index
100799 ** + nRow table searches to lookup the table entry using the rowid
100801 cost += (nInMul + nRow)*log10N;
100802 }else{
100803 /* For a covering index:
100804 ** nInMul index searches to find the initial entry
100805 ** + nRow steps through the index
100807 cost += nInMul*log10N;
100809 }else{
100810 /* For a rowid primary key lookup:
100811 ** nInMult table searches to find the initial entry for each range
100812 ** + nRow steps through the table
100814 cost += nInMul*log10N;
100818 /* Add in the estimated cost of sorting the result. Actual experimental
100819 ** measurements of sorting performance in SQLite show that sorting time
100820 ** adds C*N*log10(N) to the cost, where N is the number of rows to be
100821 ** sorted and C is a factor between 1.95 and 4.3. We will split the
100822 ** difference and select C of 3.0.
100824 if( bSort ){
100825 cost += nRow*estLog(nRow)*3;
100828 /**** Cost of using this index has now been computed ****/
100830 /* If there are additional constraints on this table that cannot
100831 ** be used with the current index, but which might lower the number
100832 ** of output rows, adjust the nRow value accordingly. This only
100833 ** matters if the current index is the least costly, so do not bother
100834 ** with this step if we already know this index will not be chosen.
100835 ** Also, never reduce the output row count below 2 using this step.
100837 ** It is critical that the notValid mask be used here instead of
100838 ** the notReady mask. When computing an "optimal" index, the notReady
100839 ** mask will only have one bit set - the bit for the current table.
100840 ** The notValid mask, on the other hand, always has all bits set for
100841 ** tables that are not in outer loops. If notReady is used here instead
100842 ** of notValid, then a optimal index that depends on inner joins loops
100843 ** might be selected even when there exists an optimal index that has
100844 ** no such dependency.
100846 if( nRow>2 && cost<=pCost->rCost ){
100847 int k; /* Loop counter */
100848 int nSkipEq = nEq; /* Number of == constraints to skip */
100849 int nSkipRange = nBound; /* Number of < constraints to skip */
100850 Bitmask thisTab; /* Bitmap for pSrc */
100852 thisTab = getMask(pWC->pMaskSet, iCur);
100853 for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
100854 if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
100855 if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
100856 if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
100857 if( nSkipEq ){
100858 /* Ignore the first nEq equality matches since the index
100859 ** has already accounted for these */
100860 nSkipEq--;
100861 }else{
100862 /* Assume each additional equality match reduces the result
100863 ** set size by a factor of 10 */
100864 nRow /= 10;
100866 }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
100867 if( nSkipRange ){
100868 /* Ignore the first nSkipRange range constraints since the index
100869 ** has already accounted for these */
100870 nSkipRange--;
100871 }else{
100872 /* Assume each additional range constraint reduces the result
100873 ** set size by a factor of 3. Indexed range constraints reduce
100874 ** the search space by a larger factor: 4. We make indexed range
100875 ** more selective intentionally because of the subjective
100876 ** observation that indexed range constraints really are more
100877 ** selective in practice, on average. */
100878 nRow /= 3;
100880 }else if( pTerm->eOperator!=WO_NOOP ){
100881 /* Any other expression lowers the output row count by half */
100882 nRow /= 2;
100885 if( nRow<2 ) nRow = 2;
100889 WHERETRACE((
100890 "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
100891 " notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
100892 pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
100893 nEq, nInMul, estBound, bSort, bLookup, wsFlags,
100894 notReady, log10N, nRow, cost, used
100897 /* If this index is the best we have seen so far, then record this
100898 ** index and its cost in the pCost structure.
100900 if( (!pIdx || wsFlags)
100901 && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
100903 pCost->rCost = cost;
100904 pCost->used = used;
100905 pCost->plan.nRow = nRow;
100906 pCost->plan.wsFlags = (wsFlags&wsFlagMask);
100907 pCost->plan.nEq = nEq;
100908 pCost->plan.u.pIdx = pIdx;
100911 /* If there was an INDEXED BY clause, then only that one index is
100912 ** considered. */
100913 if( pSrc->pIndex ) break;
100915 /* Reset masks for the next index in the loop */
100916 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
100917 eqTermMask = idxEqTermMask;
100920 /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
100921 ** is set, then reverse the order that the index will be scanned
100922 ** in. This is used for application testing, to help find cases
100923 ** where application behaviour depends on the (undefined) order that
100924 ** SQLite outputs rows in in the absence of an ORDER BY clause. */
100925 if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
100926 pCost->plan.wsFlags |= WHERE_REVERSE;
100929 assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
100930 assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
100931 assert( pSrc->pIndex==0
100932 || pCost->plan.u.pIdx==0
100933 || pCost->plan.u.pIdx==pSrc->pIndex
100936 WHERETRACE(("best index is: %s\n",
100937 ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
100938 pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
100941 bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100942 bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
100943 pCost->plan.wsFlags |= eqTermMask;
100947 ** Find the query plan for accessing table pSrc->pTab. Write the
100948 ** best query plan and its cost into the WhereCost object supplied
100949 ** as the last parameter. This function may calculate the cost of
100950 ** both real and virtual table scans.
100952 static void bestIndex(
100953 Parse *pParse, /* The parsing context */
100954 WhereClause *pWC, /* The WHERE clause */
100955 struct SrcList_item *pSrc, /* The FROM clause term to search */
100956 Bitmask notReady, /* Mask of cursors not available for indexing */
100957 Bitmask notValid, /* Cursors not available for any purpose */
100958 ExprList *pOrderBy, /* The ORDER BY clause */
100959 WhereCost *pCost /* Lowest cost query plan */
100961 #ifndef SQLITE_OMIT_VIRTUALTABLE
100962 if( IsVirtual(pSrc->pTab) ){
100963 sqlite3_index_info *p = 0;
100964 bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
100965 if( p->needToFreeIdxStr ){
100966 sqlite3_free(p->idxStr);
100968 sqlite3DbFree(pParse->db, p);
100969 }else
100970 #endif
100972 bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100977 ** Disable a term in the WHERE clause. Except, do not disable the term
100978 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
100979 ** or USING clause of that join.
100981 ** Consider the term t2.z='ok' in the following queries:
100983 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
100984 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
100985 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
100987 ** The t2.z='ok' is disabled in the in (2) because it originates
100988 ** in the ON clause. The term is disabled in (3) because it is not part
100989 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
100991 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
100992 ** completely satisfied by indices.
100994 ** Disabling a term causes that term to not be tested in the inner loop
100995 ** of the join. Disabling is an optimization. When terms are satisfied
100996 ** by indices, we disable them to prevent redundant tests in the inner
100997 ** loop. We would get the correct results if nothing were ever disabled,
100998 ** but joins might run a little slower. The trick is to disable as much
100999 ** as we can without disabling too much. If we disabled in (1), we'd get
101000 ** the wrong answer. See ticket #813.
101002 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
101003 if( pTerm
101004 && (pTerm->wtFlags & TERM_CODED)==0
101005 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
101007 pTerm->wtFlags |= TERM_CODED;
101008 if( pTerm->iParent>=0 ){
101009 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
101010 if( (--pOther->nChild)==0 ){
101011 disableTerm(pLevel, pOther);
101018 ** Code an OP_Affinity opcode to apply the column affinity string zAff
101019 ** to the n registers starting at base.
101021 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
101022 ** beginning and end of zAff are ignored. If all entries in zAff are
101023 ** SQLITE_AFF_NONE, then no code gets generated.
101025 ** This routine makes its own copy of zAff so that the caller is free
101026 ** to modify zAff after this routine returns.
101028 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
101029 Vdbe *v = pParse->pVdbe;
101030 if( zAff==0 ){
101031 assert( pParse->db->mallocFailed );
101032 return;
101034 assert( v!=0 );
101036 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
101037 ** and end of the affinity string.
101039 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
101041 base++;
101042 zAff++;
101044 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
101048 /* Code the OP_Affinity opcode if there is anything left to do. */
101049 if( n>0 ){
101050 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
101051 sqlite3VdbeChangeP4(v, -1, zAff, n);
101052 sqlite3ExprCacheAffinityChange(pParse, base, n);
101058 ** Generate code for a single equality term of the WHERE clause. An equality
101059 ** term can be either X=expr or X IN (...). pTerm is the term to be
101060 ** coded.
101062 ** The current value for the constraint is left in register iReg.
101064 ** For a constraint of the form X=expr, the expression is evaluated and its
101065 ** result is left on the stack. For constraints of the form X IN (...)
101066 ** this routine sets up a loop that will iterate over all values of X.
101068 static int codeEqualityTerm(
101069 Parse *pParse, /* The parsing context */
101070 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
101071 WhereLevel *pLevel, /* When level of the FROM clause we are working on */
101072 int iTarget /* Attempt to leave results in this register */
101074 Expr *pX = pTerm->pExpr;
101075 Vdbe *v = pParse->pVdbe;
101076 int iReg; /* Register holding results */
101078 assert( iTarget>0 );
101079 if( pX->op==TK_EQ ){
101080 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
101081 }else if( pX->op==TK_ISNULL ){
101082 iReg = iTarget;
101083 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
101084 #ifndef SQLITE_OMIT_SUBQUERY
101085 }else{
101086 int eType;
101087 int iTab;
101088 struct InLoop *pIn;
101090 assert( pX->op==TK_IN );
101091 iReg = iTarget;
101092 eType = sqlite3FindInIndex(pParse, pX, 0);
101093 iTab = pX->iTable;
101094 sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
101095 assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
101096 if( pLevel->u.in.nIn==0 ){
101097 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
101099 pLevel->u.in.nIn++;
101100 pLevel->u.in.aInLoop =
101101 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
101102 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
101103 pIn = pLevel->u.in.aInLoop;
101104 if( pIn ){
101105 pIn += pLevel->u.in.nIn - 1;
101106 pIn->iCur = iTab;
101107 if( eType==IN_INDEX_ROWID ){
101108 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
101109 }else{
101110 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
101112 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
101113 }else{
101114 pLevel->u.in.nIn = 0;
101116 #endif
101118 disableTerm(pLevel, pTerm);
101119 return iReg;
101123 ** Generate code that will evaluate all == and IN constraints for an
101124 ** index.
101126 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
101127 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
101128 ** The index has as many as three equality constraints, but in this
101129 ** example, the third "c" value is an inequality. So only two
101130 ** constraints are coded. This routine will generate code to evaluate
101131 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
101132 ** in consecutive registers and the index of the first register is returned.
101134 ** In the example above nEq==2. But this subroutine works for any value
101135 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
101136 ** The only thing it does is allocate the pLevel->iMem memory cell and
101137 ** compute the affinity string.
101139 ** This routine always allocates at least one memory cell and returns
101140 ** the index of that memory cell. The code that
101141 ** calls this routine will use that memory cell to store the termination
101142 ** key value of the loop. If one or more IN operators appear, then
101143 ** this routine allocates an additional nEq memory cells for internal
101144 ** use.
101146 ** Before returning, *pzAff is set to point to a buffer containing a
101147 ** copy of the column affinity string of the index allocated using
101148 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
101149 ** with equality constraints that use NONE affinity are set to
101150 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
101152 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
101153 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
101155 ** In the example above, the index on t1(a) has TEXT affinity. But since
101156 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
101157 ** no conversion should be attempted before using a t2.b value as part of
101158 ** a key to search the index. Hence the first byte in the returned affinity
101159 ** string in this example would be set to SQLITE_AFF_NONE.
101161 static int codeAllEqualityTerms(
101162 Parse *pParse, /* Parsing context */
101163 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
101164 WhereClause *pWC, /* The WHERE clause */
101165 Bitmask notReady, /* Which parts of FROM have not yet been coded */
101166 int nExtraReg, /* Number of extra registers to allocate */
101167 char **pzAff /* OUT: Set to point to affinity string */
101169 int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
101170 Vdbe *v = pParse->pVdbe; /* The vm under construction */
101171 Index *pIdx; /* The index being used for this loop */
101172 int iCur = pLevel->iTabCur; /* The cursor of the table */
101173 WhereTerm *pTerm; /* A single constraint term */
101174 int j; /* Loop counter */
101175 int regBase; /* Base register */
101176 int nReg; /* Number of registers to allocate */
101177 char *zAff; /* Affinity string to return */
101179 /* This module is only called on query plans that use an index. */
101180 assert( pLevel->plan.wsFlags & WHERE_INDEXED );
101181 pIdx = pLevel->plan.u.pIdx;
101183 /* Figure out how many memory cells we will need then allocate them.
101185 regBase = pParse->nMem + 1;
101186 nReg = pLevel->plan.nEq + nExtraReg;
101187 pParse->nMem += nReg;
101189 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
101190 if( !zAff ){
101191 pParse->db->mallocFailed = 1;
101194 /* Evaluate the equality constraints
101196 assert( pIdx->nColumn>=nEq );
101197 for(j=0; j<nEq; j++){
101198 int r1;
101199 int k = pIdx->aiColumn[j];
101200 pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
101201 if( NEVER(pTerm==0) ) break;
101202 /* The following true for indices with redundant columns.
101203 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
101204 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
101205 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101206 r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
101207 if( r1!=regBase+j ){
101208 if( nReg==1 ){
101209 sqlite3ReleaseTempReg(pParse, regBase);
101210 regBase = r1;
101211 }else{
101212 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
101215 testcase( pTerm->eOperator & WO_ISNULL );
101216 testcase( pTerm->eOperator & WO_IN );
101217 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
101218 Expr *pRight = pTerm->pExpr->pRight;
101219 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
101220 if( zAff ){
101221 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
101222 zAff[j] = SQLITE_AFF_NONE;
101224 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
101225 zAff[j] = SQLITE_AFF_NONE;
101230 *pzAff = zAff;
101231 return regBase;
101234 #ifndef SQLITE_OMIT_EXPLAIN
101236 ** This routine is a helper for explainIndexRange() below
101238 ** pStr holds the text of an expression that we are building up one term
101239 ** at a time. This routine adds a new term to the end of the expression.
101240 ** Terms are separated by AND so add the "AND" text for second and subsequent
101241 ** terms only.
101243 static void explainAppendTerm(
101244 StrAccum *pStr, /* The text expression being built */
101245 int iTerm, /* Index of this term. First is zero */
101246 const char *zColumn, /* Name of the column */
101247 const char *zOp /* Name of the operator */
101249 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
101250 sqlite3StrAccumAppend(pStr, zColumn, -1);
101251 sqlite3StrAccumAppend(pStr, zOp, 1);
101252 sqlite3StrAccumAppend(pStr, "?", 1);
101256 ** Argument pLevel describes a strategy for scanning table pTab. This
101257 ** function returns a pointer to a string buffer containing a description
101258 ** of the subset of table rows scanned by the strategy in the form of an
101259 ** SQL expression. Or, if all rows are scanned, NULL is returned.
101261 ** For example, if the query:
101263 ** SELECT * FROM t1 WHERE a=1 AND b>2;
101265 ** is run and there is an index on (a, b), then this function returns a
101266 ** string similar to:
101268 ** "a=? AND b>?"
101270 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
101271 ** It is the responsibility of the caller to free the buffer when it is
101272 ** no longer required.
101274 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
101275 WherePlan *pPlan = &pLevel->plan;
101276 Index *pIndex = pPlan->u.pIdx;
101277 int nEq = pPlan->nEq;
101278 int i, j;
101279 Column *aCol = pTab->aCol;
101280 int *aiColumn = pIndex->aiColumn;
101281 StrAccum txt;
101283 if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
101284 return 0;
101286 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
101287 txt.db = db;
101288 sqlite3StrAccumAppend(&txt, " (", 2);
101289 for(i=0; i<nEq; i++){
101290 explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
101293 j = i;
101294 if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
101295 explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
101297 if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
101298 explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
101300 sqlite3StrAccumAppend(&txt, ")", 1);
101301 return sqlite3StrAccumFinish(&txt);
101305 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
101306 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
101307 ** record is added to the output to describe the table scan strategy in
101308 ** pLevel.
101310 static void explainOneScan(
101311 Parse *pParse, /* Parse context */
101312 SrcList *pTabList, /* Table list this loop refers to */
101313 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
101314 int iLevel, /* Value for "level" column of output */
101315 int iFrom, /* Value for "from" column of output */
101316 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
101318 if( pParse->explain==2 ){
101319 u32 flags = pLevel->plan.wsFlags;
101320 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
101321 Vdbe *v = pParse->pVdbe; /* VM being constructed */
101322 sqlite3 *db = pParse->db; /* Database handle */
101323 char *zMsg; /* Text to add to EQP output */
101324 sqlite3_int64 nRow; /* Expected number of rows visited by scan */
101325 int iId = pParse->iSelectId; /* Select id (left-most output column) */
101326 int isSearch; /* True for a SEARCH. False for SCAN. */
101328 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
101330 isSearch = (pLevel->plan.nEq>0)
101331 || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
101332 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
101334 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
101335 if( pItem->pSelect ){
101336 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
101337 }else{
101338 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
101341 if( pItem->zAlias ){
101342 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
101344 if( (flags & WHERE_INDEXED)!=0 ){
101345 char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
101346 zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
101347 ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
101348 ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
101349 ((flags & WHERE_TEMP_INDEX)?"":" "),
101350 ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
101351 zWhere
101353 sqlite3DbFree(db, zWhere);
101354 }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
101355 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
101357 if( flags&WHERE_ROWID_EQ ){
101358 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
101359 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
101360 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
101361 }else if( flags&WHERE_BTM_LIMIT ){
101362 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
101363 }else if( flags&WHERE_TOP_LIMIT ){
101364 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
101367 #ifndef SQLITE_OMIT_VIRTUALTABLE
101368 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
101369 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101370 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
101371 pVtabIdx->idxNum, pVtabIdx->idxStr);
101373 #endif
101374 if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
101375 testcase( wctrlFlags & WHERE_ORDERBY_MIN );
101376 nRow = 1;
101377 }else{
101378 nRow = (sqlite3_int64)pLevel->plan.nRow;
101380 zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
101381 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
101384 #else
101385 # define explainOneScan(u,v,w,x,y,z)
101386 #endif /* SQLITE_OMIT_EXPLAIN */
101390 ** Generate code for the start of the iLevel-th loop in the WHERE clause
101391 ** implementation described by pWInfo.
101393 static Bitmask codeOneLoopStart(
101394 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
101395 int iLevel, /* Which level of pWInfo->a[] should be coded */
101396 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
101397 Bitmask notReady /* Which tables are currently available */
101399 int j, k; /* Loop counters */
101400 int iCur; /* The VDBE cursor for the table */
101401 int addrNxt; /* Where to jump to continue with the next IN case */
101402 int omitTable; /* True if we use the index only */
101403 int bRev; /* True if we need to scan in reverse order */
101404 WhereLevel *pLevel; /* The where level to be coded */
101405 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
101406 WhereTerm *pTerm; /* A WHERE clause term */
101407 Parse *pParse; /* Parsing context */
101408 Vdbe *v; /* The prepared stmt under constructions */
101409 struct SrcList_item *pTabItem; /* FROM clause term being coded */
101410 int addrBrk; /* Jump here to break out of the loop */
101411 int addrCont; /* Jump here to continue with next cycle */
101412 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
101413 int iReleaseReg = 0; /* Temp register to free before returning */
101415 pParse = pWInfo->pParse;
101416 v = pParse->pVdbe;
101417 pWC = pWInfo->pWC;
101418 pLevel = &pWInfo->a[iLevel];
101419 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
101420 iCur = pTabItem->iCursor;
101421 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
101422 omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
101423 && (wctrlFlags & WHERE_FORCE_TABLE)==0;
101425 /* Create labels for the "break" and "continue" instructions
101426 ** for the current loop. Jump to addrBrk to break out of a loop.
101427 ** Jump to cont to go immediately to the next iteration of the
101428 ** loop.
101430 ** When there is an IN operator, we also have a "addrNxt" label that
101431 ** means to continue with the next IN value combination. When
101432 ** there are no IN operators in the constraints, the "addrNxt" label
101433 ** is the same as "addrBrk".
101435 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
101436 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
101438 /* If this is the right table of a LEFT OUTER JOIN, allocate and
101439 ** initialize a memory cell that records if this table matches any
101440 ** row of the left table of the join.
101442 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
101443 pLevel->iLeftJoin = ++pParse->nMem;
101444 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
101445 VdbeComment((v, "init LEFT JOIN no-match flag"));
101448 #ifndef SQLITE_OMIT_VIRTUALTABLE
101449 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
101450 /* Case 0: The table is a virtual-table. Use the VFilter and VNext
101451 ** to access the data.
101453 int iReg; /* P3 Value for OP_VFilter */
101454 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101455 int nConstraint = pVtabIdx->nConstraint;
101456 struct sqlite3_index_constraint_usage *aUsage =
101457 pVtabIdx->aConstraintUsage;
101458 const struct sqlite3_index_constraint *aConstraint =
101459 pVtabIdx->aConstraint;
101461 sqlite3ExprCachePush(pParse);
101462 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
101463 for(j=1; j<=nConstraint; j++){
101464 for(k=0; k<nConstraint; k++){
101465 if( aUsage[k].argvIndex==j ){
101466 int iTerm = aConstraint[k].iTermOffset;
101467 sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
101468 break;
101471 if( k==nConstraint ) break;
101473 sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
101474 sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
101475 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
101476 pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
101477 pVtabIdx->needToFreeIdxStr = 0;
101478 for(j=0; j<nConstraint; j++){
101479 if( aUsage[j].omit ){
101480 int iTerm = aConstraint[j].iTermOffset;
101481 disableTerm(pLevel, &pWC->a[iTerm]);
101484 pLevel->op = OP_VNext;
101485 pLevel->p1 = iCur;
101486 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
101487 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
101488 sqlite3ExprCachePop(pParse, 1);
101489 }else
101490 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101492 if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
101493 /* Case 1: We can directly reference a single row using an
101494 ** equality comparison against the ROWID field. Or
101495 ** we reference multiple rows using a "rowid IN (...)"
101496 ** construct.
101498 iReleaseReg = sqlite3GetTempReg(pParse);
101499 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
101500 assert( pTerm!=0 );
101501 assert( pTerm->pExpr!=0 );
101502 assert( pTerm->leftCursor==iCur );
101503 assert( omitTable==0 );
101504 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101505 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
101506 addrNxt = pLevel->addrNxt;
101507 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
101508 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
101509 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101510 VdbeComment((v, "pk"));
101511 pLevel->op = OP_Noop;
101512 }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
101513 /* Case 2: We have an inequality comparison against the ROWID field.
101515 int testOp = OP_Noop;
101516 int start;
101517 int memEndValue = 0;
101518 WhereTerm *pStart, *pEnd;
101520 assert( omitTable==0 );
101521 pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
101522 pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
101523 if( bRev ){
101524 pTerm = pStart;
101525 pStart = pEnd;
101526 pEnd = pTerm;
101528 if( pStart ){
101529 Expr *pX; /* The expression that defines the start bound */
101530 int r1, rTemp; /* Registers for holding the start boundary */
101532 /* The following constant maps TK_xx codes into corresponding
101533 ** seek opcodes. It depends on a particular ordering of TK_xx
101535 const u8 aMoveOp[] = {
101536 /* TK_GT */ OP_SeekGt,
101537 /* TK_LE */ OP_SeekLe,
101538 /* TK_LT */ OP_SeekLt,
101539 /* TK_GE */ OP_SeekGe
101541 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
101542 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
101543 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
101545 testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101546 pX = pStart->pExpr;
101547 assert( pX!=0 );
101548 assert( pStart->leftCursor==iCur );
101549 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
101550 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
101551 VdbeComment((v, "pk"));
101552 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
101553 sqlite3ReleaseTempReg(pParse, rTemp);
101554 disableTerm(pLevel, pStart);
101555 }else{
101556 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
101558 if( pEnd ){
101559 Expr *pX;
101560 pX = pEnd->pExpr;
101561 assert( pX!=0 );
101562 assert( pEnd->leftCursor==iCur );
101563 testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101564 memEndValue = ++pParse->nMem;
101565 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
101566 if( pX->op==TK_LT || pX->op==TK_GT ){
101567 testOp = bRev ? OP_Le : OP_Ge;
101568 }else{
101569 testOp = bRev ? OP_Lt : OP_Gt;
101571 disableTerm(pLevel, pEnd);
101573 start = sqlite3VdbeCurrentAddr(v);
101574 pLevel->op = bRev ? OP_Prev : OP_Next;
101575 pLevel->p1 = iCur;
101576 pLevel->p2 = start;
101577 if( pStart==0 && pEnd==0 ){
101578 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
101579 }else{
101580 assert( pLevel->p5==0 );
101582 if( testOp!=OP_Noop ){
101583 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
101584 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
101585 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101586 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
101587 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
101589 }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
101590 /* Case 3: A scan using an index.
101592 ** The WHERE clause may contain zero or more equality
101593 ** terms ("==" or "IN" operators) that refer to the N
101594 ** left-most columns of the index. It may also contain
101595 ** inequality constraints (>, <, >= or <=) on the indexed
101596 ** column that immediately follows the N equalities. Only
101597 ** the right-most column can be an inequality - the rest must
101598 ** use the "==" and "IN" operators. For example, if the
101599 ** index is on (x,y,z), then the following clauses are all
101600 ** optimized:
101602 ** x=5
101603 ** x=5 AND y=10
101604 ** x=5 AND y<10
101605 ** x=5 AND y>5 AND y<10
101606 ** x=5 AND y=5 AND z<=10
101608 ** The z<10 term of the following cannot be used, only
101609 ** the x=5 term:
101611 ** x=5 AND z<10
101613 ** N may be zero if there are inequality constraints.
101614 ** If there are no inequality constraints, then N is at
101615 ** least one.
101617 ** This case is also used when there are no WHERE clause
101618 ** constraints but an index is selected anyway, in order
101619 ** to force the output order to conform to an ORDER BY.
101621 static const u8 aStartOp[] = {
101624 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
101625 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
101626 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
101627 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
101628 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
101629 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
101631 static const u8 aEndOp[] = {
101632 OP_Noop, /* 0: (!end_constraints) */
101633 OP_IdxGE, /* 1: (end_constraints && !bRev) */
101634 OP_IdxLT /* 2: (end_constraints && bRev) */
101636 int nEq = pLevel->plan.nEq; /* Number of == or IN terms */
101637 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
101638 int regBase; /* Base register holding constraint values */
101639 int r1; /* Temp register */
101640 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
101641 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
101642 int startEq; /* True if range start uses ==, >= or <= */
101643 int endEq; /* True if range end uses ==, >= or <= */
101644 int start_constraints; /* Start of range is constrained */
101645 int nConstraint; /* Number of constraint terms */
101646 Index *pIdx; /* The index we will be using */
101647 int iIdxCur; /* The VDBE cursor for the index */
101648 int nExtraReg = 0; /* Number of extra registers needed */
101649 int op; /* Instruction opcode */
101650 char *zStartAff; /* Affinity for start of range constraint */
101651 char *zEndAff; /* Affinity for end of range constraint */
101653 pIdx = pLevel->plan.u.pIdx;
101654 iIdxCur = pLevel->iIdxCur;
101655 k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
101657 /* If this loop satisfies a sort order (pOrderBy) request that
101658 ** was passed to this function to implement a "SELECT min(x) ..."
101659 ** query, then the caller will only allow the loop to run for
101660 ** a single iteration. This means that the first row returned
101661 ** should not have a NULL value stored in 'x'. If column 'x' is
101662 ** the first one after the nEq equality constraints in the index,
101663 ** this requires some special handling.
101665 if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
101666 && (pLevel->plan.wsFlags&WHERE_ORDERBY)
101667 && (pIdx->nColumn>nEq)
101669 /* assert( pOrderBy->nExpr==1 ); */
101670 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
101671 isMinQuery = 1;
101672 nExtraReg = 1;
101675 /* Find any inequality constraint terms for the start and end
101676 ** of the range.
101678 if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
101679 pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
101680 nExtraReg = 1;
101682 if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
101683 pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
101684 nExtraReg = 1;
101687 /* Generate code to evaluate all constraint terms using == or IN
101688 ** and store the values of those terms in an array of registers
101689 ** starting at regBase.
101691 regBase = codeAllEqualityTerms(
101692 pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
101694 zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
101695 addrNxt = pLevel->addrNxt;
101697 /* If we are doing a reverse order scan on an ascending index, or
101698 ** a forward order scan on a descending index, interchange the
101699 ** start and end terms (pRangeStart and pRangeEnd).
101701 if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
101702 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
101705 testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
101706 testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
101707 testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
101708 testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
101709 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
101710 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
101711 start_constraints = pRangeStart || nEq>0;
101713 /* Seek the index cursor to the start of the range. */
101714 nConstraint = nEq;
101715 if( pRangeStart ){
101716 Expr *pRight = pRangeStart->pExpr->pRight;
101717 sqlite3ExprCode(pParse, pRight, regBase+nEq);
101718 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
101719 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
101721 if( zStartAff ){
101722 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
101723 /* Since the comparison is to be performed with no conversions
101724 ** applied to the operands, set the affinity to apply to pRight to
101725 ** SQLITE_AFF_NONE. */
101726 zStartAff[nEq] = SQLITE_AFF_NONE;
101728 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
101729 zStartAff[nEq] = SQLITE_AFF_NONE;
101732 nConstraint++;
101733 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101734 }else if( isMinQuery ){
101735 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
101736 nConstraint++;
101737 startEq = 0;
101738 start_constraints = 1;
101740 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
101741 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
101742 assert( op!=0 );
101743 testcase( op==OP_Rewind );
101744 testcase( op==OP_Last );
101745 testcase( op==OP_SeekGt );
101746 testcase( op==OP_SeekGe );
101747 testcase( op==OP_SeekLe );
101748 testcase( op==OP_SeekLt );
101749 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
101751 /* Load the value for the inequality constraint at the end of the
101752 ** range (if any).
101754 nConstraint = nEq;
101755 if( pRangeEnd ){
101756 Expr *pRight = pRangeEnd->pExpr->pRight;
101757 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
101758 sqlite3ExprCode(pParse, pRight, regBase+nEq);
101759 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
101760 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
101762 if( zEndAff ){
101763 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
101764 /* Since the comparison is to be performed with no conversions
101765 ** applied to the operands, set the affinity to apply to pRight to
101766 ** SQLITE_AFF_NONE. */
101767 zEndAff[nEq] = SQLITE_AFF_NONE;
101769 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
101770 zEndAff[nEq] = SQLITE_AFF_NONE;
101773 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
101774 nConstraint++;
101775 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101777 sqlite3DbFree(pParse->db, zStartAff);
101778 sqlite3DbFree(pParse->db, zEndAff);
101780 /* Top of the loop body */
101781 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
101783 /* Check if the index cursor is past the end of the range. */
101784 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
101785 testcase( op==OP_Noop );
101786 testcase( op==OP_IdxGE );
101787 testcase( op==OP_IdxLT );
101788 if( op!=OP_Noop ){
101789 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
101790 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
101793 /* If there are inequality constraints, check that the value
101794 ** of the table column that the inequality contrains is not NULL.
101795 ** If it is, jump to the next iteration of the loop.
101797 r1 = sqlite3GetTempReg(pParse);
101798 testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
101799 testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
101800 if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
101801 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
101802 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
101804 sqlite3ReleaseTempReg(pParse, r1);
101806 /* Seek the table cursor, if required */
101807 disableTerm(pLevel, pRangeStart);
101808 disableTerm(pLevel, pRangeEnd);
101809 if( !omitTable ){
101810 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
101811 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
101812 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101813 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
101816 /* Record the instruction used to terminate the loop. Disable
101817 ** WHERE clause terms made redundant by the index range scan.
101819 if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
101820 pLevel->op = OP_Noop;
101821 }else if( bRev ){
101822 pLevel->op = OP_Prev;
101823 }else{
101824 pLevel->op = OP_Next;
101826 pLevel->p1 = iIdxCur;
101827 }else
101829 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
101830 if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
101831 /* Case 4: Two or more separately indexed terms connected by OR
101833 ** Example:
101835 ** CREATE TABLE t1(a,b,c,d);
101836 ** CREATE INDEX i1 ON t1(a);
101837 ** CREATE INDEX i2 ON t1(b);
101838 ** CREATE INDEX i3 ON t1(c);
101840 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
101842 ** In the example, there are three indexed terms connected by OR.
101843 ** The top of the loop looks like this:
101845 ** Null 1 # Zero the rowset in reg 1
101847 ** Then, for each indexed term, the following. The arguments to
101848 ** RowSetTest are such that the rowid of the current row is inserted
101849 ** into the RowSet. If it is already present, control skips the
101850 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
101852 ** sqlite3WhereBegin(<term>)
101853 ** RowSetTest # Insert rowid into rowset
101854 ** Gosub 2 A
101855 ** sqlite3WhereEnd()
101857 ** Following the above, code to terminate the loop. Label A, the target
101858 ** of the Gosub above, jumps to the instruction right after the Goto.
101860 ** Null 1 # Zero the rowset in reg 1
101861 ** Goto B # The loop is finished.
101863 ** A: <loop body> # Return data, whatever.
101865 ** Return 2 # Jump back to the Gosub
101867 ** B: <after the loop>
101870 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
101871 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
101873 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
101874 int regRowset = 0; /* Register for RowSet object */
101875 int regRowid = 0; /* Register holding rowid */
101876 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
101877 int iRetInit; /* Address of regReturn init */
101878 int untestedTerms = 0; /* Some terms not completely tested */
101879 int ii;
101881 pTerm = pLevel->plan.u.pTerm;
101882 assert( pTerm!=0 );
101883 assert( pTerm->eOperator==WO_OR );
101884 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
101885 pOrWc = &pTerm->u.pOrInfo->wc;
101886 pLevel->op = OP_Return;
101887 pLevel->p1 = regReturn;
101889 /* Set up a new SrcList ni pOrTab containing the table being scanned
101890 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
101891 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
101893 if( pWInfo->nLevel>1 ){
101894 int nNotReady; /* The number of notReady tables */
101895 struct SrcList_item *origSrc; /* Original list of tables */
101896 nNotReady = pWInfo->nLevel - iLevel - 1;
101897 pOrTab = sqlite3StackAllocRaw(pParse->db,
101898 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
101899 if( pOrTab==0 ) return notReady;
101900 pOrTab->nAlloc = (i16)(nNotReady + 1);
101901 pOrTab->nSrc = pOrTab->nAlloc;
101902 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
101903 origSrc = pWInfo->pTabList->a;
101904 for(k=1; k<=nNotReady; k++){
101905 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
101907 }else{
101908 pOrTab = pWInfo->pTabList;
101911 /* Initialize the rowset register to contain NULL. An SQL NULL is
101912 ** equivalent to an empty rowset.
101914 ** Also initialize regReturn to contain the address of the instruction
101915 ** immediately following the OP_Return at the bottom of the loop. This
101916 ** is required in a few obscure LEFT JOIN cases where control jumps
101917 ** over the top of the loop into the body of it. In this case the
101918 ** correct response for the end-of-loop code (the OP_Return) is to
101919 ** fall through to the next instruction, just as an OP_Next does if
101920 ** called on an uninitialized cursor.
101922 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
101923 regRowset = ++pParse->nMem;
101924 regRowid = ++pParse->nMem;
101925 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
101927 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
101929 for(ii=0; ii<pOrWc->nTerm; ii++){
101930 WhereTerm *pOrTerm = &pOrWc->a[ii];
101931 if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
101932 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
101933 /* Loop through table entries that match term pOrTerm. */
101934 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
101935 WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
101936 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
101937 if( pSubWInfo ){
101938 explainOneScan(
101939 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
101941 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
101942 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
101943 int r;
101944 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
101945 regRowid);
101946 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
101947 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
101949 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
101951 /* The pSubWInfo->untestedTerms flag means that this OR term
101952 ** contained one or more AND term from a notReady table. The
101953 ** terms from the notReady table could not be tested and will
101954 ** need to be tested later.
101956 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
101958 /* Finish the loop through table entries that match term pOrTerm. */
101959 sqlite3WhereEnd(pSubWInfo);
101963 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
101964 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
101965 sqlite3VdbeResolveLabel(v, iLoopBody);
101967 if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
101968 if( !untestedTerms ) disableTerm(pLevel, pTerm);
101969 }else
101970 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
101973 /* Case 5: There is no usable index. We must do a complete
101974 ** scan of the entire table.
101976 static const u8 aStep[] = { OP_Next, OP_Prev };
101977 static const u8 aStart[] = { OP_Rewind, OP_Last };
101978 assert( bRev==0 || bRev==1 );
101979 assert( omitTable==0 );
101980 pLevel->op = aStep[bRev];
101981 pLevel->p1 = iCur;
101982 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
101983 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
101985 notReady &= ~getMask(pWC->pMaskSet, iCur);
101987 /* Insert code to test every subexpression that can be completely
101988 ** computed using the current set of tables.
101990 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
101991 ** the use of indices become tests that are evaluated against each row of
101992 ** the relevant input tables.
101994 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
101995 Expr *pE;
101996 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
101997 testcase( pTerm->wtFlags & TERM_CODED );
101998 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
101999 if( (pTerm->prereqAll & notReady)!=0 ){
102000 testcase( pWInfo->untestedTerms==0
102001 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
102002 pWInfo->untestedTerms = 1;
102003 continue;
102005 pE = pTerm->pExpr;
102006 assert( pE!=0 );
102007 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
102008 continue;
102010 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
102011 pTerm->wtFlags |= TERM_CODED;
102014 /* For a LEFT OUTER JOIN, generate code that will record the fact that
102015 ** at least one row of the right table has matched the left table.
102017 if( pLevel->iLeftJoin ){
102018 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
102019 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
102020 VdbeComment((v, "record LEFT JOIN hit"));
102021 sqlite3ExprCacheClear(pParse);
102022 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
102023 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
102024 testcase( pTerm->wtFlags & TERM_CODED );
102025 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
102026 if( (pTerm->prereqAll & notReady)!=0 ){
102027 assert( pWInfo->untestedTerms );
102028 continue;
102030 assert( pTerm->pExpr );
102031 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
102032 pTerm->wtFlags |= TERM_CODED;
102035 sqlite3ReleaseTempReg(pParse, iReleaseReg);
102037 return notReady;
102040 #if defined(SQLITE_TEST)
102042 ** The following variable holds a text description of query plan generated
102043 ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
102044 ** overwrites the previous. This information is used for testing and
102045 ** analysis only.
102047 SQLITE_API char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
102048 static int nQPlan = 0; /* Next free slow in _query_plan[] */
102050 #endif /* SQLITE_TEST */
102054 ** Free a WhereInfo structure
102056 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
102057 if( ALWAYS(pWInfo) ){
102058 int i;
102059 for(i=0; i<pWInfo->nLevel; i++){
102060 sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
102061 if( pInfo ){
102062 /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
102063 if( pInfo->needToFreeIdxStr ){
102064 sqlite3_free(pInfo->idxStr);
102066 sqlite3DbFree(db, pInfo);
102068 if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
102069 Index *pIdx = pWInfo->a[i].plan.u.pIdx;
102070 if( pIdx ){
102071 sqlite3DbFree(db, pIdx->zColAff);
102072 sqlite3DbFree(db, pIdx);
102076 whereClauseClear(pWInfo->pWC);
102077 sqlite3DbFree(db, pWInfo);
102083 ** Generate the beginning of the loop used for WHERE clause processing.
102084 ** The return value is a pointer to an opaque structure that contains
102085 ** information needed to terminate the loop. Later, the calling routine
102086 ** should invoke sqlite3WhereEnd() with the return value of this function
102087 ** in order to complete the WHERE clause processing.
102089 ** If an error occurs, this routine returns NULL.
102091 ** The basic idea is to do a nested loop, one loop for each table in
102092 ** the FROM clause of a select. (INSERT and UPDATE statements are the
102093 ** same as a SELECT with only a single table in the FROM clause.) For
102094 ** example, if the SQL is this:
102096 ** SELECT * FROM t1, t2, t3 WHERE ...;
102098 ** Then the code generated is conceptually like the following:
102100 ** foreach row1 in t1 do \ Code generated
102101 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
102102 ** foreach row3 in t3 do /
102103 ** ...
102104 ** end \ Code generated
102105 ** end |-- by sqlite3WhereEnd()
102106 ** end /
102108 ** Note that the loops might not be nested in the order in which they
102109 ** appear in the FROM clause if a different order is better able to make
102110 ** use of indices. Note also that when the IN operator appears in
102111 ** the WHERE clause, it might result in additional nested loops for
102112 ** scanning through all values on the right-hand side of the IN.
102114 ** There are Btree cursors associated with each table. t1 uses cursor
102115 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
102116 ** And so forth. This routine generates code to open those VDBE cursors
102117 ** and sqlite3WhereEnd() generates the code to close them.
102119 ** The code that sqlite3WhereBegin() generates leaves the cursors named
102120 ** in pTabList pointing at their appropriate entries. The [...] code
102121 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
102122 ** data from the various tables of the loop.
102124 ** If the WHERE clause is empty, the foreach loops must each scan their
102125 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
102126 ** the tables have indices and there are terms in the WHERE clause that
102127 ** refer to those indices, a complete table scan can be avoided and the
102128 ** code will run much faster. Most of the work of this routine is checking
102129 ** to see if there are indices that can be used to speed up the loop.
102131 ** Terms of the WHERE clause are also used to limit which rows actually
102132 ** make it to the "..." in the middle of the loop. After each "foreach",
102133 ** terms of the WHERE clause that use only terms in that loop and outer
102134 ** loops are evaluated and if false a jump is made around all subsequent
102135 ** inner loops (or around the "..." if the test occurs within the inner-
102136 ** most loop)
102138 ** OUTER JOINS
102140 ** An outer join of tables t1 and t2 is conceptally coded as follows:
102142 ** foreach row1 in t1 do
102143 ** flag = 0
102144 ** foreach row2 in t2 do
102145 ** start:
102146 ** ...
102147 ** flag = 1
102148 ** end
102149 ** if flag==0 then
102150 ** move the row2 cursor to a null row
102151 ** goto start
102152 ** fi
102153 ** end
102155 ** ORDER BY CLAUSE PROCESSING
102157 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
102158 ** if there is one. If there is no ORDER BY clause or if this routine
102159 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
102161 ** If an index can be used so that the natural output order of the table
102162 ** scan is correct for the ORDER BY clause, then that index is used and
102163 ** *ppOrderBy is set to NULL. This is an optimization that prevents an
102164 ** unnecessary sort of the result set if an index appropriate for the
102165 ** ORDER BY clause already exists.
102167 ** If the where clause loops cannot be arranged to provide the correct
102168 ** output order, then the *ppOrderBy is unchanged.
102170 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
102171 Parse *pParse, /* The parser context */
102172 SrcList *pTabList, /* A list of all tables to be scanned */
102173 Expr *pWhere, /* The WHERE clause */
102174 ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
102175 u16 wctrlFlags /* One of the WHERE_* flags defined in sqliteInt.h */
102177 int i; /* Loop counter */
102178 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
102179 int nTabList; /* Number of elements in pTabList */
102180 WhereInfo *pWInfo; /* Will become the return value of this function */
102181 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
102182 Bitmask notReady; /* Cursors that are not yet positioned */
102183 WhereMaskSet *pMaskSet; /* The expression mask set */
102184 WhereClause *pWC; /* Decomposition of the WHERE clause */
102185 struct SrcList_item *pTabItem; /* A single entry from pTabList */
102186 WhereLevel *pLevel; /* A single level in the pWInfo list */
102187 int iFrom; /* First unused FROM clause element */
102188 int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
102189 sqlite3 *db; /* Database connection */
102191 /* The number of tables in the FROM clause is limited by the number of
102192 ** bits in a Bitmask
102194 testcase( pTabList->nSrc==BMS );
102195 if( pTabList->nSrc>BMS ){
102196 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
102197 return 0;
102200 /* This function normally generates a nested loop for all tables in
102201 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
102202 ** only generate code for the first table in pTabList and assume that
102203 ** any cursors associated with subsequent tables are uninitialized.
102205 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
102207 /* Allocate and initialize the WhereInfo structure that will become the
102208 ** return value. A single allocation is used to store the WhereInfo
102209 ** struct, the contents of WhereInfo.a[], the WhereClause structure
102210 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
102211 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
102212 ** some architectures. Hence the ROUND8() below.
102214 db = pParse->db;
102215 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
102216 pWInfo = sqlite3DbMallocZero(db,
102217 nByteWInfo +
102218 sizeof(WhereClause) +
102219 sizeof(WhereMaskSet)
102221 if( db->mallocFailed ){
102222 sqlite3DbFree(db, pWInfo);
102223 pWInfo = 0;
102224 goto whereBeginError;
102226 pWInfo->nLevel = nTabList;
102227 pWInfo->pParse = pParse;
102228 pWInfo->pTabList = pTabList;
102229 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
102230 pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
102231 pWInfo->wctrlFlags = wctrlFlags;
102232 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
102233 pMaskSet = (WhereMaskSet*)&pWC[1];
102235 /* Split the WHERE clause into separate subexpressions where each
102236 ** subexpression is separated by an AND operator.
102238 initMaskSet(pMaskSet);
102239 whereClauseInit(pWC, pParse, pMaskSet);
102240 sqlite3ExprCodeConstants(pParse, pWhere);
102241 whereSplit(pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
102243 /* Special case: a WHERE clause that is constant. Evaluate the
102244 ** expression and either jump over all of the code or fall thru.
102246 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
102247 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
102248 pWhere = 0;
102251 /* Assign a bit from the bitmask to every term in the FROM clause.
102253 ** When assigning bitmask values to FROM clause cursors, it must be
102254 ** the case that if X is the bitmask for the N-th FROM clause term then
102255 ** the bitmask for all FROM clause terms to the left of the N-th term
102256 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
102257 ** its Expr.iRightJoinTable value to find the bitmask of the right table
102258 ** of the join. Subtracting one from the right table bitmask gives a
102259 ** bitmask for all tables to the left of the join. Knowing the bitmask
102260 ** for all tables to the left of a left join is important. Ticket #3015.
102262 ** Configure the WhereClause.vmask variable so that bits that correspond
102263 ** to virtual table cursors are set. This is used to selectively disable
102264 ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
102265 ** with virtual tables.
102267 ** Note that bitmasks are created for all pTabList->nSrc tables in
102268 ** pTabList, not just the first nTabList tables. nTabList is normally
102269 ** equal to pTabList->nSrc but might be shortened to 1 if the
102270 ** WHERE_ONETABLE_ONLY flag is set.
102272 assert( pWC->vmask==0 && pMaskSet->n==0 );
102273 for(i=0; i<pTabList->nSrc; i++){
102274 createMask(pMaskSet, pTabList->a[i].iCursor);
102275 #ifndef SQLITE_OMIT_VIRTUALTABLE
102276 if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
102277 pWC->vmask |= ((Bitmask)1 << i);
102279 #endif
102281 #ifndef NDEBUG
102283 Bitmask toTheLeft = 0;
102284 for(i=0; i<pTabList->nSrc; i++){
102285 Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
102286 assert( (m-1)==toTheLeft );
102287 toTheLeft |= m;
102290 #endif
102292 /* Analyze all of the subexpressions. Note that exprAnalyze() might
102293 ** add new virtual terms onto the end of the WHERE clause. We do not
102294 ** want to analyze these virtual terms, so start analyzing at the end
102295 ** and work forward so that the added virtual terms are never processed.
102297 exprAnalyzeAll(pTabList, pWC);
102298 if( db->mallocFailed ){
102299 goto whereBeginError;
102302 /* Chose the best index to use for each table in the FROM clause.
102304 ** This loop fills in the following fields:
102306 ** pWInfo->a[].pIdx The index to use for this level of the loop.
102307 ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
102308 ** pWInfo->a[].nEq The number of == and IN constraints
102309 ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
102310 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
102311 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
102312 ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
102314 ** This loop also figures out the nesting order of tables in the FROM
102315 ** clause.
102317 notReady = ~(Bitmask)0;
102318 andFlags = ~0;
102319 WHERETRACE(("*** Optimizer Start ***\n"));
102320 for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
102321 WhereCost bestPlan; /* Most efficient plan seen so far */
102322 Index *pIdx; /* Index for FROM table at pTabItem */
102323 int j; /* For looping over FROM tables */
102324 int bestJ = -1; /* The value of j */
102325 Bitmask m; /* Bitmask value for j or bestJ */
102326 int isOptimal; /* Iterator for optimal/non-optimal search */
102327 int nUnconstrained; /* Number tables without INDEXED BY */
102328 Bitmask notIndexed; /* Mask of tables that cannot use an index */
102330 memset(&bestPlan, 0, sizeof(bestPlan));
102331 bestPlan.rCost = SQLITE_BIG_DBL;
102332 WHERETRACE(("*** Begin search for loop %d ***\n", i));
102334 /* Loop through the remaining entries in the FROM clause to find the
102335 ** next nested loop. The loop tests all FROM clause entries
102336 ** either once or twice.
102338 ** The first test is always performed if there are two or more entries
102339 ** remaining and never performed if there is only one FROM clause entry
102340 ** to choose from. The first test looks for an "optimal" scan. In
102341 ** this context an optimal scan is one that uses the same strategy
102342 ** for the given FROM clause entry as would be selected if the entry
102343 ** were used as the innermost nested loop. In other words, a table
102344 ** is chosen such that the cost of running that table cannot be reduced
102345 ** by waiting for other tables to run first. This "optimal" test works
102346 ** by first assuming that the FROM clause is on the inner loop and finding
102347 ** its query plan, then checking to see if that query plan uses any
102348 ** other FROM clause terms that are notReady. If no notReady terms are
102349 ** used then the "optimal" query plan works.
102351 ** Note that the WhereCost.nRow parameter for an optimal scan might
102352 ** not be as small as it would be if the table really were the innermost
102353 ** join. The nRow value can be reduced by WHERE clause constraints
102354 ** that do not use indices. But this nRow reduction only happens if the
102355 ** table really is the innermost join.
102357 ** The second loop iteration is only performed if no optimal scan
102358 ** strategies were found by the first iteration. This second iteration
102359 ** is used to search for the lowest cost scan overall.
102361 ** Previous versions of SQLite performed only the second iteration -
102362 ** the next outermost loop was always that with the lowest overall
102363 ** cost. However, this meant that SQLite could select the wrong plan
102364 ** for scripts such as the following:
102366 ** CREATE TABLE t1(a, b);
102367 ** CREATE TABLE t2(c, d);
102368 ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
102370 ** The best strategy is to iterate through table t1 first. However it
102371 ** is not possible to determine this with a simple greedy algorithm.
102372 ** Since the cost of a linear scan through table t2 is the same
102373 ** as the cost of a linear scan through table t1, a simple greedy
102374 ** algorithm may choose to use t2 for the outer loop, which is a much
102375 ** costlier approach.
102377 nUnconstrained = 0;
102378 notIndexed = 0;
102379 for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
102380 Bitmask mask; /* Mask of tables not yet ready */
102381 for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
102382 int doNotReorder; /* True if this table should not be reordered */
102383 WhereCost sCost; /* Cost information from best[Virtual]Index() */
102384 ExprList *pOrderBy; /* ORDER BY clause for index to optimize */
102386 doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
102387 if( j!=iFrom && doNotReorder ) break;
102388 m = getMask(pMaskSet, pTabItem->iCursor);
102389 if( (m & notReady)==0 ){
102390 if( j==iFrom ) iFrom++;
102391 continue;
102393 mask = (isOptimal ? m : notReady);
102394 pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
102395 if( pTabItem->pIndex==0 ) nUnconstrained++;
102397 WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
102398 j, isOptimal));
102399 assert( pTabItem->pTab );
102400 #ifndef SQLITE_OMIT_VIRTUALTABLE
102401 if( IsVirtual(pTabItem->pTab) ){
102402 sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
102403 bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102404 &sCost, pp);
102405 }else
102406 #endif
102408 bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102409 &sCost);
102411 assert( isOptimal || (sCost.used&notReady)==0 );
102413 /* If an INDEXED BY clause is present, then the plan must use that
102414 ** index if it uses any index at all */
102415 assert( pTabItem->pIndex==0
102416 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102417 || sCost.plan.u.pIdx==pTabItem->pIndex );
102419 if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
102420 notIndexed |= m;
102423 /* Conditions under which this table becomes the best so far:
102425 ** (1) The table must not depend on other tables that have not
102426 ** yet run.
102428 ** (2) A full-table-scan plan cannot supercede indexed plan unless
102429 ** the full-table-scan is an "optimal" plan as defined above.
102431 ** (3) All tables have an INDEXED BY clause or this table lacks an
102432 ** INDEXED BY clause or this table uses the specific
102433 ** index specified by its INDEXED BY clause. This rule ensures
102434 ** that a best-so-far is always selected even if an impossible
102435 ** combination of INDEXED BY clauses are given. The error
102436 ** will be detected and relayed back to the application later.
102437 ** The NEVER() comes about because rule (2) above prevents
102438 ** An indexable full-table-scan from reaching rule (3).
102440 ** (4) The plan cost must be lower than prior plans or else the
102441 ** cost must be the same and the number of rows must be lower.
102443 if( (sCost.used&notReady)==0 /* (1) */
102444 && (bestJ<0 || (notIndexed&m)!=0 /* (2) */
102445 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102446 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
102447 && (nUnconstrained==0 || pTabItem->pIndex==0 /* (3) */
102448 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
102449 && (bestJ<0 || sCost.rCost<bestPlan.rCost /* (4) */
102450 || (sCost.rCost<=bestPlan.rCost
102451 && sCost.plan.nRow<bestPlan.plan.nRow))
102453 WHERETRACE(("=== table %d is best so far"
102454 " with cost=%g and nRow=%g\n",
102455 j, sCost.rCost, sCost.plan.nRow));
102456 bestPlan = sCost;
102457 bestJ = j;
102459 if( doNotReorder ) break;
102462 assert( bestJ>=0 );
102463 assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
102464 WHERETRACE(("*** Optimizer selects table %d for loop %d"
102465 " with cost=%g and nRow=%g\n",
102466 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
102467 if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
102468 *ppOrderBy = 0;
102470 andFlags &= bestPlan.plan.wsFlags;
102471 pLevel->plan = bestPlan.plan;
102472 testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
102473 testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
102474 if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
102475 pLevel->iIdxCur = pParse->nTab++;
102476 }else{
102477 pLevel->iIdxCur = -1;
102479 notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
102480 pLevel->iFrom = (u8)bestJ;
102481 if( bestPlan.plan.nRow>=(double)1 ){
102482 pParse->nQueryLoop *= bestPlan.plan.nRow;
102485 /* Check that if the table scanned by this loop iteration had an
102486 ** INDEXED BY clause attached to it, that the named index is being
102487 ** used for the scan. If not, then query compilation has failed.
102488 ** Return an error.
102490 pIdx = pTabList->a[bestJ].pIndex;
102491 if( pIdx ){
102492 if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
102493 sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
102494 goto whereBeginError;
102495 }else{
102496 /* If an INDEXED BY clause is used, the bestIndex() function is
102497 ** guaranteed to find the index specified in the INDEXED BY clause
102498 ** if it find an index at all. */
102499 assert( bestPlan.plan.u.pIdx==pIdx );
102503 WHERETRACE(("*** Optimizer Finished ***\n"));
102504 if( pParse->nErr || db->mallocFailed ){
102505 goto whereBeginError;
102508 /* If the total query only selects a single row, then the ORDER BY
102509 ** clause is irrelevant.
102511 if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
102512 *ppOrderBy = 0;
102515 /* If the caller is an UPDATE or DELETE statement that is requesting
102516 ** to use a one-pass algorithm, determine if this is appropriate.
102517 ** The one-pass algorithm only works if the WHERE clause constraints
102518 ** the statement to update a single row.
102520 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
102521 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
102522 pWInfo->okOnePass = 1;
102523 pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
102526 /* Open all tables in the pTabList and any indices selected for
102527 ** searching those tables.
102529 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
102530 notReady = ~(Bitmask)0;
102531 pWInfo->nRowOut = (double)1;
102532 for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
102533 Table *pTab; /* Table to open */
102534 int iDb; /* Index of database containing table/index */
102536 pTabItem = &pTabList->a[pLevel->iFrom];
102537 pTab = pTabItem->pTab;
102538 pLevel->iTabCur = pTabItem->iCursor;
102539 pWInfo->nRowOut *= pLevel->plan.nRow;
102540 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102541 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
102542 /* Do nothing */
102543 }else
102544 #ifndef SQLITE_OMIT_VIRTUALTABLE
102545 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
102546 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
102547 int iCur = pTabItem->iCursor;
102548 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
102549 }else
102550 #endif
102551 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102552 && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
102553 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
102554 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
102555 testcase( pTab->nCol==BMS-1 );
102556 testcase( pTab->nCol==BMS );
102557 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
102558 Bitmask b = pTabItem->colUsed;
102559 int n = 0;
102560 for(; b; b=b>>1, n++){}
102561 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
102562 SQLITE_INT_TO_PTR(n), P4_INT32);
102563 assert( n<=pTab->nCol );
102565 }else{
102566 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
102568 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
102569 if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
102570 constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
102571 }else
102572 #endif
102573 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
102574 Index *pIx = pLevel->plan.u.pIdx;
102575 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
102576 int iIdxCur = pLevel->iIdxCur;
102577 assert( pIx->pSchema==pTab->pSchema );
102578 assert( iIdxCur>=0 );
102579 sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
102580 (char*)pKey, P4_KEYINFO_HANDOFF);
102581 VdbeComment((v, "%s", pIx->zName));
102583 sqlite3CodeVerifySchema(pParse, iDb);
102584 notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
102586 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
102587 if( db->mallocFailed ) goto whereBeginError;
102589 /* Generate the code to do the search. Each iteration of the for
102590 ** loop below generates code for a single nested loop of the VM
102591 ** program.
102593 notReady = ~(Bitmask)0;
102594 for(i=0; i<nTabList; i++){
102595 pLevel = &pWInfo->a[i];
102596 explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
102597 notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
102598 pWInfo->iContinue = pLevel->addrCont;
102601 #ifdef SQLITE_TEST /* For testing and debugging use only */
102602 /* Record in the query plan information about the current table
102603 ** and the index used to access it (if any). If the table itself
102604 ** is not used, its name is just '{}'. If no index is used
102605 ** the index is listed as "{}". If the primary key is used the
102606 ** index name is '*'.
102608 for(i=0; i<nTabList; i++){
102609 char *z;
102610 int n;
102611 pLevel = &pWInfo->a[i];
102612 pTabItem = &pTabList->a[pLevel->iFrom];
102613 z = pTabItem->zAlias;
102614 if( z==0 ) z = pTabItem->pTab->zName;
102615 n = sqlite3Strlen30(z);
102616 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
102617 if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
102618 memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
102619 nQPlan += 2;
102620 }else{
102621 memcpy(&sqlite3_query_plan[nQPlan], z, n);
102622 nQPlan += n;
102624 sqlite3_query_plan[nQPlan++] = ' ';
102626 testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
102627 testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
102628 if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
102629 memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
102630 nQPlan += 2;
102631 }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
102632 n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
102633 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
102634 memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
102635 nQPlan += n;
102636 sqlite3_query_plan[nQPlan++] = ' ';
102638 }else{
102639 memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
102640 nQPlan += 3;
102643 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
102644 sqlite3_query_plan[--nQPlan] = 0;
102646 sqlite3_query_plan[nQPlan] = 0;
102647 nQPlan = 0;
102648 #endif /* SQLITE_TEST // Testing and debugging use only */
102650 /* Record the continuation address in the WhereInfo structure. Then
102651 ** clean up and return.
102653 return pWInfo;
102655 /* Jump here if malloc fails */
102656 whereBeginError:
102657 if( pWInfo ){
102658 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
102659 whereInfoFree(db, pWInfo);
102661 return 0;
102665 ** Generate the end of the WHERE loop. See comments on
102666 ** sqlite3WhereBegin() for additional information.
102668 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
102669 Parse *pParse = pWInfo->pParse;
102670 Vdbe *v = pParse->pVdbe;
102671 int i;
102672 WhereLevel *pLevel;
102673 SrcList *pTabList = pWInfo->pTabList;
102674 sqlite3 *db = pParse->db;
102676 /* Generate loop termination code.
102678 sqlite3ExprCacheClear(pParse);
102679 for(i=pWInfo->nLevel-1; i>=0; i--){
102680 pLevel = &pWInfo->a[i];
102681 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
102682 if( pLevel->op!=OP_Noop ){
102683 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
102684 sqlite3VdbeChangeP5(v, pLevel->p5);
102686 if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
102687 struct InLoop *pIn;
102688 int j;
102689 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
102690 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
102691 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
102692 sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
102693 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
102695 sqlite3DbFree(db, pLevel->u.in.aInLoop);
102697 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
102698 if( pLevel->iLeftJoin ){
102699 int addr;
102700 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
102701 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102702 || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
102703 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
102704 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
102706 if( pLevel->iIdxCur>=0 ){
102707 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
102709 if( pLevel->op==OP_Return ){
102710 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
102711 }else{
102712 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
102714 sqlite3VdbeJumpHere(v, addr);
102718 /* The "break" point is here, just past the end of the outer loop.
102719 ** Set it.
102721 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
102723 /* Close all of the cursors that were opened by sqlite3WhereBegin.
102725 assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
102726 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
102727 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
102728 Table *pTab = pTabItem->pTab;
102729 assert( pTab!=0 );
102730 if( (pTab->tabFlags & TF_Ephemeral)==0
102731 && pTab->pSelect==0
102732 && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
102734 int ws = pLevel->plan.wsFlags;
102735 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
102736 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
102738 if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
102739 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
102743 /* If this scan uses an index, make code substitutions to read data
102744 ** from the index in preference to the table. Sometimes, this means
102745 ** the table need never be read from. This is a performance boost,
102746 ** as the vdbe level waits until the table is read before actually
102747 ** seeking the table cursor to the record corresponding to the current
102748 ** position in the index.
102750 ** Calls to the code generator in between sqlite3WhereBegin and
102751 ** sqlite3WhereEnd will have created code that references the table
102752 ** directly. This loop scans all that code looking for opcodes
102753 ** that reference the table and converts them into opcodes that
102754 ** reference the index.
102756 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
102757 int k, j, last;
102758 VdbeOp *pOp;
102759 Index *pIdx = pLevel->plan.u.pIdx;
102761 assert( pIdx!=0 );
102762 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
102763 last = sqlite3VdbeCurrentAddr(v);
102764 for(k=pWInfo->iTop; k<last; k++, pOp++){
102765 if( pOp->p1!=pLevel->iTabCur ) continue;
102766 if( pOp->opcode==OP_Column ){
102767 for(j=0; j<pIdx->nColumn; j++){
102768 if( pOp->p2==pIdx->aiColumn[j] ){
102769 pOp->p2 = j;
102770 pOp->p1 = pLevel->iIdxCur;
102771 break;
102774 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102775 || j<pIdx->nColumn );
102776 }else if( pOp->opcode==OP_Rowid ){
102777 pOp->p1 = pLevel->iIdxCur;
102778 pOp->opcode = OP_IdxRowid;
102784 /* Final cleanup
102786 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
102787 whereInfoFree(db, pWInfo);
102788 return;
102791 /************** End of where.c ***********************************************/
102792 /************** Begin file parse.c *******************************************/
102793 /* Driver template for the LEMON parser generator.
102794 ** The author disclaims copyright to this source code.
102796 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
102797 ** The only modifications are the addition of a couple of NEVER()
102798 ** macros to disable tests that are needed in the case of a general
102799 ** LALR(1) grammar but which are always false in the
102800 ** specific grammar used by SQLite.
102802 /* First off, code is included that follows the "include" declaration
102803 ** in the input grammar file. */
102807 ** Disable all error recovery processing in the parser push-down
102808 ** automaton.
102810 #define YYNOERRORRECOVERY 1
102813 ** Make yytestcase() the same as testcase()
102815 #define yytestcase(X) testcase(X)
102818 ** An instance of this structure holds information about the
102819 ** LIMIT clause of a SELECT statement.
102821 struct LimitVal {
102822 Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
102823 Expr *pOffset; /* The OFFSET expression. NULL if there is none */
102827 ** An instance of this structure is used to store the LIKE,
102828 ** GLOB, NOT LIKE, and NOT GLOB operators.
102830 struct LikeOp {
102831 Token eOperator; /* "like" or "glob" or "regexp" */
102832 int not; /* True if the NOT keyword is present */
102836 ** An instance of the following structure describes the event of a
102837 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
102838 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
102840 ** UPDATE ON (a,b,c)
102842 ** Then the "b" IdList records the list "a,b,c".
102844 struct TrigEvent { int a; IdList * b; };
102847 ** An instance of this structure holds the ATTACH key and the key type.
102849 struct AttachKey { int type; Token key; };
102852 /* This is a utility routine used to set the ExprSpan.zStart and
102853 ** ExprSpan.zEnd values of pOut so that the span covers the complete
102854 ** range of text beginning with pStart and going to the end of pEnd.
102856 static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
102857 pOut->zStart = pStart->z;
102858 pOut->zEnd = &pEnd->z[pEnd->n];
102861 /* Construct a new Expr object from a single identifier. Use the
102862 ** new Expr to populate pOut. Set the span of pOut to be the identifier
102863 ** that created the expression.
102865 static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
102866 pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
102867 pOut->zStart = pValue->z;
102868 pOut->zEnd = &pValue->z[pValue->n];
102871 /* This routine constructs a binary expression node out of two ExprSpan
102872 ** objects and uses the result to populate a new ExprSpan object.
102874 static void spanBinaryExpr(
102875 ExprSpan *pOut, /* Write the result here */
102876 Parse *pParse, /* The parsing context. Errors accumulate here */
102877 int op, /* The binary operation */
102878 ExprSpan *pLeft, /* The left operand */
102879 ExprSpan *pRight /* The right operand */
102881 pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
102882 pOut->zStart = pLeft->zStart;
102883 pOut->zEnd = pRight->zEnd;
102886 /* Construct an expression node for a unary postfix operator
102888 static void spanUnaryPostfix(
102889 ExprSpan *pOut, /* Write the new expression node here */
102890 Parse *pParse, /* Parsing context to record errors */
102891 int op, /* The operator */
102892 ExprSpan *pOperand, /* The operand */
102893 Token *pPostOp /* The operand token for setting the span */
102895 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
102896 pOut->zStart = pOperand->zStart;
102897 pOut->zEnd = &pPostOp->z[pPostOp->n];
102900 /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
102901 ** unary TK_ISNULL or TK_NOTNULL expression. */
102902 static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
102903 sqlite3 *db = pParse->db;
102904 if( db->mallocFailed==0 && pY->op==TK_NULL ){
102905 pA->op = (u8)op;
102906 sqlite3ExprDelete(db, pA->pRight);
102907 pA->pRight = 0;
102911 /* Construct an expression node for a unary prefix operator
102913 static void spanUnaryPrefix(
102914 ExprSpan *pOut, /* Write the new expression node here */
102915 Parse *pParse, /* Parsing context to record errors */
102916 int op, /* The operator */
102917 ExprSpan *pOperand, /* The operand */
102918 Token *pPreOp /* The operand token for setting the span */
102920 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
102921 pOut->zStart = pPreOp->z;
102922 pOut->zEnd = pOperand->zEnd;
102924 /* Next is all token values, in a form suitable for use by makeheaders.
102925 ** This section will be null unless lemon is run with the -m switch.
102928 ** These constants (all generated automatically by the parser generator)
102929 ** specify the various kinds of tokens (terminals) that the parser
102930 ** understands.
102932 ** Each symbol here is a terminal symbol in the grammar.
102934 /* Make sure the INTERFACE macro is defined.
102936 #ifndef INTERFACE
102937 # define INTERFACE 1
102938 #endif
102939 /* The next thing included is series of defines which control
102940 ** various aspects of the generated parser.
102941 ** YYCODETYPE is the data type used for storing terminal
102942 ** and nonterminal numbers. "unsigned char" is
102943 ** used if there are fewer than 250 terminals
102944 ** and nonterminals. "int" is used otherwise.
102945 ** YYNOCODE is a number of type YYCODETYPE which corresponds
102946 ** to no legal terminal or nonterminal number. This
102947 ** number is used to fill in empty slots of the hash
102948 ** table.
102949 ** YYFALLBACK If defined, this indicates that one or more tokens
102950 ** have fall-back values which should be used if the
102951 ** original value of the token will not parse.
102952 ** YYACTIONTYPE is the data type used for storing terminal
102953 ** and nonterminal numbers. "unsigned char" is
102954 ** used if there are fewer than 250 rules and
102955 ** states combined. "int" is used otherwise.
102956 ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
102957 ** directly to the parser from the tokenizer.
102958 ** YYMINORTYPE is the data type used for all minor tokens.
102959 ** This is typically a union of many types, one of
102960 ** which is sqlite3ParserTOKENTYPE. The entry in the union
102961 ** for base tokens is called "yy0".
102962 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
102963 ** zero the stack is dynamically sized using realloc()
102964 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
102965 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
102966 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
102967 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
102968 ** YYNSTATE the combined number of states.
102969 ** YYNRULE the number of rules in the grammar
102970 ** YYERRORSYMBOL is the code number of the error symbol. If not
102971 ** defined, then do no error processing.
102973 #define YYCODETYPE unsigned char
102974 #define YYNOCODE 253
102975 #define YYACTIONTYPE unsigned short int
102976 #define YYWILDCARD 67
102977 #define sqlite3ParserTOKENTYPE Token
102978 typedef union {
102979 int yyinit;
102980 sqlite3ParserTOKENTYPE yy0;
102981 int yy4;
102982 struct TrigEvent yy90;
102983 ExprSpan yy118;
102984 TriggerStep* yy203;
102985 u8 yy210;
102986 struct {int value; int mask;} yy215;
102987 SrcList* yy259;
102988 struct LimitVal yy292;
102989 Expr* yy314;
102990 ExprList* yy322;
102991 struct LikeOp yy342;
102992 IdList* yy384;
102993 Select* yy387;
102994 } YYMINORTYPE;
102995 #ifndef YYSTACKDEPTH
102996 #define YYSTACKDEPTH 100
102997 #endif
102998 #define sqlite3ParserARG_SDECL Parse *pParse;
102999 #define sqlite3ParserARG_PDECL ,Parse *pParse
103000 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
103001 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
103002 #define YYNSTATE 630
103003 #define YYNRULE 329
103004 #define YYFALLBACK 1
103005 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
103006 #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
103007 #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
103009 /* The yyzerominor constant is used to initialize instances of
103010 ** YYMINORTYPE objects to zero. */
103011 static const YYMINORTYPE yyzerominor = { 0 };
103013 /* Define the yytestcase() macro to be a no-op if is not already defined
103014 ** otherwise.
103016 ** Applications can choose to define yytestcase() in the %include section
103017 ** to a macro that can assist in verifying code coverage. For production
103018 ** code the yytestcase() macro should be turned off. But it is useful
103019 ** for testing.
103021 #ifndef yytestcase
103022 # define yytestcase(X)
103023 #endif
103026 /* Next are the tables used to determine what action to take based on the
103027 ** current state and lookahead token. These tables are used to implement
103028 ** functions that take a state number and lookahead value and return an
103029 ** action integer.
103031 ** Suppose the action integer is N. Then the action is determined as
103032 ** follows
103034 ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
103035 ** token onto the stack and goto state N.
103037 ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
103039 ** N == YYNSTATE+YYNRULE A syntax error has occurred.
103041 ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
103043 ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
103044 ** slots in the yy_action[] table.
103046 ** The action table is constructed as a single large table named yy_action[].
103047 ** Given state S and lookahead X, the action is computed as
103049 ** yy_action[ yy_shift_ofst[S] + X ]
103051 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
103052 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
103053 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
103054 ** and that yy_default[S] should be used instead.
103056 ** The formula above is for computing the action when the lookahead is
103057 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
103058 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
103059 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
103060 ** YY_SHIFT_USE_DFLT.
103062 ** The following are the tables generated in this section:
103064 ** yy_action[] A single table containing all actions.
103065 ** yy_lookahead[] A table containing the lookahead for each entry in
103066 ** yy_action. Used to detect hash collisions.
103067 ** yy_shift_ofst[] For each state, the offset into yy_action for
103068 ** shifting terminals.
103069 ** yy_reduce_ofst[] For each state, the offset into yy_action for
103070 ** shifting non-terminals after a reduce.
103071 ** yy_default[] Default action for each state.
103073 #define YY_ACTTAB_COUNT (1557)
103074 static const YYACTIONTYPE yy_action[] = {
103075 /* 0 */ 313, 960, 186, 419, 2, 172, 627, 597, 55, 55,
103076 /* 10 */ 55, 55, 48, 53, 53, 53, 53, 52, 52, 51,
103077 /* 20 */ 51, 51, 50, 238, 302, 283, 623, 622, 516, 515,
103078 /* 30 */ 590, 584, 55, 55, 55, 55, 282, 53, 53, 53,
103079 /* 40 */ 53, 52, 52, 51, 51, 51, 50, 238, 6, 56,
103080 /* 50 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
103081 /* 60 */ 55, 55, 608, 53, 53, 53, 53, 52, 52, 51,
103082 /* 70 */ 51, 51, 50, 238, 313, 597, 409, 330, 579, 579,
103083 /* 80 */ 32, 53, 53, 53, 53, 52, 52, 51, 51, 51,
103084 /* 90 */ 50, 238, 330, 217, 620, 619, 166, 411, 624, 382,
103085 /* 100 */ 379, 378, 7, 491, 590, 584, 200, 199, 198, 58,
103086 /* 110 */ 377, 300, 414, 621, 481, 66, 623, 622, 621, 580,
103087 /* 120 */ 254, 601, 94, 56, 57, 47, 582, 581, 583, 583,
103088 /* 130 */ 54, 54, 55, 55, 55, 55, 671, 53, 53, 53,
103089 /* 140 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 532,
103090 /* 150 */ 226, 506, 507, 133, 177, 139, 284, 385, 279, 384,
103091 /* 160 */ 169, 197, 342, 398, 251, 226, 253, 275, 388, 167,
103092 /* 170 */ 139, 284, 385, 279, 384, 169, 570, 236, 590, 584,
103093 /* 180 */ 672, 240, 275, 157, 620, 619, 554, 437, 51, 51,
103094 /* 190 */ 51, 50, 238, 343, 439, 553, 438, 56, 57, 47,
103095 /* 200 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
103096 /* 210 */ 465, 53, 53, 53, 53, 52, 52, 51, 51, 51,
103097 /* 220 */ 50, 238, 313, 390, 52, 52, 51, 51, 51, 50,
103098 /* 230 */ 238, 391, 166, 491, 566, 382, 379, 378, 409, 440,
103099 /* 240 */ 579, 579, 252, 440, 607, 66, 377, 513, 621, 49,
103100 /* 250 */ 46, 147, 590, 584, 621, 16, 466, 189, 621, 441,
103101 /* 260 */ 442, 673, 526, 441, 340, 577, 595, 64, 194, 482,
103102 /* 270 */ 434, 56, 57, 47, 582, 581, 583, 583, 54, 54,
103103 /* 280 */ 55, 55, 55, 55, 30, 53, 53, 53, 53, 52,
103104 /* 290 */ 52, 51, 51, 51, 50, 238, 313, 593, 593, 593,
103105 /* 300 */ 387, 578, 606, 493, 259, 351, 258, 411, 1, 623,
103106 /* 310 */ 622, 496, 623, 622, 65, 240, 623, 622, 597, 443,
103107 /* 320 */ 237, 239, 414, 341, 237, 602, 590, 584, 18, 603,
103108 /* 330 */ 166, 601, 87, 382, 379, 378, 67, 623, 622, 38,
103109 /* 340 */ 623, 622, 176, 270, 377, 56, 57, 47, 582, 581,
103110 /* 350 */ 583, 583, 54, 54, 55, 55, 55, 55, 175, 53,
103111 /* 360 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
103112 /* 370 */ 313, 396, 233, 411, 531, 565, 317, 620, 619, 44,
103113 /* 380 */ 620, 619, 240, 206, 620, 619, 597, 266, 414, 268,
103114 /* 390 */ 409, 597, 579, 579, 352, 184, 505, 601, 73, 533,
103115 /* 400 */ 590, 584, 466, 548, 190, 620, 619, 576, 620, 619,
103116 /* 410 */ 547, 383, 551, 35, 332, 575, 574, 600, 504, 56,
103117 /* 420 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
103118 /* 430 */ 55, 55, 567, 53, 53, 53, 53, 52, 52, 51,
103119 /* 440 */ 51, 51, 50, 238, 313, 411, 561, 561, 528, 364,
103120 /* 450 */ 259, 351, 258, 183, 361, 549, 524, 374, 411, 597,
103121 /* 460 */ 414, 240, 560, 560, 409, 604, 579, 579, 328, 601,
103122 /* 470 */ 93, 623, 622, 414, 590, 584, 237, 564, 559, 559,
103123 /* 480 */ 520, 402, 601, 87, 409, 210, 579, 579, 168, 421,
103124 /* 490 */ 950, 519, 950, 56, 57, 47, 582, 581, 583, 583,
103125 /* 500 */ 54, 54, 55, 55, 55, 55, 192, 53, 53, 53,
103126 /* 510 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 600,
103127 /* 520 */ 293, 563, 511, 234, 357, 146, 475, 475, 367, 411,
103128 /* 530 */ 562, 411, 358, 542, 425, 171, 411, 215, 144, 620,
103129 /* 540 */ 619, 544, 318, 353, 414, 203, 414, 275, 590, 584,
103130 /* 550 */ 549, 414, 174, 601, 94, 601, 79, 558, 471, 61,
103131 /* 560 */ 601, 79, 421, 949, 350, 949, 34, 56, 57, 47,
103132 /* 570 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
103133 /* 580 */ 535, 53, 53, 53, 53, 52, 52, 51, 51, 51,
103134 /* 590 */ 50, 238, 313, 307, 424, 394, 272, 49, 46, 147,
103135 /* 600 */ 349, 322, 4, 411, 491, 312, 321, 425, 568, 492,
103136 /* 610 */ 216, 264, 407, 575, 574, 429, 66, 549, 414, 621,
103137 /* 620 */ 540, 602, 590, 584, 13, 603, 621, 601, 72, 12,
103138 /* 630 */ 618, 617, 616, 202, 210, 621, 546, 469, 422, 319,
103139 /* 640 */ 148, 56, 57, 47, 582, 581, 583, 583, 54, 54,
103140 /* 650 */ 55, 55, 55, 55, 338, 53, 53, 53, 53, 52,
103141 /* 660 */ 52, 51, 51, 51, 50, 238, 313, 600, 600, 411,
103142 /* 670 */ 39, 21, 37, 170, 237, 875, 411, 572, 572, 201,
103143 /* 680 */ 144, 473, 538, 331, 414, 474, 143, 146, 630, 628,
103144 /* 690 */ 334, 414, 353, 601, 68, 168, 590, 584, 132, 365,
103145 /* 700 */ 601, 96, 307, 423, 530, 336, 49, 46, 147, 568,
103146 /* 710 */ 406, 216, 549, 360, 529, 56, 57, 47, 582, 581,
103147 /* 720 */ 583, 583, 54, 54, 55, 55, 55, 55, 411, 53,
103148 /* 730 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
103149 /* 740 */ 313, 411, 605, 414, 484, 510, 172, 422, 597, 318,
103150 /* 750 */ 496, 485, 601, 99, 411, 142, 414, 411, 231, 411,
103151 /* 760 */ 540, 411, 359, 629, 2, 601, 97, 426, 308, 414,
103152 /* 770 */ 590, 584, 414, 20, 414, 621, 414, 621, 601, 106,
103153 /* 780 */ 503, 601, 105, 601, 108, 601, 109, 204, 28, 56,
103154 /* 790 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
103155 /* 800 */ 55, 55, 411, 53, 53, 53, 53, 52, 52, 51,
103156 /* 810 */ 51, 51, 50, 238, 313, 411, 597, 414, 411, 276,
103157 /* 820 */ 214, 600, 411, 366, 213, 381, 601, 134, 274, 500,
103158 /* 830 */ 414, 167, 130, 414, 621, 411, 354, 414, 376, 601,
103159 /* 840 */ 135, 129, 601, 100, 590, 584, 601, 104, 522, 521,
103160 /* 850 */ 414, 621, 224, 273, 600, 167, 327, 282, 600, 601,
103161 /* 860 */ 103, 468, 521, 56, 57, 47, 582, 581, 583, 583,
103162 /* 870 */ 54, 54, 55, 55, 55, 55, 411, 53, 53, 53,
103163 /* 880 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 411,
103164 /* 890 */ 27, 414, 411, 375, 276, 167, 359, 544, 50, 238,
103165 /* 900 */ 601, 95, 128, 223, 414, 411, 165, 414, 411, 621,
103166 /* 910 */ 411, 621, 612, 601, 102, 372, 601, 76, 590, 584,
103167 /* 920 */ 414, 570, 236, 414, 470, 414, 167, 621, 188, 601,
103168 /* 930 */ 98, 225, 601, 138, 601, 137, 232, 56, 45, 47,
103169 /* 940 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
103170 /* 950 */ 411, 53, 53, 53, 53, 52, 52, 51, 51, 51,
103171 /* 960 */ 50, 238, 313, 276, 276, 414, 411, 276, 544, 459,
103172 /* 970 */ 359, 171, 209, 479, 601, 136, 628, 334, 621, 621,
103173 /* 980 */ 125, 414, 621, 368, 411, 621, 257, 540, 589, 588,
103174 /* 990 */ 601, 75, 590, 584, 458, 446, 23, 23, 124, 414,
103175 /* 1000 */ 326, 325, 621, 427, 324, 309, 600, 288, 601, 92,
103176 /* 1010 */ 586, 585, 57, 47, 582, 581, 583, 583, 54, 54,
103177 /* 1020 */ 55, 55, 55, 55, 411, 53, 53, 53, 53, 52,
103178 /* 1030 */ 52, 51, 51, 51, 50, 238, 313, 587, 411, 414,
103179 /* 1040 */ 411, 207, 611, 476, 171, 472, 160, 123, 601, 91,
103180 /* 1050 */ 323, 261, 15, 414, 464, 414, 411, 621, 411, 354,
103181 /* 1060 */ 222, 411, 601, 74, 601, 90, 590, 584, 159, 264,
103182 /* 1070 */ 158, 414, 461, 414, 621, 600, 414, 121, 120, 25,
103183 /* 1080 */ 601, 89, 601, 101, 621, 601, 88, 47, 582, 581,
103184 /* 1090 */ 583, 583, 54, 54, 55, 55, 55, 55, 544, 53,
103185 /* 1100 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
103186 /* 1110 */ 43, 405, 263, 3, 610, 264, 140, 415, 622, 24,
103187 /* 1120 */ 410, 11, 456, 594, 118, 155, 219, 452, 408, 621,
103188 /* 1130 */ 621, 621, 156, 43, 405, 621, 3, 286, 621, 113,
103189 /* 1140 */ 415, 622, 111, 445, 411, 400, 557, 403, 545, 10,
103190 /* 1150 */ 411, 408, 264, 110, 205, 436, 541, 566, 453, 414,
103191 /* 1160 */ 621, 621, 63, 621, 435, 414, 411, 621, 601, 94,
103192 /* 1170 */ 403, 621, 411, 337, 601, 86, 150, 40, 41, 534,
103193 /* 1180 */ 566, 414, 242, 264, 42, 413, 412, 414, 600, 595,
103194 /* 1190 */ 601, 85, 191, 333, 107, 451, 601, 84, 621, 539,
103195 /* 1200 */ 40, 41, 420, 230, 411, 149, 316, 42, 413, 412,
103196 /* 1210 */ 398, 127, 595, 315, 621, 399, 278, 625, 181, 414,
103197 /* 1220 */ 593, 593, 593, 592, 591, 14, 450, 411, 601, 71,
103198 /* 1230 */ 240, 621, 43, 405, 264, 3, 615, 180, 264, 415,
103199 /* 1240 */ 622, 614, 414, 593, 593, 593, 592, 591, 14, 621,
103200 /* 1250 */ 408, 601, 70, 621, 417, 33, 405, 613, 3, 411,
103201 /* 1260 */ 264, 411, 415, 622, 418, 626, 178, 509, 8, 403,
103202 /* 1270 */ 241, 416, 126, 408, 414, 621, 414, 449, 208, 566,
103203 /* 1280 */ 240, 221, 621, 601, 83, 601, 82, 599, 297, 277,
103204 /* 1290 */ 296, 30, 403, 31, 395, 264, 295, 397, 489, 40,
103205 /* 1300 */ 41, 411, 566, 220, 621, 294, 42, 413, 412, 271,
103206 /* 1310 */ 621, 595, 600, 621, 59, 60, 414, 269, 267, 623,
103207 /* 1320 */ 622, 36, 40, 41, 621, 601, 81, 598, 235, 42,
103208 /* 1330 */ 413, 412, 621, 621, 595, 265, 344, 411, 248, 556,
103209 /* 1340 */ 173, 185, 593, 593, 593, 592, 591, 14, 218, 29,
103210 /* 1350 */ 621, 543, 414, 305, 304, 303, 179, 301, 411, 566,
103211 /* 1360 */ 454, 601, 80, 289, 335, 593, 593, 593, 592, 591,
103212 /* 1370 */ 14, 411, 287, 414, 151, 392, 246, 260, 411, 196,
103213 /* 1380 */ 195, 523, 601, 69, 411, 245, 414, 526, 537, 285,
103214 /* 1390 */ 389, 595, 621, 414, 536, 601, 17, 362, 153, 414,
103215 /* 1400 */ 466, 463, 601, 78, 154, 414, 462, 152, 601, 77,
103216 /* 1410 */ 355, 255, 621, 455, 601, 9, 621, 386, 444, 517,
103217 /* 1420 */ 247, 621, 593, 593, 593, 621, 621, 244, 621, 243,
103218 /* 1430 */ 430, 518, 292, 621, 329, 621, 145, 393, 280, 513,
103219 /* 1440 */ 291, 131, 621, 514, 621, 621, 311, 621, 259, 346,
103220 /* 1450 */ 249, 621, 621, 229, 314, 621, 228, 512, 227, 240,
103221 /* 1460 */ 494, 488, 310, 164, 487, 486, 373, 480, 163, 262,
103222 /* 1470 */ 369, 371, 162, 26, 212, 478, 477, 161, 141, 363,
103223 /* 1480 */ 467, 122, 339, 187, 119, 348, 347, 117, 116, 115,
103224 /* 1490 */ 114, 112, 182, 457, 320, 22, 433, 432, 448, 19,
103225 /* 1500 */ 609, 431, 428, 62, 193, 596, 573, 298, 555, 552,
103226 /* 1510 */ 571, 404, 290, 380, 498, 510, 495, 306, 281, 499,
103227 /* 1520 */ 250, 5, 497, 460, 345, 447, 569, 550, 238, 299,
103228 /* 1530 */ 527, 525, 508, 961, 502, 501, 961, 401, 961, 211,
103229 /* 1540 */ 490, 356, 256, 961, 483, 961, 961, 961, 961, 961,
103230 /* 1550 */ 961, 961, 961, 961, 961, 961, 370,
103232 static const YYCODETYPE yy_lookahead[] = {
103233 /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
103234 /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
103235 /* 20 */ 89, 90, 91, 92, 15, 98, 26, 27, 7, 8,
103236 /* 30 */ 49, 50, 77, 78, 79, 80, 109, 82, 83, 84,
103237 /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 22, 68,
103238 /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
103239 /* 60 */ 79, 80, 23, 82, 83, 84, 85, 86, 87, 88,
103240 /* 70 */ 89, 90, 91, 92, 19, 94, 112, 19, 114, 115,
103241 /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
103242 /* 90 */ 91, 92, 19, 22, 94, 95, 96, 150, 150, 99,
103243 /* 100 */ 100, 101, 76, 150, 49, 50, 105, 106, 107, 54,
103244 /* 110 */ 110, 158, 165, 165, 161, 162, 26, 27, 165, 113,
103245 /* 120 */ 16, 174, 175, 68, 69, 70, 71, 72, 73, 74,
103246 /* 130 */ 75, 76, 77, 78, 79, 80, 118, 82, 83, 84,
103247 /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 23,
103248 /* 150 */ 92, 97, 98, 24, 96, 97, 98, 99, 100, 101,
103249 /* 160 */ 102, 25, 97, 216, 60, 92, 62, 109, 221, 25,
103250 /* 170 */ 97, 98, 99, 100, 101, 102, 86, 87, 49, 50,
103251 /* 180 */ 118, 116, 109, 25, 94, 95, 32, 97, 88, 89,
103252 /* 190 */ 90, 91, 92, 128, 104, 41, 106, 68, 69, 70,
103253 /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
103254 /* 210 */ 11, 82, 83, 84, 85, 86, 87, 88, 89, 90,
103255 /* 220 */ 91, 92, 19, 19, 86, 87, 88, 89, 90, 91,
103256 /* 230 */ 92, 27, 96, 150, 66, 99, 100, 101, 112, 150,
103257 /* 240 */ 114, 115, 138, 150, 161, 162, 110, 103, 165, 222,
103258 /* 250 */ 223, 224, 49, 50, 165, 22, 57, 24, 165, 170,
103259 /* 260 */ 171, 118, 94, 170, 171, 23, 98, 25, 185, 186,
103260 /* 270 */ 243, 68, 69, 70, 71, 72, 73, 74, 75, 76,
103261 /* 280 */ 77, 78, 79, 80, 126, 82, 83, 84, 85, 86,
103262 /* 290 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 131,
103263 /* 300 */ 88, 23, 172, 173, 105, 106, 107, 150, 22, 26,
103264 /* 310 */ 27, 181, 26, 27, 22, 116, 26, 27, 26, 230,
103265 /* 320 */ 231, 197, 165, 230, 231, 113, 49, 50, 204, 117,
103266 /* 330 */ 96, 174, 175, 99, 100, 101, 22, 26, 27, 136,
103267 /* 340 */ 26, 27, 118, 16, 110, 68, 69, 70, 71, 72,
103268 /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 118, 82,
103269 /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
103270 /* 370 */ 19, 214, 215, 150, 23, 23, 155, 94, 95, 22,
103271 /* 380 */ 94, 95, 116, 160, 94, 95, 94, 60, 165, 62,
103272 /* 390 */ 112, 26, 114, 115, 128, 23, 36, 174, 175, 88,
103273 /* 400 */ 49, 50, 57, 120, 22, 94, 95, 23, 94, 95,
103274 /* 410 */ 120, 51, 25, 136, 169, 170, 171, 194, 58, 68,
103275 /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
103276 /* 430 */ 79, 80, 23, 82, 83, 84, 85, 86, 87, 88,
103277 /* 440 */ 89, 90, 91, 92, 19, 150, 12, 12, 23, 228,
103278 /* 450 */ 105, 106, 107, 23, 233, 25, 165, 19, 150, 94,
103279 /* 460 */ 165, 116, 28, 28, 112, 174, 114, 115, 108, 174,
103280 /* 470 */ 175, 26, 27, 165, 49, 50, 231, 11, 44, 44,
103281 /* 480 */ 46, 46, 174, 175, 112, 160, 114, 115, 50, 22,
103282 /* 490 */ 23, 57, 25, 68, 69, 70, 71, 72, 73, 74,
103283 /* 500 */ 75, 76, 77, 78, 79, 80, 119, 82, 83, 84,
103284 /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 194,
103285 /* 520 */ 225, 23, 23, 215, 19, 95, 105, 106, 107, 150,
103286 /* 530 */ 23, 150, 27, 23, 67, 25, 150, 206, 207, 94,
103287 /* 540 */ 95, 166, 104, 218, 165, 22, 165, 109, 49, 50,
103288 /* 550 */ 120, 165, 25, 174, 175, 174, 175, 23, 21, 234,
103289 /* 560 */ 174, 175, 22, 23, 239, 25, 25, 68, 69, 70,
103290 /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
103291 /* 580 */ 205, 82, 83, 84, 85, 86, 87, 88, 89, 90,
103292 /* 590 */ 91, 92, 19, 22, 23, 216, 23, 222, 223, 224,
103293 /* 600 */ 63, 220, 35, 150, 150, 163, 220, 67, 166, 167,
103294 /* 610 */ 168, 150, 169, 170, 171, 161, 162, 25, 165, 165,
103295 /* 620 */ 150, 113, 49, 50, 25, 117, 165, 174, 175, 35,
103296 /* 630 */ 7, 8, 9, 160, 160, 165, 120, 100, 67, 247,
103297 /* 640 */ 248, 68, 69, 70, 71, 72, 73, 74, 75, 76,
103298 /* 650 */ 77, 78, 79, 80, 193, 82, 83, 84, 85, 86,
103299 /* 660 */ 87, 88, 89, 90, 91, 92, 19, 194, 194, 150,
103300 /* 670 */ 135, 24, 137, 35, 231, 138, 150, 129, 130, 206,
103301 /* 680 */ 207, 30, 27, 213, 165, 34, 118, 95, 0, 1,
103302 /* 690 */ 2, 165, 218, 174, 175, 50, 49, 50, 22, 48,
103303 /* 700 */ 174, 175, 22, 23, 23, 244, 222, 223, 224, 166,
103304 /* 710 */ 167, 168, 120, 239, 23, 68, 69, 70, 71, 72,
103305 /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
103306 /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
103307 /* 740 */ 19, 150, 173, 165, 181, 182, 24, 67, 26, 104,
103308 /* 750 */ 181, 188, 174, 175, 150, 39, 165, 150, 52, 150,
103309 /* 760 */ 150, 150, 150, 144, 145, 174, 175, 249, 250, 165,
103310 /* 770 */ 49, 50, 165, 52, 165, 165, 165, 165, 174, 175,
103311 /* 780 */ 29, 174, 175, 174, 175, 174, 175, 160, 22, 68,
103312 /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
103313 /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
103314 /* 810 */ 89, 90, 91, 92, 19, 150, 94, 165, 150, 150,
103315 /* 820 */ 160, 194, 150, 213, 160, 52, 174, 175, 23, 23,
103316 /* 830 */ 165, 25, 22, 165, 165, 150, 150, 165, 52, 174,
103317 /* 840 */ 175, 22, 174, 175, 49, 50, 174, 175, 190, 191,
103318 /* 850 */ 165, 165, 240, 23, 194, 25, 187, 109, 194, 174,
103319 /* 860 */ 175, 190, 191, 68, 69, 70, 71, 72, 73, 74,
103320 /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
103321 /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
103322 /* 890 */ 22, 165, 150, 23, 150, 25, 150, 166, 91, 92,
103323 /* 900 */ 174, 175, 22, 217, 165, 150, 102, 165, 150, 165,
103324 /* 910 */ 150, 165, 150, 174, 175, 19, 174, 175, 49, 50,
103325 /* 920 */ 165, 86, 87, 165, 23, 165, 25, 165, 24, 174,
103326 /* 930 */ 175, 187, 174, 175, 174, 175, 205, 68, 69, 70,
103327 /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
103328 /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
103329 /* 960 */ 91, 92, 19, 150, 150, 165, 150, 150, 166, 23,
103330 /* 970 */ 150, 25, 160, 20, 174, 175, 1, 2, 165, 165,
103331 /* 980 */ 104, 165, 165, 43, 150, 165, 240, 150, 49, 50,
103332 /* 990 */ 174, 175, 49, 50, 23, 23, 25, 25, 53, 165,
103333 /* 1000 */ 187, 187, 165, 23, 187, 25, 194, 205, 174, 175,
103334 /* 1010 */ 71, 72, 69, 70, 71, 72, 73, 74, 75, 76,
103335 /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
103336 /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 98, 150, 165,
103337 /* 1040 */ 150, 160, 150, 59, 25, 53, 104, 22, 174, 175,
103338 /* 1050 */ 213, 138, 5, 165, 1, 165, 150, 165, 150, 150,
103339 /* 1060 */ 240, 150, 174, 175, 174, 175, 49, 50, 118, 150,
103340 /* 1070 */ 35, 165, 27, 165, 165, 194, 165, 108, 127, 76,
103341 /* 1080 */ 174, 175, 174, 175, 165, 174, 175, 70, 71, 72,
103342 /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 166, 82,
103343 /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
103344 /* 1110 */ 19, 20, 193, 22, 150, 150, 150, 26, 27, 76,
103345 /* 1120 */ 150, 22, 1, 150, 119, 121, 217, 20, 37, 165,
103346 /* 1130 */ 165, 165, 16, 19, 20, 165, 22, 205, 165, 119,
103347 /* 1140 */ 26, 27, 108, 128, 150, 150, 150, 56, 150, 22,
103348 /* 1150 */ 150, 37, 150, 127, 160, 23, 150, 66, 193, 165,
103349 /* 1160 */ 165, 165, 16, 165, 23, 165, 150, 165, 174, 175,
103350 /* 1170 */ 56, 165, 150, 65, 174, 175, 15, 86, 87, 88,
103351 /* 1180 */ 66, 165, 140, 150, 93, 94, 95, 165, 194, 98,
103352 /* 1190 */ 174, 175, 22, 3, 164, 193, 174, 175, 165, 150,
103353 /* 1200 */ 86, 87, 4, 180, 150, 248, 251, 93, 94, 95,
103354 /* 1210 */ 216, 180, 98, 251, 165, 221, 150, 149, 6, 165,
103355 /* 1220 */ 129, 130, 131, 132, 133, 134, 193, 150, 174, 175,
103356 /* 1230 */ 116, 165, 19, 20, 150, 22, 149, 151, 150, 26,
103357 /* 1240 */ 27, 149, 165, 129, 130, 131, 132, 133, 134, 165,
103358 /* 1250 */ 37, 174, 175, 165, 149, 19, 20, 13, 22, 150,
103359 /* 1260 */ 150, 150, 26, 27, 146, 147, 151, 150, 25, 56,
103360 /* 1270 */ 152, 159, 154, 37, 165, 165, 165, 193, 160, 66,
103361 /* 1280 */ 116, 193, 165, 174, 175, 174, 175, 194, 199, 150,
103362 /* 1290 */ 200, 126, 56, 124, 123, 150, 201, 122, 150, 86,
103363 /* 1300 */ 87, 150, 66, 193, 165, 202, 93, 94, 95, 150,
103364 /* 1310 */ 165, 98, 194, 165, 125, 22, 165, 150, 150, 26,
103365 /* 1320 */ 27, 135, 86, 87, 165, 174, 175, 203, 226, 93,
103366 /* 1330 */ 94, 95, 165, 165, 98, 150, 218, 150, 193, 157,
103367 /* 1340 */ 118, 157, 129, 130, 131, 132, 133, 134, 5, 104,
103368 /* 1350 */ 165, 211, 165, 10, 11, 12, 13, 14, 150, 66,
103369 /* 1360 */ 17, 174, 175, 210, 246, 129, 130, 131, 132, 133,
103370 /* 1370 */ 134, 150, 210, 165, 31, 121, 33, 150, 150, 86,
103371 /* 1380 */ 87, 176, 174, 175, 150, 42, 165, 94, 211, 210,
103372 /* 1390 */ 150, 98, 165, 165, 211, 174, 175, 150, 55, 165,
103373 /* 1400 */ 57, 150, 174, 175, 61, 165, 150, 64, 174, 175,
103374 /* 1410 */ 150, 150, 165, 150, 174, 175, 165, 104, 150, 184,
103375 /* 1420 */ 150, 165, 129, 130, 131, 165, 165, 150, 165, 150,
103376 /* 1430 */ 150, 176, 150, 165, 47, 165, 150, 150, 176, 103,
103377 /* 1440 */ 150, 22, 165, 178, 165, 165, 179, 165, 105, 106,
103378 /* 1450 */ 107, 165, 165, 229, 111, 165, 92, 176, 229, 116,
103379 /* 1460 */ 184, 176, 179, 156, 176, 176, 18, 157, 156, 237,
103380 /* 1470 */ 45, 157, 156, 135, 157, 157, 238, 156, 68, 157,
103381 /* 1480 */ 189, 189, 139, 219, 22, 157, 18, 192, 192, 192,
103382 /* 1490 */ 192, 189, 219, 199, 157, 242, 40, 157, 199, 242,
103383 /* 1500 */ 153, 157, 38, 245, 196, 166, 232, 198, 177, 177,
103384 /* 1510 */ 232, 227, 209, 178, 166, 182, 166, 148, 177, 177,
103385 /* 1520 */ 209, 196, 177, 199, 209, 199, 166, 208, 92, 195,
103386 /* 1530 */ 174, 174, 183, 252, 183, 183, 252, 191, 252, 235,
103387 /* 1540 */ 186, 241, 241, 252, 186, 252, 252, 252, 252, 252,
103388 /* 1550 */ 252, 252, 252, 252, 252, 252, 236,
103390 #define YY_SHIFT_USE_DFLT (-74)
103391 #define YY_SHIFT_COUNT (418)
103392 #define YY_SHIFT_MIN (-73)
103393 #define YY_SHIFT_MAX (1468)
103394 static const short yy_shift_ofst[] = {
103395 /* 0 */ 975, 1114, 1343, 1114, 1213, 1213, 90, 90, 0, -19,
103396 /* 10 */ 1213, 1213, 1213, 1213, 1213, 345, 445, 721, 1091, 1213,
103397 /* 20 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103398 /* 30 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103399 /* 40 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
103400 /* 50 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103401 /* 60 */ 1213, 199, 445, 445, 835, 835, 365, 1164, 55, 647,
103402 /* 70 */ 573, 499, 425, 351, 277, 203, 129, 795, 795, 795,
103403 /* 80 */ 795, 795, 795, 795, 795, 795, 795, 795, 795, 795,
103404 /* 90 */ 795, 795, 795, 795, 795, 869, 795, 943, 1017, 1017,
103405 /* 100 */ -69, -45, -45, -45, -45, -45, -1, 58, 138, 100,
103406 /* 110 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
103407 /* 120 */ 445, 445, 445, 445, 445, 445, 537, 438, 445, 445,
103408 /* 130 */ 445, 445, 445, 365, 807, 1436, -74, -74, -74, 1293,
103409 /* 140 */ 73, 434, 434, 311, 314, 290, 283, 286, 540, 467,
103410 /* 150 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
103411 /* 160 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
103412 /* 170 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
103413 /* 180 */ 445, 445, 65, 722, 722, 722, 688, 266, 1164, 1164,
103414 /* 190 */ 1164, -74, -74, -74, 136, 168, 168, 234, 360, 360,
103415 /* 200 */ 360, 430, 372, 435, 352, 278, 126, -36, -36, -36,
103416 /* 210 */ -36, 421, 651, -36, -36, 592, 292, 212, 623, 158,
103417 /* 220 */ 204, 204, 505, 158, 505, 144, 365, 154, 365, 154,
103418 /* 230 */ 645, 154, 204, 154, 154, 535, 548, 548, 365, 387,
103419 /* 240 */ 508, 233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
103420 /* 250 */ 1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
103421 /* 260 */ 1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
103422 /* 270 */ 1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
103423 /* 280 */ 1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
103424 /* 290 */ 1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
103425 /* 300 */ 1243, 1244, 1244, 1212, 1212, 1212, 1212, -74, -74, -74,
103426 /* 310 */ -74, -74, -74, 939, 104, 680, 571, 327, 1, 980,
103427 /* 320 */ 26, 972, 971, 946, 901, 870, 830, 806, 54, 21,
103428 /* 330 */ -73, 510, 242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
103429 /* 340 */ 1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
103430 /* 350 */ 1121, 1005, 1099, 951, 1043, 1003, 969, 1045, 1035, 950,
103431 /* 360 */ 1053, 1047, 1025, 942, 913, 992, 1019, 945, 984, 940,
103432 /* 370 */ 876, 904, 953, 896, 748, 804, 880, 786, 868, 819,
103433 /* 380 */ 805, 810, 773, 751, 766, 706, 716, 691, 681, 568,
103434 /* 390 */ 655, 638, 676, 516, 541, 594, 599, 567, 541, 534,
103435 /* 400 */ 507, 527, 498, 523, 466, 382, 409, 384, 357, 6,
103436 /* 410 */ 240, 224, 143, 62, 18, 71, 39, 9, 5,
103438 #define YY_REDUCE_USE_DFLT (-142)
103439 #define YY_REDUCE_COUNT (312)
103440 #define YY_REDUCE_MIN (-141)
103441 #define YY_REDUCE_MAX (1369)
103442 static const short yy_reduce_ofst[] = {
103443 /* 0 */ -141, 994, 1118, 223, 157, -53, 93, 89, 83, 375,
103444 /* 10 */ 386, 381, 379, 308, 295, 325, -47, 27, 1240, 1234,
103445 /* 20 */ 1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
103446 /* 30 */ 1016, 1000, 911, 908, 906, 890, 888, 874, 834, 816,
103447 /* 40 */ 800, 760, 758, 755, 742, 739, 726, 685, 672, 668,
103448 /* 50 */ 665, 652, 611, 609, 607, 604, 591, 578, 526, 519,
103449 /* 60 */ 453, 474, 454, 461, 443, 245, 442, 473, 484, 484,
103450 /* 70 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
103451 /* 80 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
103452 /* 90 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
103453 /* 100 */ 484, 484, 484, 484, 484, 484, 484, 130, 484, 484,
103454 /* 110 */ 1145, 909, 1110, 1088, 1084, 1033, 1002, 965, 820, 837,
103455 /* 120 */ 746, 686, 612, 817, 610, 919, 221, 563, 814, 813,
103456 /* 130 */ 744, 669, 470, 543, 484, 484, 484, 484, 484, 291,
103457 /* 140 */ 569, 671, 658, 970, 1290, 1287, 1286, 1282, 518, 518,
103458 /* 150 */ 1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
103459 /* 160 */ 1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
103460 /* 170 */ 1049, 1006, 998, 996, 995, 973, 970, 966, 964, 892,
103461 /* 180 */ 762, -52, 881, 932, 802, 731, 619, 812, 664, 660,
103462 /* 190 */ 627, 392, 331, 124, 1358, 1357, 1356, 1354, 1352, 1351,
103463 /* 200 */ 1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
103464 /* 210 */ 1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
103465 /* 220 */ 1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
103466 /* 230 */ 1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
103467 /* 240 */ 1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
103468 /* 250 */ 1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
103469 /* 260 */ 1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
103470 /* 270 */ 1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
103471 /* 280 */ 1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
103472 /* 290 */ 1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
103473 /* 300 */ 1112, 1115, 1086, 1105, 1092, 1087, 1068, 962, 955, 957,
103474 /* 310 */ 1031, 1023, 1030,
103476 static const YYACTIONTYPE yy_default[] = {
103477 /* 0 */ 635, 870, 959, 959, 959, 870, 899, 899, 959, 759,
103478 /* 10 */ 959, 959, 959, 959, 868, 959, 959, 933, 959, 959,
103479 /* 20 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103480 /* 30 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103481 /* 40 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103482 /* 50 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103483 /* 60 */ 959, 959, 959, 959, 899, 899, 674, 763, 794, 959,
103484 /* 70 */ 959, 959, 959, 959, 959, 959, 959, 932, 934, 809,
103485 /* 80 */ 808, 802, 801, 912, 774, 799, 792, 785, 796, 871,
103486 /* 90 */ 864, 865, 863, 867, 872, 959, 795, 831, 848, 830,
103487 /* 100 */ 842, 847, 854, 846, 843, 833, 832, 666, 834, 835,
103488 /* 110 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103489 /* 120 */ 959, 959, 959, 959, 959, 959, 661, 728, 959, 959,
103490 /* 130 */ 959, 959, 959, 959, 836, 837, 851, 850, 849, 959,
103491 /* 140 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103492 /* 150 */ 959, 939, 937, 959, 883, 959, 959, 959, 959, 959,
103493 /* 160 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103494 /* 170 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103495 /* 180 */ 959, 641, 959, 759, 759, 759, 635, 959, 959, 959,
103496 /* 190 */ 959, 951, 763, 753, 719, 959, 959, 959, 959, 959,
103497 /* 200 */ 959, 959, 959, 959, 959, 959, 959, 804, 742, 922,
103498 /* 210 */ 924, 959, 905, 740, 663, 761, 676, 751, 643, 798,
103499 /* 220 */ 776, 776, 917, 798, 917, 700, 959, 788, 959, 788,
103500 /* 230 */ 697, 788, 776, 788, 788, 866, 959, 959, 959, 760,
103501 /* 240 */ 751, 959, 944, 767, 767, 936, 936, 767, 810, 732,
103502 /* 250 */ 798, 739, 739, 739, 739, 767, 798, 810, 732, 732,
103503 /* 260 */ 767, 658, 911, 909, 767, 767, 658, 767, 658, 767,
103504 /* 270 */ 658, 876, 730, 730, 730, 715, 880, 880, 876, 730,
103505 /* 280 */ 700, 730, 715, 730, 730, 780, 775, 780, 775, 780,
103506 /* 290 */ 775, 767, 767, 959, 793, 781, 791, 789, 798, 959,
103507 /* 300 */ 718, 651, 651, 640, 640, 640, 640, 956, 956, 951,
103508 /* 310 */ 702, 702, 684, 959, 959, 959, 959, 959, 959, 959,
103509 /* 320 */ 885, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103510 /* 330 */ 959, 959, 959, 959, 636, 946, 959, 959, 943, 959,
103511 /* 340 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103512 /* 350 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 915,
103513 /* 360 */ 959, 959, 959, 959, 959, 959, 908, 907, 959, 959,
103514 /* 370 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103515 /* 380 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103516 /* 390 */ 959, 959, 959, 959, 790, 959, 782, 959, 869, 959,
103517 /* 400 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 745,
103518 /* 410 */ 819, 959, 818, 822, 817, 668, 959, 649, 959, 632,
103519 /* 420 */ 637, 955, 958, 957, 954, 953, 952, 947, 945, 942,
103520 /* 430 */ 941, 940, 938, 935, 931, 889, 887, 894, 893, 892,
103521 /* 440 */ 891, 890, 888, 886, 884, 805, 803, 800, 797, 930,
103522 /* 450 */ 882, 741, 738, 737, 657, 948, 914, 923, 921, 811,
103523 /* 460 */ 920, 919, 918, 916, 913, 900, 807, 806, 733, 874,
103524 /* 470 */ 873, 660, 904, 903, 902, 906, 910, 901, 769, 659,
103525 /* 480 */ 656, 665, 722, 721, 729, 727, 726, 725, 724, 723,
103526 /* 490 */ 720, 667, 675, 686, 714, 699, 698, 879, 881, 878,
103527 /* 500 */ 877, 707, 706, 712, 711, 710, 709, 708, 705, 704,
103528 /* 510 */ 703, 696, 695, 701, 694, 717, 716, 713, 693, 736,
103529 /* 520 */ 735, 734, 731, 692, 691, 690, 822, 689, 688, 828,
103530 /* 530 */ 827, 815, 858, 756, 755, 754, 766, 765, 778, 777,
103531 /* 540 */ 813, 812, 779, 764, 758, 757, 773, 772, 771, 770,
103532 /* 550 */ 762, 752, 784, 787, 786, 783, 860, 768, 857, 929,
103533 /* 560 */ 928, 927, 926, 925, 862, 861, 829, 826, 679, 680,
103534 /* 570 */ 898, 896, 897, 895, 682, 681, 678, 677, 859, 747,
103535 /* 580 */ 746, 855, 852, 844, 840, 856, 853, 845, 841, 839,
103536 /* 590 */ 838, 824, 823, 821, 820, 816, 825, 670, 748, 744,
103537 /* 600 */ 743, 814, 750, 749, 687, 685, 683, 664, 662, 655,
103538 /* 610 */ 653, 652, 654, 650, 648, 647, 646, 645, 644, 673,
103539 /* 620 */ 672, 671, 669, 668, 642, 639, 638, 634, 633, 631,
103542 /* The next table maps tokens into fallback tokens. If a construct
103543 ** like the following:
103545 ** %fallback ID X Y Z.
103547 ** appears in the grammar, then ID becomes a fallback token for X, Y,
103548 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
103549 ** but it does not parse, the type of the token is changed to ID and
103550 ** the parse is retried before an error is thrown.
103552 #ifdef YYFALLBACK
103553 static const YYCODETYPE yyFallback[] = {
103554 0, /* $ => nothing */
103555 0, /* SEMI => nothing */
103556 26, /* EXPLAIN => ID */
103557 26, /* QUERY => ID */
103558 26, /* PLAN => ID */
103559 26, /* BEGIN => ID */
103560 0, /* TRANSACTION => nothing */
103561 26, /* DEFERRED => ID */
103562 26, /* IMMEDIATE => ID */
103563 26, /* EXCLUSIVE => ID */
103564 0, /* COMMIT => nothing */
103565 26, /* END => ID */
103566 26, /* ROLLBACK => ID */
103567 26, /* SAVEPOINT => ID */
103568 26, /* RELEASE => ID */
103569 0, /* TO => nothing */
103570 0, /* TABLE => nothing */
103571 0, /* CREATE => nothing */
103572 26, /* IF => ID */
103573 0, /* NOT => nothing */
103574 0, /* EXISTS => nothing */
103575 26, /* TEMP => ID */
103576 0, /* LP => nothing */
103577 0, /* RP => nothing */
103578 0, /* AS => nothing */
103579 0, /* COMMA => nothing */
103580 0, /* ID => nothing */
103581 0, /* INDEXED => nothing */
103582 26, /* ABORT => ID */
103583 26, /* ACTION => ID */
103584 26, /* AFTER => ID */
103585 26, /* ANALYZE => ID */
103586 26, /* ASC => ID */
103587 26, /* ATTACH => ID */
103588 26, /* BEFORE => ID */
103589 26, /* BY => ID */
103590 26, /* CASCADE => ID */
103591 26, /* CAST => ID */
103592 26, /* COLUMNKW => ID */
103593 26, /* CONFLICT => ID */
103594 26, /* DATABASE => ID */
103595 26, /* DESC => ID */
103596 26, /* DETACH => ID */
103597 26, /* EACH => ID */
103598 26, /* FAIL => ID */
103599 26, /* FOR => ID */
103600 26, /* IGNORE => ID */
103601 26, /* INITIALLY => ID */
103602 26, /* INSTEAD => ID */
103603 26, /* LIKE_KW => ID */
103604 26, /* MATCH => ID */
103605 26, /* NO => ID */
103606 26, /* KEY => ID */
103607 26, /* OF => ID */
103608 26, /* OFFSET => ID */
103609 26, /* PRAGMA => ID */
103610 26, /* RAISE => ID */
103611 26, /* REPLACE => ID */
103612 26, /* RESTRICT => ID */
103613 26, /* ROW => ID */
103614 26, /* TRIGGER => ID */
103615 26, /* VACUUM => ID */
103616 26, /* VIEW => ID */
103617 26, /* VIRTUAL => ID */
103618 26, /* REINDEX => ID */
103619 26, /* RENAME => ID */
103620 26, /* CTIME_KW => ID */
103622 #endif /* YYFALLBACK */
103624 /* The following structure represents a single element of the
103625 ** parser's stack. Information stored includes:
103627 ** + The state number for the parser at this level of the stack.
103629 ** + The value of the token stored at this level of the stack.
103630 ** (In other words, the "major" token.)
103632 ** + The semantic value stored at this level of the stack. This is
103633 ** the information used by the action routines in the grammar.
103634 ** It is sometimes called the "minor" token.
103636 struct yyStackEntry {
103637 YYACTIONTYPE stateno; /* The state-number */
103638 YYCODETYPE major; /* The major token value. This is the code
103639 ** number for the token at this stack level */
103640 YYMINORTYPE minor; /* The user-supplied minor token value. This
103641 ** is the value of the token */
103643 typedef struct yyStackEntry yyStackEntry;
103645 /* The state of the parser is completely contained in an instance of
103646 ** the following structure */
103647 struct yyParser {
103648 int yyidx; /* Index of top element in stack */
103649 #ifdef YYTRACKMAXSTACKDEPTH
103650 int yyidxMax; /* Maximum value of yyidx */
103651 #endif
103652 int yyerrcnt; /* Shifts left before out of the error */
103653 sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
103654 #if YYSTACKDEPTH<=0
103655 int yystksz; /* Current side of the stack */
103656 yyStackEntry *yystack; /* The parser's stack */
103657 #else
103658 yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
103659 #endif
103661 typedef struct yyParser yyParser;
103663 #ifndef NDEBUG
103664 static FILE *yyTraceFILE = 0;
103665 static char *yyTracePrompt = 0;
103666 #endif /* NDEBUG */
103668 #ifndef NDEBUG
103670 ** Turn parser tracing on by giving a stream to which to write the trace
103671 ** and a prompt to preface each trace message. Tracing is turned off
103672 ** by making either argument NULL
103674 ** Inputs:
103675 ** <ul>
103676 ** <li> A FILE* to which trace output should be written.
103677 ** If NULL, then tracing is turned off.
103678 ** <li> A prefix string written at the beginning of every
103679 ** line of trace output. If NULL, then tracing is
103680 ** turned off.
103681 ** </ul>
103683 ** Outputs:
103684 ** None.
103686 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
103687 yyTraceFILE = TraceFILE;
103688 yyTracePrompt = zTracePrompt;
103689 if( yyTraceFILE==0 ) yyTracePrompt = 0;
103690 else if( yyTracePrompt==0 ) yyTraceFILE = 0;
103692 #endif /* NDEBUG */
103694 #ifndef NDEBUG
103695 /* For tracing shifts, the names of all terminals and nonterminals
103696 ** are required. The following table supplies these names */
103697 static const char *const yyTokenName[] = {
103698 "$", "SEMI", "EXPLAIN", "QUERY",
103699 "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
103700 "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
103701 "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
103702 "TABLE", "CREATE", "IF", "NOT",
103703 "EXISTS", "TEMP", "LP", "RP",
103704 "AS", "COMMA", "ID", "INDEXED",
103705 "ABORT", "ACTION", "AFTER", "ANALYZE",
103706 "ASC", "ATTACH", "BEFORE", "BY",
103707 "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
103708 "DATABASE", "DESC", "DETACH", "EACH",
103709 "FAIL", "FOR", "IGNORE", "INITIALLY",
103710 "INSTEAD", "LIKE_KW", "MATCH", "NO",
103711 "KEY", "OF", "OFFSET", "PRAGMA",
103712 "RAISE", "REPLACE", "RESTRICT", "ROW",
103713 "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
103714 "REINDEX", "RENAME", "CTIME_KW", "ANY",
103715 "OR", "AND", "IS", "BETWEEN",
103716 "IN", "ISNULL", "NOTNULL", "NE",
103717 "EQ", "GT", "LE", "LT",
103718 "GE", "ESCAPE", "BITAND", "BITOR",
103719 "LSHIFT", "RSHIFT", "PLUS", "MINUS",
103720 "STAR", "SLASH", "REM", "CONCAT",
103721 "COLLATE", "BITNOT", "STRING", "JOIN_KW",
103722 "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
103723 "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
103724 "ON", "INSERT", "DELETE", "UPDATE",
103725 "SET", "DEFERRABLE", "FOREIGN", "DROP",
103726 "UNION", "ALL", "EXCEPT", "INTERSECT",
103727 "SELECT", "DISTINCT", "DOT", "FROM",
103728 "JOIN", "USING", "ORDER", "GROUP",
103729 "HAVING", "LIMIT", "WHERE", "INTO",
103730 "VALUES", "INTEGER", "FLOAT", "BLOB",
103731 "REGISTER", "VARIABLE", "CASE", "WHEN",
103732 "THEN", "ELSE", "INDEX", "ALTER",
103733 "ADD", "error", "input", "cmdlist",
103734 "ecmd", "explain", "cmdx", "cmd",
103735 "transtype", "trans_opt", "nm", "savepoint_opt",
103736 "create_table", "create_table_args", "createkw", "temp",
103737 "ifnotexists", "dbnm", "columnlist", "conslist_opt",
103738 "select", "column", "columnid", "type",
103739 "carglist", "id", "ids", "typetoken",
103740 "typename", "signed", "plus_num", "minus_num",
103741 "carg", "ccons", "term", "expr",
103742 "onconf", "sortorder", "autoinc", "idxlist_opt",
103743 "refargs", "defer_subclause", "refarg", "refact",
103744 "init_deferred_pred_opt", "conslist", "tcons", "idxlist",
103745 "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
103746 "ifexists", "fullname", "oneselect", "multiselect_op",
103747 "distinct", "selcollist", "from", "where_opt",
103748 "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
103749 "sclp", "as", "seltablist", "stl_prefix",
103750 "joinop", "indexed_opt", "on_opt", "using_opt",
103751 "joinop2", "inscollist", "sortlist", "sortitem",
103752 "nexprlist", "setlist", "insert_cmd", "inscollist_opt",
103753 "itemlist", "exprlist", "likeop", "between_op",
103754 "in_op", "case_operand", "case_exprlist", "case_else",
103755 "uniqueflag", "collate", "nmnum", "plus_opt",
103756 "number", "trigger_decl", "trigger_cmd_list", "trigger_time",
103757 "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
103758 "trnm", "tridxby", "database_kw_opt", "key_opt",
103759 "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
103760 "vtabarg", "vtabargtoken", "lp", "anylist",
103762 #endif /* NDEBUG */
103764 #ifndef NDEBUG
103765 /* For tracing reduce actions, the names of all rules are required.
103767 static const char *const yyRuleName[] = {
103768 /* 0 */ "input ::= cmdlist",
103769 /* 1 */ "cmdlist ::= cmdlist ecmd",
103770 /* 2 */ "cmdlist ::= ecmd",
103771 /* 3 */ "ecmd ::= SEMI",
103772 /* 4 */ "ecmd ::= explain cmdx SEMI",
103773 /* 5 */ "explain ::=",
103774 /* 6 */ "explain ::= EXPLAIN",
103775 /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
103776 /* 8 */ "cmdx ::= cmd",
103777 /* 9 */ "cmd ::= BEGIN transtype trans_opt",
103778 /* 10 */ "trans_opt ::=",
103779 /* 11 */ "trans_opt ::= TRANSACTION",
103780 /* 12 */ "trans_opt ::= TRANSACTION nm",
103781 /* 13 */ "transtype ::=",
103782 /* 14 */ "transtype ::= DEFERRED",
103783 /* 15 */ "transtype ::= IMMEDIATE",
103784 /* 16 */ "transtype ::= EXCLUSIVE",
103785 /* 17 */ "cmd ::= COMMIT trans_opt",
103786 /* 18 */ "cmd ::= END trans_opt",
103787 /* 19 */ "cmd ::= ROLLBACK trans_opt",
103788 /* 20 */ "savepoint_opt ::= SAVEPOINT",
103789 /* 21 */ "savepoint_opt ::=",
103790 /* 22 */ "cmd ::= SAVEPOINT nm",
103791 /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
103792 /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
103793 /* 25 */ "cmd ::= create_table create_table_args",
103794 /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
103795 /* 27 */ "createkw ::= CREATE",
103796 /* 28 */ "ifnotexists ::=",
103797 /* 29 */ "ifnotexists ::= IF NOT EXISTS",
103798 /* 30 */ "temp ::= TEMP",
103799 /* 31 */ "temp ::=",
103800 /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
103801 /* 33 */ "create_table_args ::= AS select",
103802 /* 34 */ "columnlist ::= columnlist COMMA column",
103803 /* 35 */ "columnlist ::= column",
103804 /* 36 */ "column ::= columnid type carglist",
103805 /* 37 */ "columnid ::= nm",
103806 /* 38 */ "id ::= ID",
103807 /* 39 */ "id ::= INDEXED",
103808 /* 40 */ "ids ::= ID|STRING",
103809 /* 41 */ "nm ::= id",
103810 /* 42 */ "nm ::= STRING",
103811 /* 43 */ "nm ::= JOIN_KW",
103812 /* 44 */ "type ::=",
103813 /* 45 */ "type ::= typetoken",
103814 /* 46 */ "typetoken ::= typename",
103815 /* 47 */ "typetoken ::= typename LP signed RP",
103816 /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
103817 /* 49 */ "typename ::= ids",
103818 /* 50 */ "typename ::= typename ids",
103819 /* 51 */ "signed ::= plus_num",
103820 /* 52 */ "signed ::= minus_num",
103821 /* 53 */ "carglist ::= carglist carg",
103822 /* 54 */ "carglist ::=",
103823 /* 55 */ "carg ::= CONSTRAINT nm ccons",
103824 /* 56 */ "carg ::= ccons",
103825 /* 57 */ "ccons ::= DEFAULT term",
103826 /* 58 */ "ccons ::= DEFAULT LP expr RP",
103827 /* 59 */ "ccons ::= DEFAULT PLUS term",
103828 /* 60 */ "ccons ::= DEFAULT MINUS term",
103829 /* 61 */ "ccons ::= DEFAULT id",
103830 /* 62 */ "ccons ::= NULL onconf",
103831 /* 63 */ "ccons ::= NOT NULL onconf",
103832 /* 64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
103833 /* 65 */ "ccons ::= UNIQUE onconf",
103834 /* 66 */ "ccons ::= CHECK LP expr RP",
103835 /* 67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
103836 /* 68 */ "ccons ::= defer_subclause",
103837 /* 69 */ "ccons ::= COLLATE ids",
103838 /* 70 */ "autoinc ::=",
103839 /* 71 */ "autoinc ::= AUTOINCR",
103840 /* 72 */ "refargs ::=",
103841 /* 73 */ "refargs ::= refargs refarg",
103842 /* 74 */ "refarg ::= MATCH nm",
103843 /* 75 */ "refarg ::= ON INSERT refact",
103844 /* 76 */ "refarg ::= ON DELETE refact",
103845 /* 77 */ "refarg ::= ON UPDATE refact",
103846 /* 78 */ "refact ::= SET NULL",
103847 /* 79 */ "refact ::= SET DEFAULT",
103848 /* 80 */ "refact ::= CASCADE",
103849 /* 81 */ "refact ::= RESTRICT",
103850 /* 82 */ "refact ::= NO ACTION",
103851 /* 83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
103852 /* 84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
103853 /* 85 */ "init_deferred_pred_opt ::=",
103854 /* 86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
103855 /* 87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
103856 /* 88 */ "conslist_opt ::=",
103857 /* 89 */ "conslist_opt ::= COMMA conslist",
103858 /* 90 */ "conslist ::= conslist COMMA tcons",
103859 /* 91 */ "conslist ::= conslist tcons",
103860 /* 92 */ "conslist ::= tcons",
103861 /* 93 */ "tcons ::= CONSTRAINT nm",
103862 /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
103863 /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
103864 /* 96 */ "tcons ::= CHECK LP expr RP onconf",
103865 /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
103866 /* 98 */ "defer_subclause_opt ::=",
103867 /* 99 */ "defer_subclause_opt ::= defer_subclause",
103868 /* 100 */ "onconf ::=",
103869 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
103870 /* 102 */ "orconf ::=",
103871 /* 103 */ "orconf ::= OR resolvetype",
103872 /* 104 */ "resolvetype ::= raisetype",
103873 /* 105 */ "resolvetype ::= IGNORE",
103874 /* 106 */ "resolvetype ::= REPLACE",
103875 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
103876 /* 108 */ "ifexists ::= IF EXISTS",
103877 /* 109 */ "ifexists ::=",
103878 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
103879 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
103880 /* 112 */ "cmd ::= select",
103881 /* 113 */ "select ::= oneselect",
103882 /* 114 */ "select ::= select multiselect_op oneselect",
103883 /* 115 */ "multiselect_op ::= UNION",
103884 /* 116 */ "multiselect_op ::= UNION ALL",
103885 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
103886 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
103887 /* 119 */ "distinct ::= DISTINCT",
103888 /* 120 */ "distinct ::= ALL",
103889 /* 121 */ "distinct ::=",
103890 /* 122 */ "sclp ::= selcollist COMMA",
103891 /* 123 */ "sclp ::=",
103892 /* 124 */ "selcollist ::= sclp expr as",
103893 /* 125 */ "selcollist ::= sclp STAR",
103894 /* 126 */ "selcollist ::= sclp nm DOT STAR",
103895 /* 127 */ "as ::= AS nm",
103896 /* 128 */ "as ::= ids",
103897 /* 129 */ "as ::=",
103898 /* 130 */ "from ::=",
103899 /* 131 */ "from ::= FROM seltablist",
103900 /* 132 */ "stl_prefix ::= seltablist joinop",
103901 /* 133 */ "stl_prefix ::=",
103902 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
103903 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
103904 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
103905 /* 137 */ "dbnm ::=",
103906 /* 138 */ "dbnm ::= DOT nm",
103907 /* 139 */ "fullname ::= nm dbnm",
103908 /* 140 */ "joinop ::= COMMA|JOIN",
103909 /* 141 */ "joinop ::= JOIN_KW JOIN",
103910 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
103911 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
103912 /* 144 */ "on_opt ::= ON expr",
103913 /* 145 */ "on_opt ::=",
103914 /* 146 */ "indexed_opt ::=",
103915 /* 147 */ "indexed_opt ::= INDEXED BY nm",
103916 /* 148 */ "indexed_opt ::= NOT INDEXED",
103917 /* 149 */ "using_opt ::= USING LP inscollist RP",
103918 /* 150 */ "using_opt ::=",
103919 /* 151 */ "orderby_opt ::=",
103920 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
103921 /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
103922 /* 154 */ "sortlist ::= sortitem sortorder",
103923 /* 155 */ "sortitem ::= expr",
103924 /* 156 */ "sortorder ::= ASC",
103925 /* 157 */ "sortorder ::= DESC",
103926 /* 158 */ "sortorder ::=",
103927 /* 159 */ "groupby_opt ::=",
103928 /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
103929 /* 161 */ "having_opt ::=",
103930 /* 162 */ "having_opt ::= HAVING expr",
103931 /* 163 */ "limit_opt ::=",
103932 /* 164 */ "limit_opt ::= LIMIT expr",
103933 /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
103934 /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
103935 /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
103936 /* 168 */ "where_opt ::=",
103937 /* 169 */ "where_opt ::= WHERE expr",
103938 /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
103939 /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
103940 /* 172 */ "setlist ::= nm EQ expr",
103941 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
103942 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
103943 /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
103944 /* 176 */ "insert_cmd ::= INSERT orconf",
103945 /* 177 */ "insert_cmd ::= REPLACE",
103946 /* 178 */ "itemlist ::= itemlist COMMA expr",
103947 /* 179 */ "itemlist ::= expr",
103948 /* 180 */ "inscollist_opt ::=",
103949 /* 181 */ "inscollist_opt ::= LP inscollist RP",
103950 /* 182 */ "inscollist ::= inscollist COMMA nm",
103951 /* 183 */ "inscollist ::= nm",
103952 /* 184 */ "expr ::= term",
103953 /* 185 */ "expr ::= LP expr RP",
103954 /* 186 */ "term ::= NULL",
103955 /* 187 */ "expr ::= id",
103956 /* 188 */ "expr ::= JOIN_KW",
103957 /* 189 */ "expr ::= nm DOT nm",
103958 /* 190 */ "expr ::= nm DOT nm DOT nm",
103959 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
103960 /* 192 */ "term ::= STRING",
103961 /* 193 */ "expr ::= REGISTER",
103962 /* 194 */ "expr ::= VARIABLE",
103963 /* 195 */ "expr ::= expr COLLATE ids",
103964 /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
103965 /* 197 */ "expr ::= ID LP distinct exprlist RP",
103966 /* 198 */ "expr ::= ID LP STAR RP",
103967 /* 199 */ "term ::= CTIME_KW",
103968 /* 200 */ "expr ::= expr AND expr",
103969 /* 201 */ "expr ::= expr OR expr",
103970 /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
103971 /* 203 */ "expr ::= expr EQ|NE expr",
103972 /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
103973 /* 205 */ "expr ::= expr PLUS|MINUS expr",
103974 /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
103975 /* 207 */ "expr ::= expr CONCAT expr",
103976 /* 208 */ "likeop ::= LIKE_KW",
103977 /* 209 */ "likeop ::= NOT LIKE_KW",
103978 /* 210 */ "likeop ::= MATCH",
103979 /* 211 */ "likeop ::= NOT MATCH",
103980 /* 212 */ "expr ::= expr likeop expr",
103981 /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
103982 /* 214 */ "expr ::= expr ISNULL|NOTNULL",
103983 /* 215 */ "expr ::= expr NOT NULL",
103984 /* 216 */ "expr ::= expr IS expr",
103985 /* 217 */ "expr ::= expr IS NOT expr",
103986 /* 218 */ "expr ::= NOT expr",
103987 /* 219 */ "expr ::= BITNOT expr",
103988 /* 220 */ "expr ::= MINUS expr",
103989 /* 221 */ "expr ::= PLUS expr",
103990 /* 222 */ "between_op ::= BETWEEN",
103991 /* 223 */ "between_op ::= NOT BETWEEN",
103992 /* 224 */ "expr ::= expr between_op expr AND expr",
103993 /* 225 */ "in_op ::= IN",
103994 /* 226 */ "in_op ::= NOT IN",
103995 /* 227 */ "expr ::= expr in_op LP exprlist RP",
103996 /* 228 */ "expr ::= LP select RP",
103997 /* 229 */ "expr ::= expr in_op LP select RP",
103998 /* 230 */ "expr ::= expr in_op nm dbnm",
103999 /* 231 */ "expr ::= EXISTS LP select RP",
104000 /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
104001 /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
104002 /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
104003 /* 235 */ "case_else ::= ELSE expr",
104004 /* 236 */ "case_else ::=",
104005 /* 237 */ "case_operand ::= expr",
104006 /* 238 */ "case_operand ::=",
104007 /* 239 */ "exprlist ::= nexprlist",
104008 /* 240 */ "exprlist ::=",
104009 /* 241 */ "nexprlist ::= nexprlist COMMA expr",
104010 /* 242 */ "nexprlist ::= expr",
104011 /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
104012 /* 244 */ "uniqueflag ::= UNIQUE",
104013 /* 245 */ "uniqueflag ::=",
104014 /* 246 */ "idxlist_opt ::=",
104015 /* 247 */ "idxlist_opt ::= LP idxlist RP",
104016 /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
104017 /* 249 */ "idxlist ::= nm collate sortorder",
104018 /* 250 */ "collate ::=",
104019 /* 251 */ "collate ::= COLLATE ids",
104020 /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
104021 /* 253 */ "cmd ::= VACUUM",
104022 /* 254 */ "cmd ::= VACUUM nm",
104023 /* 255 */ "cmd ::= PRAGMA nm dbnm",
104024 /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
104025 /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
104026 /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
104027 /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
104028 /* 260 */ "nmnum ::= plus_num",
104029 /* 261 */ "nmnum ::= nm",
104030 /* 262 */ "nmnum ::= ON",
104031 /* 263 */ "nmnum ::= DELETE",
104032 /* 264 */ "nmnum ::= DEFAULT",
104033 /* 265 */ "plus_num ::= plus_opt number",
104034 /* 266 */ "minus_num ::= MINUS number",
104035 /* 267 */ "number ::= INTEGER|FLOAT",
104036 /* 268 */ "plus_opt ::= PLUS",
104037 /* 269 */ "plus_opt ::=",
104038 /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
104039 /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
104040 /* 272 */ "trigger_time ::= BEFORE",
104041 /* 273 */ "trigger_time ::= AFTER",
104042 /* 274 */ "trigger_time ::= INSTEAD OF",
104043 /* 275 */ "trigger_time ::=",
104044 /* 276 */ "trigger_event ::= DELETE|INSERT",
104045 /* 277 */ "trigger_event ::= UPDATE",
104046 /* 278 */ "trigger_event ::= UPDATE OF inscollist",
104047 /* 279 */ "foreach_clause ::=",
104048 /* 280 */ "foreach_clause ::= FOR EACH ROW",
104049 /* 281 */ "when_clause ::=",
104050 /* 282 */ "when_clause ::= WHEN expr",
104051 /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
104052 /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
104053 /* 285 */ "trnm ::= nm",
104054 /* 286 */ "trnm ::= nm DOT nm",
104055 /* 287 */ "tridxby ::=",
104056 /* 288 */ "tridxby ::= INDEXED BY nm",
104057 /* 289 */ "tridxby ::= NOT INDEXED",
104058 /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
104059 /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
104060 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
104061 /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
104062 /* 294 */ "trigger_cmd ::= select",
104063 /* 295 */ "expr ::= RAISE LP IGNORE RP",
104064 /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
104065 /* 297 */ "raisetype ::= ROLLBACK",
104066 /* 298 */ "raisetype ::= ABORT",
104067 /* 299 */ "raisetype ::= FAIL",
104068 /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
104069 /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
104070 /* 302 */ "cmd ::= DETACH database_kw_opt expr",
104071 /* 303 */ "key_opt ::=",
104072 /* 304 */ "key_opt ::= KEY expr",
104073 /* 305 */ "database_kw_opt ::= DATABASE",
104074 /* 306 */ "database_kw_opt ::=",
104075 /* 307 */ "cmd ::= REINDEX",
104076 /* 308 */ "cmd ::= REINDEX nm dbnm",
104077 /* 309 */ "cmd ::= ANALYZE",
104078 /* 310 */ "cmd ::= ANALYZE nm dbnm",
104079 /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
104080 /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
104081 /* 313 */ "add_column_fullname ::= fullname",
104082 /* 314 */ "kwcolumn_opt ::=",
104083 /* 315 */ "kwcolumn_opt ::= COLUMNKW",
104084 /* 316 */ "cmd ::= create_vtab",
104085 /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
104086 /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
104087 /* 319 */ "vtabarglist ::= vtabarg",
104088 /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
104089 /* 321 */ "vtabarg ::=",
104090 /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
104091 /* 323 */ "vtabargtoken ::= ANY",
104092 /* 324 */ "vtabargtoken ::= lp anylist RP",
104093 /* 325 */ "lp ::= LP",
104094 /* 326 */ "anylist ::=",
104095 /* 327 */ "anylist ::= anylist LP anylist RP",
104096 /* 328 */ "anylist ::= anylist ANY",
104098 #endif /* NDEBUG */
104101 #if YYSTACKDEPTH<=0
104103 ** Try to increase the size of the parser stack.
104105 static void yyGrowStack(yyParser *p){
104106 int newSize;
104107 yyStackEntry *pNew;
104109 newSize = p->yystksz*2 + 100;
104110 pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
104111 if( pNew ){
104112 p->yystack = pNew;
104113 p->yystksz = newSize;
104114 #ifndef NDEBUG
104115 if( yyTraceFILE ){
104116 fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
104117 yyTracePrompt, p->yystksz);
104119 #endif
104122 #endif
104125 ** This function allocates a new parser.
104126 ** The only argument is a pointer to a function which works like
104127 ** malloc.
104129 ** Inputs:
104130 ** A pointer to the function used to allocate memory.
104132 ** Outputs:
104133 ** A pointer to a parser. This pointer is used in subsequent calls
104134 ** to sqlite3Parser and sqlite3ParserFree.
104136 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
104137 yyParser *pParser;
104138 pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
104139 if( pParser ){
104140 pParser->yyidx = -1;
104141 #ifdef YYTRACKMAXSTACKDEPTH
104142 pParser->yyidxMax = 0;
104143 #endif
104144 #if YYSTACKDEPTH<=0
104145 pParser->yystack = NULL;
104146 pParser->yystksz = 0;
104147 yyGrowStack(pParser);
104148 #endif
104150 return pParser;
104153 /* The following function deletes the value associated with a
104154 ** symbol. The symbol can be either a terminal or nonterminal.
104155 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
104156 ** the value.
104158 static void yy_destructor(
104159 yyParser *yypParser, /* The parser */
104160 YYCODETYPE yymajor, /* Type code for object to destroy */
104161 YYMINORTYPE *yypminor /* The object to be destroyed */
104163 sqlite3ParserARG_FETCH;
104164 switch( yymajor ){
104165 /* Here is inserted the actions which take place when a
104166 ** terminal or non-terminal is destroyed. This can happen
104167 ** when the symbol is popped from the stack during a
104168 ** reduce or during error processing or when a parser is
104169 ** being destroyed before it is finished parsing.
104171 ** Note: during a reduce, the only symbols destroyed are those
104172 ** which appear on the RHS of the rule, but which are not used
104173 ** inside the C code.
104175 case 160: /* select */
104176 case 194: /* oneselect */
104178 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
104180 break;
104181 case 174: /* term */
104182 case 175: /* expr */
104184 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
104186 break;
104187 case 179: /* idxlist_opt */
104188 case 187: /* idxlist */
104189 case 197: /* selcollist */
104190 case 200: /* groupby_opt */
104191 case 202: /* orderby_opt */
104192 case 204: /* sclp */
104193 case 214: /* sortlist */
104194 case 216: /* nexprlist */
104195 case 217: /* setlist */
104196 case 220: /* itemlist */
104197 case 221: /* exprlist */
104198 case 226: /* case_exprlist */
104200 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
104202 break;
104203 case 193: /* fullname */
104204 case 198: /* from */
104205 case 206: /* seltablist */
104206 case 207: /* stl_prefix */
104208 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
104210 break;
104211 case 199: /* where_opt */
104212 case 201: /* having_opt */
104213 case 210: /* on_opt */
104214 case 215: /* sortitem */
104215 case 225: /* case_operand */
104216 case 227: /* case_else */
104217 case 238: /* when_clause */
104218 case 243: /* key_opt */
104220 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
104222 break;
104223 case 211: /* using_opt */
104224 case 213: /* inscollist */
104225 case 219: /* inscollist_opt */
104227 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
104229 break;
104230 case 234: /* trigger_cmd_list */
104231 case 239: /* trigger_cmd */
104233 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
104235 break;
104236 case 236: /* trigger_event */
104238 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
104240 break;
104241 default: break; /* If no destructor action specified: do nothing */
104246 ** Pop the parser's stack once.
104248 ** If there is a destructor routine associated with the token which
104249 ** is popped from the stack, then call it.
104251 ** Return the major token number for the symbol popped.
104253 static int yy_pop_parser_stack(yyParser *pParser){
104254 YYCODETYPE yymajor;
104255 yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
104257 /* There is no mechanism by which the parser stack can be popped below
104258 ** empty in SQLite. */
104259 if( NEVER(pParser->yyidx<0) ) return 0;
104260 #ifndef NDEBUG
104261 if( yyTraceFILE && pParser->yyidx>=0 ){
104262 fprintf(yyTraceFILE,"%sPopping %s\n",
104263 yyTracePrompt,
104264 yyTokenName[yytos->major]);
104266 #endif
104267 yymajor = yytos->major;
104268 yy_destructor(pParser, yymajor, &yytos->minor);
104269 pParser->yyidx--;
104270 return yymajor;
104274 ** Deallocate and destroy a parser. Destructors are all called for
104275 ** all stack elements before shutting the parser down.
104277 ** Inputs:
104278 ** <ul>
104279 ** <li> A pointer to the parser. This should be a pointer
104280 ** obtained from sqlite3ParserAlloc.
104281 ** <li> A pointer to a function used to reclaim memory obtained
104282 ** from malloc.
104283 ** </ul>
104285 SQLITE_PRIVATE void sqlite3ParserFree(
104286 void *p, /* The parser to be deleted */
104287 void (*freeProc)(void*) /* Function used to reclaim memory */
104289 yyParser *pParser = (yyParser*)p;
104290 /* In SQLite, we never try to destroy a parser that was not successfully
104291 ** created in the first place. */
104292 if( NEVER(pParser==0) ) return;
104293 while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
104294 #if YYSTACKDEPTH<=0
104295 free(pParser->yystack);
104296 #endif
104297 (*freeProc)((void*)pParser);
104301 ** Return the peak depth of the stack for a parser.
104303 #ifdef YYTRACKMAXSTACKDEPTH
104304 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
104305 yyParser *pParser = (yyParser*)p;
104306 return pParser->yyidxMax;
104308 #endif
104311 ** Find the appropriate action for a parser given the terminal
104312 ** look-ahead token iLookAhead.
104314 ** If the look-ahead token is YYNOCODE, then check to see if the action is
104315 ** independent of the look-ahead. If it is, return the action, otherwise
104316 ** return YY_NO_ACTION.
104318 static int yy_find_shift_action(
104319 yyParser *pParser, /* The parser */
104320 YYCODETYPE iLookAhead /* The look-ahead token */
104322 int i;
104323 int stateno = pParser->yystack[pParser->yyidx].stateno;
104325 if( stateno>YY_SHIFT_COUNT
104326 || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
104327 return yy_default[stateno];
104329 assert( iLookAhead!=YYNOCODE );
104330 i += iLookAhead;
104331 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104332 if( iLookAhead>0 ){
104333 #ifdef YYFALLBACK
104334 YYCODETYPE iFallback; /* Fallback token */
104335 if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
104336 && (iFallback = yyFallback[iLookAhead])!=0 ){
104337 #ifndef NDEBUG
104338 if( yyTraceFILE ){
104339 fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
104340 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
104342 #endif
104343 return yy_find_shift_action(pParser, iFallback);
104345 #endif
104346 #ifdef YYWILDCARD
104348 int j = i - iLookAhead + YYWILDCARD;
104350 #if YY_SHIFT_MIN+YYWILDCARD<0
104351 j>=0 &&
104352 #endif
104353 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
104354 j<YY_ACTTAB_COUNT &&
104355 #endif
104356 yy_lookahead[j]==YYWILDCARD
104358 #ifndef NDEBUG
104359 if( yyTraceFILE ){
104360 fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
104361 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
104363 #endif /* NDEBUG */
104364 return yy_action[j];
104367 #endif /* YYWILDCARD */
104369 return yy_default[stateno];
104370 }else{
104371 return yy_action[i];
104376 ** Find the appropriate action for a parser given the non-terminal
104377 ** look-ahead token iLookAhead.
104379 ** If the look-ahead token is YYNOCODE, then check to see if the action is
104380 ** independent of the look-ahead. If it is, return the action, otherwise
104381 ** return YY_NO_ACTION.
104383 static int yy_find_reduce_action(
104384 int stateno, /* Current state number */
104385 YYCODETYPE iLookAhead /* The look-ahead token */
104387 int i;
104388 #ifdef YYERRORSYMBOL
104389 if( stateno>YY_REDUCE_COUNT ){
104390 return yy_default[stateno];
104392 #else
104393 assert( stateno<=YY_REDUCE_COUNT );
104394 #endif
104395 i = yy_reduce_ofst[stateno];
104396 assert( i!=YY_REDUCE_USE_DFLT );
104397 assert( iLookAhead!=YYNOCODE );
104398 i += iLookAhead;
104399 #ifdef YYERRORSYMBOL
104400 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104401 return yy_default[stateno];
104403 #else
104404 assert( i>=0 && i<YY_ACTTAB_COUNT );
104405 assert( yy_lookahead[i]==iLookAhead );
104406 #endif
104407 return yy_action[i];
104411 ** The following routine is called if the stack overflows.
104413 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
104414 sqlite3ParserARG_FETCH;
104415 yypParser->yyidx--;
104416 #ifndef NDEBUG
104417 if( yyTraceFILE ){
104418 fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
104420 #endif
104421 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
104422 /* Here code is inserted which will execute if the parser
104423 ** stack every overflows */
104425 UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
104426 sqlite3ErrorMsg(pParse, "parser stack overflow");
104427 pParse->parseError = 1;
104428 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
104432 ** Perform a shift action.
104434 static void yy_shift(
104435 yyParser *yypParser, /* The parser to be shifted */
104436 int yyNewState, /* The new state to shift in */
104437 int yyMajor, /* The major token to shift in */
104438 YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
104440 yyStackEntry *yytos;
104441 yypParser->yyidx++;
104442 #ifdef YYTRACKMAXSTACKDEPTH
104443 if( yypParser->yyidx>yypParser->yyidxMax ){
104444 yypParser->yyidxMax = yypParser->yyidx;
104446 #endif
104447 #if YYSTACKDEPTH>0
104448 if( yypParser->yyidx>=YYSTACKDEPTH ){
104449 yyStackOverflow(yypParser, yypMinor);
104450 return;
104452 #else
104453 if( yypParser->yyidx>=yypParser->yystksz ){
104454 yyGrowStack(yypParser);
104455 if( yypParser->yyidx>=yypParser->yystksz ){
104456 yyStackOverflow(yypParser, yypMinor);
104457 return;
104460 #endif
104461 yytos = &yypParser->yystack[yypParser->yyidx];
104462 yytos->stateno = (YYACTIONTYPE)yyNewState;
104463 yytos->major = (YYCODETYPE)yyMajor;
104464 yytos->minor = *yypMinor;
104465 #ifndef NDEBUG
104466 if( yyTraceFILE && yypParser->yyidx>0 ){
104467 int i;
104468 fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
104469 fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
104470 for(i=1; i<=yypParser->yyidx; i++)
104471 fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
104472 fprintf(yyTraceFILE,"\n");
104474 #endif
104477 /* The following table contains information about every rule that
104478 ** is used during the reduce.
104480 static const struct {
104481 YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
104482 unsigned char nrhs; /* Number of right-hand side symbols in the rule */
104483 } yyRuleInfo[] = {
104484 { 142, 1 },
104485 { 143, 2 },
104486 { 143, 1 },
104487 { 144, 1 },
104488 { 144, 3 },
104489 { 145, 0 },
104490 { 145, 1 },
104491 { 145, 3 },
104492 { 146, 1 },
104493 { 147, 3 },
104494 { 149, 0 },
104495 { 149, 1 },
104496 { 149, 2 },
104497 { 148, 0 },
104498 { 148, 1 },
104499 { 148, 1 },
104500 { 148, 1 },
104501 { 147, 2 },
104502 { 147, 2 },
104503 { 147, 2 },
104504 { 151, 1 },
104505 { 151, 0 },
104506 { 147, 2 },
104507 { 147, 3 },
104508 { 147, 5 },
104509 { 147, 2 },
104510 { 152, 6 },
104511 { 154, 1 },
104512 { 156, 0 },
104513 { 156, 3 },
104514 { 155, 1 },
104515 { 155, 0 },
104516 { 153, 4 },
104517 { 153, 2 },
104518 { 158, 3 },
104519 { 158, 1 },
104520 { 161, 3 },
104521 { 162, 1 },
104522 { 165, 1 },
104523 { 165, 1 },
104524 { 166, 1 },
104525 { 150, 1 },
104526 { 150, 1 },
104527 { 150, 1 },
104528 { 163, 0 },
104529 { 163, 1 },
104530 { 167, 1 },
104531 { 167, 4 },
104532 { 167, 6 },
104533 { 168, 1 },
104534 { 168, 2 },
104535 { 169, 1 },
104536 { 169, 1 },
104537 { 164, 2 },
104538 { 164, 0 },
104539 { 172, 3 },
104540 { 172, 1 },
104541 { 173, 2 },
104542 { 173, 4 },
104543 { 173, 3 },
104544 { 173, 3 },
104545 { 173, 2 },
104546 { 173, 2 },
104547 { 173, 3 },
104548 { 173, 5 },
104549 { 173, 2 },
104550 { 173, 4 },
104551 { 173, 4 },
104552 { 173, 1 },
104553 { 173, 2 },
104554 { 178, 0 },
104555 { 178, 1 },
104556 { 180, 0 },
104557 { 180, 2 },
104558 { 182, 2 },
104559 { 182, 3 },
104560 { 182, 3 },
104561 { 182, 3 },
104562 { 183, 2 },
104563 { 183, 2 },
104564 { 183, 1 },
104565 { 183, 1 },
104566 { 183, 2 },
104567 { 181, 3 },
104568 { 181, 2 },
104569 { 184, 0 },
104570 { 184, 2 },
104571 { 184, 2 },
104572 { 159, 0 },
104573 { 159, 2 },
104574 { 185, 3 },
104575 { 185, 2 },
104576 { 185, 1 },
104577 { 186, 2 },
104578 { 186, 7 },
104579 { 186, 5 },
104580 { 186, 5 },
104581 { 186, 10 },
104582 { 188, 0 },
104583 { 188, 1 },
104584 { 176, 0 },
104585 { 176, 3 },
104586 { 189, 0 },
104587 { 189, 2 },
104588 { 190, 1 },
104589 { 190, 1 },
104590 { 190, 1 },
104591 { 147, 4 },
104592 { 192, 2 },
104593 { 192, 0 },
104594 { 147, 8 },
104595 { 147, 4 },
104596 { 147, 1 },
104597 { 160, 1 },
104598 { 160, 3 },
104599 { 195, 1 },
104600 { 195, 2 },
104601 { 195, 1 },
104602 { 194, 9 },
104603 { 196, 1 },
104604 { 196, 1 },
104605 { 196, 0 },
104606 { 204, 2 },
104607 { 204, 0 },
104608 { 197, 3 },
104609 { 197, 2 },
104610 { 197, 4 },
104611 { 205, 2 },
104612 { 205, 1 },
104613 { 205, 0 },
104614 { 198, 0 },
104615 { 198, 2 },
104616 { 207, 2 },
104617 { 207, 0 },
104618 { 206, 7 },
104619 { 206, 7 },
104620 { 206, 7 },
104621 { 157, 0 },
104622 { 157, 2 },
104623 { 193, 2 },
104624 { 208, 1 },
104625 { 208, 2 },
104626 { 208, 3 },
104627 { 208, 4 },
104628 { 210, 2 },
104629 { 210, 0 },
104630 { 209, 0 },
104631 { 209, 3 },
104632 { 209, 2 },
104633 { 211, 4 },
104634 { 211, 0 },
104635 { 202, 0 },
104636 { 202, 3 },
104637 { 214, 4 },
104638 { 214, 2 },
104639 { 215, 1 },
104640 { 177, 1 },
104641 { 177, 1 },
104642 { 177, 0 },
104643 { 200, 0 },
104644 { 200, 3 },
104645 { 201, 0 },
104646 { 201, 2 },
104647 { 203, 0 },
104648 { 203, 2 },
104649 { 203, 4 },
104650 { 203, 4 },
104651 { 147, 5 },
104652 { 199, 0 },
104653 { 199, 2 },
104654 { 147, 7 },
104655 { 217, 5 },
104656 { 217, 3 },
104657 { 147, 8 },
104658 { 147, 5 },
104659 { 147, 6 },
104660 { 218, 2 },
104661 { 218, 1 },
104662 { 220, 3 },
104663 { 220, 1 },
104664 { 219, 0 },
104665 { 219, 3 },
104666 { 213, 3 },
104667 { 213, 1 },
104668 { 175, 1 },
104669 { 175, 3 },
104670 { 174, 1 },
104671 { 175, 1 },
104672 { 175, 1 },
104673 { 175, 3 },
104674 { 175, 5 },
104675 { 174, 1 },
104676 { 174, 1 },
104677 { 175, 1 },
104678 { 175, 1 },
104679 { 175, 3 },
104680 { 175, 6 },
104681 { 175, 5 },
104682 { 175, 4 },
104683 { 174, 1 },
104684 { 175, 3 },
104685 { 175, 3 },
104686 { 175, 3 },
104687 { 175, 3 },
104688 { 175, 3 },
104689 { 175, 3 },
104690 { 175, 3 },
104691 { 175, 3 },
104692 { 222, 1 },
104693 { 222, 2 },
104694 { 222, 1 },
104695 { 222, 2 },
104696 { 175, 3 },
104697 { 175, 5 },
104698 { 175, 2 },
104699 { 175, 3 },
104700 { 175, 3 },
104701 { 175, 4 },
104702 { 175, 2 },
104703 { 175, 2 },
104704 { 175, 2 },
104705 { 175, 2 },
104706 { 223, 1 },
104707 { 223, 2 },
104708 { 175, 5 },
104709 { 224, 1 },
104710 { 224, 2 },
104711 { 175, 5 },
104712 { 175, 3 },
104713 { 175, 5 },
104714 { 175, 4 },
104715 { 175, 4 },
104716 { 175, 5 },
104717 { 226, 5 },
104718 { 226, 4 },
104719 { 227, 2 },
104720 { 227, 0 },
104721 { 225, 1 },
104722 { 225, 0 },
104723 { 221, 1 },
104724 { 221, 0 },
104725 { 216, 3 },
104726 { 216, 1 },
104727 { 147, 11 },
104728 { 228, 1 },
104729 { 228, 0 },
104730 { 179, 0 },
104731 { 179, 3 },
104732 { 187, 5 },
104733 { 187, 3 },
104734 { 229, 0 },
104735 { 229, 2 },
104736 { 147, 4 },
104737 { 147, 1 },
104738 { 147, 2 },
104739 { 147, 3 },
104740 { 147, 5 },
104741 { 147, 6 },
104742 { 147, 5 },
104743 { 147, 6 },
104744 { 230, 1 },
104745 { 230, 1 },
104746 { 230, 1 },
104747 { 230, 1 },
104748 { 230, 1 },
104749 { 170, 2 },
104750 { 171, 2 },
104751 { 232, 1 },
104752 { 231, 1 },
104753 { 231, 0 },
104754 { 147, 5 },
104755 { 233, 11 },
104756 { 235, 1 },
104757 { 235, 1 },
104758 { 235, 2 },
104759 { 235, 0 },
104760 { 236, 1 },
104761 { 236, 1 },
104762 { 236, 3 },
104763 { 237, 0 },
104764 { 237, 3 },
104765 { 238, 0 },
104766 { 238, 2 },
104767 { 234, 3 },
104768 { 234, 2 },
104769 { 240, 1 },
104770 { 240, 3 },
104771 { 241, 0 },
104772 { 241, 3 },
104773 { 241, 2 },
104774 { 239, 7 },
104775 { 239, 8 },
104776 { 239, 5 },
104777 { 239, 5 },
104778 { 239, 1 },
104779 { 175, 4 },
104780 { 175, 6 },
104781 { 191, 1 },
104782 { 191, 1 },
104783 { 191, 1 },
104784 { 147, 4 },
104785 { 147, 6 },
104786 { 147, 3 },
104787 { 243, 0 },
104788 { 243, 2 },
104789 { 242, 1 },
104790 { 242, 0 },
104791 { 147, 1 },
104792 { 147, 3 },
104793 { 147, 1 },
104794 { 147, 3 },
104795 { 147, 6 },
104796 { 147, 6 },
104797 { 244, 1 },
104798 { 245, 0 },
104799 { 245, 1 },
104800 { 147, 1 },
104801 { 147, 4 },
104802 { 246, 7 },
104803 { 247, 1 },
104804 { 247, 3 },
104805 { 248, 0 },
104806 { 248, 2 },
104807 { 249, 1 },
104808 { 249, 3 },
104809 { 250, 1 },
104810 { 251, 0 },
104811 { 251, 4 },
104812 { 251, 2 },
104815 static void yy_accept(yyParser*); /* Forward Declaration */
104818 ** Perform a reduce action and the shift that must immediately
104819 ** follow the reduce.
104821 static void yy_reduce(
104822 yyParser *yypParser, /* The parser */
104823 int yyruleno /* Number of the rule by which to reduce */
104825 int yygoto; /* The next state */
104826 int yyact; /* The next action */
104827 YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
104828 yyStackEntry *yymsp; /* The top of the parser's stack */
104829 int yysize; /* Amount to pop the stack */
104830 sqlite3ParserARG_FETCH;
104831 yymsp = &yypParser->yystack[yypParser->yyidx];
104832 #ifndef NDEBUG
104833 if( yyTraceFILE && yyruleno>=0
104834 && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
104835 fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
104836 yyRuleName[yyruleno]);
104838 #endif /* NDEBUG */
104840 /* Silence complaints from purify about yygotominor being uninitialized
104841 ** in some cases when it is copied into the stack after the following
104842 ** switch. yygotominor is uninitialized when a rule reduces that does
104843 ** not set the value of its left-hand side nonterminal. Leaving the
104844 ** value of the nonterminal uninitialized is utterly harmless as long
104845 ** as the value is never used. So really the only thing this code
104846 ** accomplishes is to quieten purify.
104848 ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
104849 ** without this code, their parser segfaults. I'm not sure what there
104850 ** parser is doing to make this happen. This is the second bug report
104851 ** from wireshark this week. Clearly they are stressing Lemon in ways
104852 ** that it has not been previously stressed... (SQLite ticket #2172)
104854 /*memset(&yygotominor, 0, sizeof(yygotominor));*/
104855 yygotominor = yyzerominor;
104858 switch( yyruleno ){
104859 /* Beginning here are the reduction cases. A typical example
104860 ** follows:
104861 ** case 0:
104862 ** #line <lineno> <grammarfile>
104863 ** { ... } // User supplied code
104864 ** #line <lineno> <thisfile>
104865 ** break;
104867 case 5: /* explain ::= */
104868 { sqlite3BeginParse(pParse, 0); }
104869 break;
104870 case 6: /* explain ::= EXPLAIN */
104871 { sqlite3BeginParse(pParse, 1); }
104872 break;
104873 case 7: /* explain ::= EXPLAIN QUERY PLAN */
104874 { sqlite3BeginParse(pParse, 2); }
104875 break;
104876 case 8: /* cmdx ::= cmd */
104877 { sqlite3FinishCoding(pParse); }
104878 break;
104879 case 9: /* cmd ::= BEGIN transtype trans_opt */
104880 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
104881 break;
104882 case 13: /* transtype ::= */
104883 {yygotominor.yy4 = TK_DEFERRED;}
104884 break;
104885 case 14: /* transtype ::= DEFERRED */
104886 case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
104887 case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
104888 case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
104889 case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
104890 {yygotominor.yy4 = yymsp[0].major;}
104891 break;
104892 case 17: /* cmd ::= COMMIT trans_opt */
104893 case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
104894 {sqlite3CommitTransaction(pParse);}
104895 break;
104896 case 19: /* cmd ::= ROLLBACK trans_opt */
104897 {sqlite3RollbackTransaction(pParse);}
104898 break;
104899 case 22: /* cmd ::= SAVEPOINT nm */
104901 sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
104903 break;
104904 case 23: /* cmd ::= RELEASE savepoint_opt nm */
104906 sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
104908 break;
104909 case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
104911 sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
104913 break;
104914 case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
104916 sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
104918 break;
104919 case 27: /* createkw ::= CREATE */
104921 pParse->db->lookaside.bEnabled = 0;
104922 yygotominor.yy0 = yymsp[0].minor.yy0;
104924 break;
104925 case 28: /* ifnotexists ::= */
104926 case 31: /* temp ::= */ yytestcase(yyruleno==31);
104927 case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
104928 case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
104929 case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
104930 case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
104931 case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
104932 case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
104933 case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
104934 case 121: /* distinct ::= */ yytestcase(yyruleno==121);
104935 case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
104936 case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
104937 {yygotominor.yy4 = 0;}
104938 break;
104939 case 29: /* ifnotexists ::= IF NOT EXISTS */
104940 case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
104941 case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
104942 case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
104943 case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
104944 case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
104945 case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
104946 case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
104947 {yygotominor.yy4 = 1;}
104948 break;
104949 case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
104951 sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
104953 break;
104954 case 33: /* create_table_args ::= AS select */
104956 sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
104957 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
104959 break;
104960 case 36: /* column ::= columnid type carglist */
104962 yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
104963 yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
104965 break;
104966 case 37: /* columnid ::= nm */
104968 sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
104969 yygotominor.yy0 = yymsp[0].minor.yy0;
104971 break;
104972 case 38: /* id ::= ID */
104973 case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
104974 case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
104975 case 41: /* nm ::= id */ yytestcase(yyruleno==41);
104976 case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
104977 case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
104978 case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
104979 case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
104980 case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
104981 case 128: /* as ::= ids */ yytestcase(yyruleno==128);
104982 case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
104983 case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
104984 case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
104985 case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
104986 case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
104987 case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
104988 case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
104989 case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
104990 case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
104991 case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
104992 case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
104993 case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
104994 {yygotominor.yy0 = yymsp[0].minor.yy0;}
104995 break;
104996 case 45: /* type ::= typetoken */
104997 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
104998 break;
104999 case 47: /* typetoken ::= typename LP signed RP */
105001 yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
105002 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
105004 break;
105005 case 48: /* typetoken ::= typename LP signed COMMA signed RP */
105007 yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
105008 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
105010 break;
105011 case 50: /* typename ::= typename ids */
105012 {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);}
105013 break;
105014 case 57: /* ccons ::= DEFAULT term */
105015 case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
105016 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
105017 break;
105018 case 58: /* ccons ::= DEFAULT LP expr RP */
105019 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
105020 break;
105021 case 60: /* ccons ::= DEFAULT MINUS term */
105023 ExprSpan v;
105024 v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
105025 v.zStart = yymsp[-1].minor.yy0.z;
105026 v.zEnd = yymsp[0].minor.yy118.zEnd;
105027 sqlite3AddDefaultValue(pParse,&v);
105029 break;
105030 case 61: /* ccons ::= DEFAULT id */
105032 ExprSpan v;
105033 spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
105034 sqlite3AddDefaultValue(pParse,&v);
105036 break;
105037 case 63: /* ccons ::= NOT NULL onconf */
105038 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
105039 break;
105040 case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
105041 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
105042 break;
105043 case 65: /* ccons ::= UNIQUE onconf */
105044 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
105045 break;
105046 case 66: /* ccons ::= CHECK LP expr RP */
105047 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
105048 break;
105049 case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
105050 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
105051 break;
105052 case 68: /* ccons ::= defer_subclause */
105053 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
105054 break;
105055 case 69: /* ccons ::= COLLATE ids */
105056 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
105057 break;
105058 case 72: /* refargs ::= */
105059 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
105060 break;
105061 case 73: /* refargs ::= refargs refarg */
105062 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
105063 break;
105064 case 74: /* refarg ::= MATCH nm */
105065 case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
105066 { yygotominor.yy215.value = 0; yygotominor.yy215.mask = 0x000000; }
105067 break;
105068 case 76: /* refarg ::= ON DELETE refact */
105069 { yygotominor.yy215.value = yymsp[0].minor.yy4; yygotominor.yy215.mask = 0x0000ff; }
105070 break;
105071 case 77: /* refarg ::= ON UPDATE refact */
105072 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8; yygotominor.yy215.mask = 0x00ff00; }
105073 break;
105074 case 78: /* refact ::= SET NULL */
105075 { yygotominor.yy4 = OE_SetNull; /* EV: R-33326-45252 */}
105076 break;
105077 case 79: /* refact ::= SET DEFAULT */
105078 { yygotominor.yy4 = OE_SetDflt; /* EV: R-33326-45252 */}
105079 break;
105080 case 80: /* refact ::= CASCADE */
105081 { yygotominor.yy4 = OE_Cascade; /* EV: R-33326-45252 */}
105082 break;
105083 case 81: /* refact ::= RESTRICT */
105084 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
105085 break;
105086 case 82: /* refact ::= NO ACTION */
105087 { yygotominor.yy4 = OE_None; /* EV: R-33326-45252 */}
105088 break;
105089 case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
105090 case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
105091 case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
105092 case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
105093 {yygotominor.yy4 = yymsp[0].minor.yy4;}
105094 break;
105095 case 88: /* conslist_opt ::= */
105096 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
105097 break;
105098 case 89: /* conslist_opt ::= COMMA conslist */
105099 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
105100 break;
105101 case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
105102 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
105103 break;
105104 case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
105105 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
105106 break;
105107 case 96: /* tcons ::= CHECK LP expr RP onconf */
105108 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
105109 break;
105110 case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
105112 sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
105113 sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
105115 break;
105116 case 100: /* onconf ::= */
105117 {yygotominor.yy4 = OE_Default;}
105118 break;
105119 case 102: /* orconf ::= */
105120 {yygotominor.yy210 = OE_Default;}
105121 break;
105122 case 103: /* orconf ::= OR resolvetype */
105123 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
105124 break;
105125 case 105: /* resolvetype ::= IGNORE */
105126 {yygotominor.yy4 = OE_Ignore;}
105127 break;
105128 case 106: /* resolvetype ::= REPLACE */
105129 {yygotominor.yy4 = OE_Replace;}
105130 break;
105131 case 107: /* cmd ::= DROP TABLE ifexists fullname */
105133 sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
105135 break;
105136 case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
105138 sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy4, yymsp[-4].minor.yy4);
105140 break;
105141 case 111: /* cmd ::= DROP VIEW ifexists fullname */
105143 sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
105145 break;
105146 case 112: /* cmd ::= select */
105148 SelectDest dest = {SRT_Output, 0, 0, 0, 0};
105149 sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
105150 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
105152 break;
105153 case 113: /* select ::= oneselect */
105154 {yygotominor.yy387 = yymsp[0].minor.yy387;}
105155 break;
105156 case 114: /* select ::= select multiselect_op oneselect */
105158 if( yymsp[0].minor.yy387 ){
105159 yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
105160 yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
105161 }else{
105162 sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
105164 yygotominor.yy387 = yymsp[0].minor.yy387;
105166 break;
105167 case 116: /* multiselect_op ::= UNION ALL */
105168 {yygotominor.yy4 = TK_ALL;}
105169 break;
105170 case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
105172 yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
105174 break;
105175 case 122: /* sclp ::= selcollist COMMA */
105176 case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
105177 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
105178 break;
105179 case 123: /* sclp ::= */
105180 case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
105181 case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
105182 case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
105183 case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
105184 {yygotominor.yy322 = 0;}
105185 break;
105186 case 124: /* selcollist ::= sclp expr as */
105188 yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
105189 if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
105190 sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
105192 break;
105193 case 125: /* selcollist ::= sclp STAR */
105195 Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
105196 yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
105198 break;
105199 case 126: /* selcollist ::= sclp nm DOT STAR */
105201 Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
105202 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105203 Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
105204 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
105206 break;
105207 case 129: /* as ::= */
105208 {yygotominor.yy0.n = 0;}
105209 break;
105210 case 130: /* from ::= */
105211 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
105212 break;
105213 case 131: /* from ::= FROM seltablist */
105215 yygotominor.yy259 = yymsp[0].minor.yy259;
105216 sqlite3SrcListShiftJoinType(yygotominor.yy259);
105218 break;
105219 case 132: /* stl_prefix ::= seltablist joinop */
105221 yygotominor.yy259 = yymsp[-1].minor.yy259;
105222 if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
105224 break;
105225 case 133: /* stl_prefix ::= */
105226 {yygotominor.yy259 = 0;}
105227 break;
105228 case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
105230 yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
105231 sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
105233 break;
105234 case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
105236 yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
105238 break;
105239 case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
105241 if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
105242 yygotominor.yy259 = yymsp[-4].minor.yy259;
105243 }else{
105244 Select *pSubquery;
105245 sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
105246 pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
105247 yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
105250 break;
105251 case 137: /* dbnm ::= */
105252 case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
105253 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
105254 break;
105255 case 139: /* fullname ::= nm dbnm */
105256 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
105257 break;
105258 case 140: /* joinop ::= COMMA|JOIN */
105259 { yygotominor.yy4 = JT_INNER; }
105260 break;
105261 case 141: /* joinop ::= JOIN_KW JOIN */
105262 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
105263 break;
105264 case 142: /* joinop ::= JOIN_KW nm JOIN */
105265 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
105266 break;
105267 case 143: /* joinop ::= JOIN_KW nm nm JOIN */
105268 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
105269 break;
105270 case 144: /* on_opt ::= ON expr */
105271 case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
105272 case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
105273 case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
105274 case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
105275 case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
105276 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
105277 break;
105278 case 145: /* on_opt ::= */
105279 case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
105280 case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
105281 case 236: /* case_else ::= */ yytestcase(yyruleno==236);
105282 case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
105283 {yygotominor.yy314 = 0;}
105284 break;
105285 case 148: /* indexed_opt ::= NOT INDEXED */
105286 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
105287 break;
105288 case 149: /* using_opt ::= USING LP inscollist RP */
105289 case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
105290 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
105291 break;
105292 case 150: /* using_opt ::= */
105293 case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
105294 {yygotominor.yy384 = 0;}
105295 break;
105296 case 152: /* orderby_opt ::= ORDER BY sortlist */
105297 case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
105298 case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
105299 {yygotominor.yy322 = yymsp[0].minor.yy322;}
105300 break;
105301 case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
105303 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
105304 if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105306 break;
105307 case 154: /* sortlist ::= sortitem sortorder */
105309 yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
105310 if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
105312 break;
105313 case 156: /* sortorder ::= ASC */
105314 case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
105315 {yygotominor.yy4 = SQLITE_SO_ASC;}
105316 break;
105317 case 157: /* sortorder ::= DESC */
105318 {yygotominor.yy4 = SQLITE_SO_DESC;}
105319 break;
105320 case 163: /* limit_opt ::= */
105321 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
105322 break;
105323 case 164: /* limit_opt ::= LIMIT expr */
105324 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
105325 break;
105326 case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
105327 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
105328 break;
105329 case 166: /* limit_opt ::= LIMIT expr COMMA expr */
105330 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
105331 break;
105332 case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
105334 sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
105335 sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
105337 break;
105338 case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
105340 sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
105341 sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
105342 sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
105344 break;
105345 case 171: /* setlist ::= setlist COMMA nm EQ expr */
105347 yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
105348 sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105350 break;
105351 case 172: /* setlist ::= nm EQ expr */
105353 yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
105354 sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105356 break;
105357 case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
105358 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
105359 break;
105360 case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
105361 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
105362 break;
105363 case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
105364 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
105365 break;
105366 case 176: /* insert_cmd ::= INSERT orconf */
105367 {yygotominor.yy210 = yymsp[0].minor.yy210;}
105368 break;
105369 case 177: /* insert_cmd ::= REPLACE */
105370 {yygotominor.yy210 = OE_Replace;}
105371 break;
105372 case 178: /* itemlist ::= itemlist COMMA expr */
105373 case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
105374 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
105375 break;
105376 case 179: /* itemlist ::= expr */
105377 case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
105378 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
105379 break;
105380 case 182: /* inscollist ::= inscollist COMMA nm */
105381 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
105382 break;
105383 case 183: /* inscollist ::= nm */
105384 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
105385 break;
105386 case 184: /* expr ::= term */
105387 {yygotominor.yy118 = yymsp[0].minor.yy118;}
105388 break;
105389 case 185: /* expr ::= LP expr RP */
105390 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
105391 break;
105392 case 186: /* term ::= NULL */
105393 case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
105394 case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
105395 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
105396 break;
105397 case 187: /* expr ::= id */
105398 case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
105399 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
105400 break;
105401 case 189: /* expr ::= nm DOT nm */
105403 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105404 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105405 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
105406 spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
105408 break;
105409 case 190: /* expr ::= nm DOT nm DOT nm */
105411 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
105412 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105413 Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105414 Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
105415 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
105416 spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105418 break;
105419 case 193: /* expr ::= REGISTER */
105421 /* When doing a nested parse, one can include terms in an expression
105422 ** that look like this: #1 #2 ... These terms refer to registers
105423 ** in the virtual machine. #N is the N-th register. */
105424 if( pParse->nested==0 ){
105425 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
105426 yygotominor.yy118.pExpr = 0;
105427 }else{
105428 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
105429 if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
105431 spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105433 break;
105434 case 194: /* expr ::= VARIABLE */
105436 spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
105437 sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
105438 spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105440 break;
105441 case 195: /* expr ::= expr COLLATE ids */
105443 yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
105444 yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
105445 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105447 break;
105448 case 196: /* expr ::= CAST LP expr AS typetoken RP */
105450 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
105451 spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
105453 break;
105454 case 197: /* expr ::= ID LP distinct exprlist RP */
105456 if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
105457 sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
105459 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
105460 spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105461 if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
105462 yygotominor.yy118.pExpr->flags |= EP_Distinct;
105465 break;
105466 case 198: /* expr ::= ID LP STAR RP */
105468 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
105469 spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
105471 break;
105472 case 199: /* term ::= CTIME_KW */
105474 /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
105475 ** treated as functions that return constants */
105476 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
105477 if( yygotominor.yy118.pExpr ){
105478 yygotominor.yy118.pExpr->op = TK_CONST_FUNC;
105480 spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105482 break;
105483 case 200: /* expr ::= expr AND expr */
105484 case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
105485 case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
105486 case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
105487 case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
105488 case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
105489 case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
105490 case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
105491 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
105492 break;
105493 case 208: /* likeop ::= LIKE_KW */
105494 case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
105495 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
105496 break;
105497 case 209: /* likeop ::= NOT LIKE_KW */
105498 case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
105499 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
105500 break;
105501 case 212: /* expr ::= expr likeop expr */
105503 ExprList *pList;
105504 pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
105505 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
105506 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
105507 if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105508 yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
105509 yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105510 if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
105512 break;
105513 case 213: /* expr ::= expr likeop expr ESCAPE expr */
105515 ExprList *pList;
105516 pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105517 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
105518 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
105519 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
105520 if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105521 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105522 yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105523 if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
105525 break;
105526 case 214: /* expr ::= expr ISNULL|NOTNULL */
105527 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
105528 break;
105529 case 215: /* expr ::= expr NOT NULL */
105530 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
105531 break;
105532 case 216: /* expr ::= expr IS expr */
105534 spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
105535 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
105537 break;
105538 case 217: /* expr ::= expr IS NOT expr */
105540 spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
105541 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
105543 break;
105544 case 218: /* expr ::= NOT expr */
105545 case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
105546 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105547 break;
105548 case 220: /* expr ::= MINUS expr */
105549 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105550 break;
105551 case 221: /* expr ::= PLUS expr */
105552 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105553 break;
105554 case 224: /* expr ::= expr between_op expr AND expr */
105556 ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105557 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
105558 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105559 if( yygotominor.yy118.pExpr ){
105560 yygotominor.yy118.pExpr->x.pList = pList;
105561 }else{
105562 sqlite3ExprListDelete(pParse->db, pList);
105564 if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105565 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105566 yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105568 break;
105569 case 227: /* expr ::= expr in_op LP exprlist RP */
105571 if( yymsp[-1].minor.yy322==0 ){
105572 /* Expressions of the form
105574 ** expr1 IN ()
105575 ** expr1 NOT IN ()
105577 ** simplify to constants 0 (false) and 1 (true), respectively,
105578 ** regardless of the value of expr1.
105580 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
105581 sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
105582 }else{
105583 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105584 if( yygotominor.yy118.pExpr ){
105585 yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
105586 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105587 }else{
105588 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
105590 if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105592 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105593 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105595 break;
105596 case 228: /* expr ::= LP select RP */
105598 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
105599 if( yygotominor.yy118.pExpr ){
105600 yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
105601 ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105602 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105603 }else{
105604 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105606 yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
105607 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105609 break;
105610 case 229: /* expr ::= expr in_op LP select RP */
105612 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105613 if( yygotominor.yy118.pExpr ){
105614 yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
105615 ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105616 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105617 }else{
105618 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105620 if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105621 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105622 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105624 break;
105625 case 230: /* expr ::= expr in_op nm dbnm */
105627 SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
105628 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
105629 if( yygotominor.yy118.pExpr ){
105630 yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
105631 ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105632 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105633 }else{
105634 sqlite3SrcListDelete(pParse->db, pSrc);
105636 if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105637 yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
105638 yygotominor.yy118.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];
105640 break;
105641 case 231: /* expr ::= EXISTS LP select RP */
105643 Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
105644 if( p ){
105645 p->x.pSelect = yymsp[-1].minor.yy387;
105646 ExprSetProperty(p, EP_xIsSelect);
105647 sqlite3ExprSetHeight(pParse, p);
105648 }else{
105649 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105651 yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
105652 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105654 break;
105655 case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
105657 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
105658 if( yygotominor.yy118.pExpr ){
105659 yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
105660 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105661 }else{
105662 sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
105664 yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
105665 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105667 break;
105668 case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
105670 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
105671 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
105673 break;
105674 case 234: /* case_exprlist ::= WHEN expr THEN expr */
105676 yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105677 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
105679 break;
105680 case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
105682 sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
105683 sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
105684 &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
105686 break;
105687 case 244: /* uniqueflag ::= UNIQUE */
105688 case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
105689 {yygotominor.yy4 = OE_Abort;}
105690 break;
105691 case 245: /* uniqueflag ::= */
105692 {yygotominor.yy4 = OE_None;}
105693 break;
105694 case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
105696 Expr *p = 0;
105697 if( yymsp[-1].minor.yy0.n>0 ){
105698 p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
105699 sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
105701 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
105702 sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
105703 sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
105704 if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105706 break;
105707 case 249: /* idxlist ::= nm collate sortorder */
105709 Expr *p = 0;
105710 if( yymsp[-1].minor.yy0.n>0 ){
105711 p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
105712 sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
105714 yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
105715 sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105716 sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
105717 if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105719 break;
105720 case 250: /* collate ::= */
105721 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
105722 break;
105723 case 252: /* cmd ::= DROP INDEX ifexists fullname */
105724 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
105725 break;
105726 case 253: /* cmd ::= VACUUM */
105727 case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
105728 {sqlite3Vacuum(pParse);}
105729 break;
105730 case 255: /* cmd ::= PRAGMA nm dbnm */
105731 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
105732 break;
105733 case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
105734 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
105735 break;
105736 case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
105737 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
105738 break;
105739 case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
105740 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
105741 break;
105742 case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
105743 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
105744 break;
105745 case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
105747 Token all;
105748 all.z = yymsp[-3].minor.yy0.z;
105749 all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
105750 sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
105752 break;
105753 case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
105755 sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
105756 yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
105758 break;
105759 case 272: /* trigger_time ::= BEFORE */
105760 case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
105761 { yygotominor.yy4 = TK_BEFORE; }
105762 break;
105763 case 273: /* trigger_time ::= AFTER */
105764 { yygotominor.yy4 = TK_AFTER; }
105765 break;
105766 case 274: /* trigger_time ::= INSTEAD OF */
105767 { yygotominor.yy4 = TK_INSTEAD;}
105768 break;
105769 case 276: /* trigger_event ::= DELETE|INSERT */
105770 case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
105771 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
105772 break;
105773 case 278: /* trigger_event ::= UPDATE OF inscollist */
105774 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
105775 break;
105776 case 281: /* when_clause ::= */
105777 case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
105778 { yygotominor.yy314 = 0; }
105779 break;
105780 case 282: /* when_clause ::= WHEN expr */
105781 case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
105782 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
105783 break;
105784 case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
105786 assert( yymsp[-2].minor.yy203!=0 );
105787 yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
105788 yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
105789 yygotominor.yy203 = yymsp[-2].minor.yy203;
105791 break;
105792 case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
105794 assert( yymsp[-1].minor.yy203!=0 );
105795 yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
105796 yygotominor.yy203 = yymsp[-1].minor.yy203;
105798 break;
105799 case 286: /* trnm ::= nm DOT nm */
105801 yygotominor.yy0 = yymsp[0].minor.yy0;
105802 sqlite3ErrorMsg(pParse,
105803 "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
105804 "statements within triggers");
105806 break;
105807 case 288: /* tridxby ::= INDEXED BY nm */
105809 sqlite3ErrorMsg(pParse,
105810 "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
105811 "within triggers");
105813 break;
105814 case 289: /* tridxby ::= NOT INDEXED */
105816 sqlite3ErrorMsg(pParse,
105817 "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
105818 "within triggers");
105820 break;
105821 case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
105822 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
105823 break;
105824 case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
105825 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
105826 break;
105827 case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
105828 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
105829 break;
105830 case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
105831 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
105832 break;
105833 case 294: /* trigger_cmd ::= select */
105834 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
105835 break;
105836 case 295: /* expr ::= RAISE LP IGNORE RP */
105838 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
105839 if( yygotominor.yy118.pExpr ){
105840 yygotominor.yy118.pExpr->affinity = OE_Ignore;
105842 yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
105843 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105845 break;
105846 case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
105848 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
105849 if( yygotominor.yy118.pExpr ) {
105850 yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
105852 yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
105853 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105855 break;
105856 case 297: /* raisetype ::= ROLLBACK */
105857 {yygotominor.yy4 = OE_Rollback;}
105858 break;
105859 case 299: /* raisetype ::= FAIL */
105860 {yygotominor.yy4 = OE_Fail;}
105861 break;
105862 case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
105864 sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
105866 break;
105867 case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
105869 sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
105871 break;
105872 case 302: /* cmd ::= DETACH database_kw_opt expr */
105874 sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
105876 break;
105877 case 307: /* cmd ::= REINDEX */
105878 {sqlite3Reindex(pParse, 0, 0);}
105879 break;
105880 case 308: /* cmd ::= REINDEX nm dbnm */
105881 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
105882 break;
105883 case 309: /* cmd ::= ANALYZE */
105884 {sqlite3Analyze(pParse, 0, 0);}
105885 break;
105886 case 310: /* cmd ::= ANALYZE nm dbnm */
105887 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
105888 break;
105889 case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
105891 sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
105893 break;
105894 case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
105896 sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
105898 break;
105899 case 313: /* add_column_fullname ::= fullname */
105901 pParse->db->lookaside.bEnabled = 0;
105902 sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
105904 break;
105905 case 316: /* cmd ::= create_vtab */
105906 {sqlite3VtabFinishParse(pParse,0);}
105907 break;
105908 case 317: /* cmd ::= create_vtab LP vtabarglist RP */
105909 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
105910 break;
105911 case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
105913 sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
105915 break;
105916 case 321: /* vtabarg ::= */
105917 {sqlite3VtabArgInit(pParse);}
105918 break;
105919 case 323: /* vtabargtoken ::= ANY */
105920 case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
105921 case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
105922 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
105923 break;
105924 default:
105925 /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
105926 /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
105927 /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
105928 /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
105929 /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
105930 /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
105931 /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
105932 /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
105933 /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
105934 /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
105935 /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
105936 /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
105937 /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
105938 /* (44) type ::= */ yytestcase(yyruleno==44);
105939 /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
105940 /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
105941 /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
105942 /* (54) carglist ::= */ yytestcase(yyruleno==54);
105943 /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
105944 /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
105945 /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
105946 /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
105947 /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
105948 /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
105949 /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
105950 /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
105951 /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
105952 /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
105953 /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
105954 /* (287) tridxby ::= */ yytestcase(yyruleno==287);
105955 /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
105956 /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
105957 /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
105958 /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
105959 /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
105960 /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
105961 /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
105962 /* (326) anylist ::= */ yytestcase(yyruleno==326);
105963 /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
105964 /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
105965 break;
105967 yygoto = yyRuleInfo[yyruleno].lhs;
105968 yysize = yyRuleInfo[yyruleno].nrhs;
105969 yypParser->yyidx -= yysize;
105970 yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
105971 if( yyact < YYNSTATE ){
105972 #ifdef NDEBUG
105973 /* If we are not debugging and the reduce action popped at least
105974 ** one element off the stack, then we can push the new element back
105975 ** onto the stack here, and skip the stack overflow test in yy_shift().
105976 ** That gives a significant speed improvement. */
105977 if( yysize ){
105978 yypParser->yyidx++;
105979 yymsp -= yysize-1;
105980 yymsp->stateno = (YYACTIONTYPE)yyact;
105981 yymsp->major = (YYCODETYPE)yygoto;
105982 yymsp->minor = yygotominor;
105983 }else
105984 #endif
105986 yy_shift(yypParser,yyact,yygoto,&yygotominor);
105988 }else{
105989 assert( yyact == YYNSTATE + YYNRULE + 1 );
105990 yy_accept(yypParser);
105995 ** The following code executes when the parse fails
105997 #ifndef YYNOERRORRECOVERY
105998 static void yy_parse_failed(
105999 yyParser *yypParser /* The parser */
106001 sqlite3ParserARG_FETCH;
106002 #ifndef NDEBUG
106003 if( yyTraceFILE ){
106004 fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
106006 #endif
106007 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
106008 /* Here code is inserted which will be executed whenever the
106009 ** parser fails */
106010 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
106012 #endif /* YYNOERRORRECOVERY */
106015 ** The following code executes when a syntax error first occurs.
106017 static void yy_syntax_error(
106018 yyParser *yypParser, /* The parser */
106019 int yymajor, /* The major type of the error token */
106020 YYMINORTYPE yyminor /* The minor type of the error token */
106022 sqlite3ParserARG_FETCH;
106023 #define TOKEN (yyminor.yy0)
106025 UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
106026 assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
106027 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
106028 pParse->parseError = 1;
106029 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
106033 ** The following is executed when the parser accepts
106035 static void yy_accept(
106036 yyParser *yypParser /* The parser */
106038 sqlite3ParserARG_FETCH;
106039 #ifndef NDEBUG
106040 if( yyTraceFILE ){
106041 fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
106043 #endif
106044 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
106045 /* Here code is inserted which will be executed whenever the
106046 ** parser accepts */
106047 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
106050 /* The main parser program.
106051 ** The first argument is a pointer to a structure obtained from
106052 ** "sqlite3ParserAlloc" which describes the current state of the parser.
106053 ** The second argument is the major token number. The third is
106054 ** the minor token. The fourth optional argument is whatever the
106055 ** user wants (and specified in the grammar) and is available for
106056 ** use by the action routines.
106058 ** Inputs:
106059 ** <ul>
106060 ** <li> A pointer to the parser (an opaque structure.)
106061 ** <li> The major token number.
106062 ** <li> The minor token number.
106063 ** <li> An option argument of a grammar-specified type.
106064 ** </ul>
106066 ** Outputs:
106067 ** None.
106069 SQLITE_PRIVATE void sqlite3Parser(
106070 void *yyp, /* The parser */
106071 int yymajor, /* The major token code number */
106072 sqlite3ParserTOKENTYPE yyminor /* The value for the token */
106073 sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
106075 YYMINORTYPE yyminorunion;
106076 int yyact; /* The parser action. */
106077 int yyendofinput; /* True if we are at the end of input */
106078 #ifdef YYERRORSYMBOL
106079 int yyerrorhit = 0; /* True if yymajor has invoked an error */
106080 #endif
106081 yyParser *yypParser; /* The parser */
106083 /* (re)initialize the parser, if necessary */
106084 yypParser = (yyParser*)yyp;
106085 if( yypParser->yyidx<0 ){
106086 #if YYSTACKDEPTH<=0
106087 if( yypParser->yystksz <=0 ){
106088 /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
106089 yyminorunion = yyzerominor;
106090 yyStackOverflow(yypParser, &yyminorunion);
106091 return;
106093 #endif
106094 yypParser->yyidx = 0;
106095 yypParser->yyerrcnt = -1;
106096 yypParser->yystack[0].stateno = 0;
106097 yypParser->yystack[0].major = 0;
106099 yyminorunion.yy0 = yyminor;
106100 yyendofinput = (yymajor==0);
106101 sqlite3ParserARG_STORE;
106103 #ifndef NDEBUG
106104 if( yyTraceFILE ){
106105 fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
106107 #endif
106110 yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
106111 if( yyact<YYNSTATE ){
106112 assert( !yyendofinput ); /* Impossible to shift the $ token */
106113 yy_shift(yypParser,yyact,yymajor,&yyminorunion);
106114 yypParser->yyerrcnt--;
106115 yymajor = YYNOCODE;
106116 }else if( yyact < YYNSTATE + YYNRULE ){
106117 yy_reduce(yypParser,yyact-YYNSTATE);
106118 }else{
106119 assert( yyact == YY_ERROR_ACTION );
106120 #ifdef YYERRORSYMBOL
106121 int yymx;
106122 #endif
106123 #ifndef NDEBUG
106124 if( yyTraceFILE ){
106125 fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
106127 #endif
106128 #ifdef YYERRORSYMBOL
106129 /* A syntax error has occurred.
106130 ** The response to an error depends upon whether or not the
106131 ** grammar defines an error token "ERROR".
106133 ** This is what we do if the grammar does define ERROR:
106135 ** * Call the %syntax_error function.
106137 ** * Begin popping the stack until we enter a state where
106138 ** it is legal to shift the error symbol, then shift
106139 ** the error symbol.
106141 ** * Set the error count to three.
106143 ** * Begin accepting and shifting new tokens. No new error
106144 ** processing will occur until three tokens have been
106145 ** shifted successfully.
106148 if( yypParser->yyerrcnt<0 ){
106149 yy_syntax_error(yypParser,yymajor,yyminorunion);
106151 yymx = yypParser->yystack[yypParser->yyidx].major;
106152 if( yymx==YYERRORSYMBOL || yyerrorhit ){
106153 #ifndef NDEBUG
106154 if( yyTraceFILE ){
106155 fprintf(yyTraceFILE,"%sDiscard input token %s\n",
106156 yyTracePrompt,yyTokenName[yymajor]);
106158 #endif
106159 yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
106160 yymajor = YYNOCODE;
106161 }else{
106162 while(
106163 yypParser->yyidx >= 0 &&
106164 yymx != YYERRORSYMBOL &&
106165 (yyact = yy_find_reduce_action(
106166 yypParser->yystack[yypParser->yyidx].stateno,
106167 YYERRORSYMBOL)) >= YYNSTATE
106169 yy_pop_parser_stack(yypParser);
106171 if( yypParser->yyidx < 0 || yymajor==0 ){
106172 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106173 yy_parse_failed(yypParser);
106174 yymajor = YYNOCODE;
106175 }else if( yymx!=YYERRORSYMBOL ){
106176 YYMINORTYPE u2;
106177 u2.YYERRSYMDT = 0;
106178 yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
106181 yypParser->yyerrcnt = 3;
106182 yyerrorhit = 1;
106183 #elif defined(YYNOERRORRECOVERY)
106184 /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
106185 ** do any kind of error recovery. Instead, simply invoke the syntax
106186 ** error routine and continue going as if nothing had happened.
106188 ** Applications can set this macro (for example inside %include) if
106189 ** they intend to abandon the parse upon the first syntax error seen.
106191 yy_syntax_error(yypParser,yymajor,yyminorunion);
106192 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106193 yymajor = YYNOCODE;
106195 #else /* YYERRORSYMBOL is not defined */
106196 /* This is what we do if the grammar does not define ERROR:
106198 ** * Report an error message, and throw away the input token.
106200 ** * If the input token is $, then fail the parse.
106202 ** As before, subsequent error messages are suppressed until
106203 ** three input tokens have been successfully shifted.
106205 if( yypParser->yyerrcnt<=0 ){
106206 yy_syntax_error(yypParser,yymajor,yyminorunion);
106208 yypParser->yyerrcnt = 3;
106209 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106210 if( yyendofinput ){
106211 yy_parse_failed(yypParser);
106213 yymajor = YYNOCODE;
106214 #endif
106216 }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
106217 return;
106220 /************** End of parse.c ***********************************************/
106221 /************** Begin file tokenize.c ****************************************/
106223 ** 2001 September 15
106225 ** The author disclaims copyright to this source code. In place of
106226 ** a legal notice, here is a blessing:
106228 ** May you do good and not evil.
106229 ** May you find forgiveness for yourself and forgive others.
106230 ** May you share freely, never taking more than you give.
106232 *************************************************************************
106233 ** An tokenizer for SQL
106235 ** This file contains C code that splits an SQL input string up into
106236 ** individual tokens and sends those tokens one-by-one over to the
106237 ** parser for analysis.
106241 ** The charMap() macro maps alphabetic characters into their
106242 ** lower-case ASCII equivalent. On ASCII machines, this is just
106243 ** an upper-to-lower case map. On EBCDIC machines we also need
106244 ** to adjust the encoding. Only alphabetic characters and underscores
106245 ** need to be translated.
106247 #ifdef SQLITE_ASCII
106248 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
106249 #endif
106250 #ifdef SQLITE_EBCDIC
106251 # define charMap(X) ebcdicToAscii[(unsigned char)X]
106252 const unsigned char ebcdicToAscii[] = {
106253 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
106254 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
106255 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
106256 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
106257 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
106258 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
106259 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
106260 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
106261 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
106262 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
106263 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
106264 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
106265 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
106266 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
106267 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
106268 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
106269 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
106271 #endif
106274 ** The sqlite3KeywordCode function looks up an identifier to determine if
106275 ** it is a keyword. If it is a keyword, the token code of that keyword is
106276 ** returned. If the input is not a keyword, TK_ID is returned.
106278 ** The implementation of this routine was generated by a program,
106279 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
106280 ** The output of the mkkeywordhash.c program is written into a file
106281 ** named keywordhash.h and then included into this source file by
106282 ** the #include below.
106284 /************** Include keywordhash.h in the middle of tokenize.c ************/
106285 /************** Begin file keywordhash.h *************************************/
106286 /***** This file contains automatically generated code ******
106288 ** The code in this file has been automatically generated by
106290 ** sqlite/tool/mkkeywordhash.c
106292 ** The code in this file implements a function that determines whether
106293 ** or not a given identifier is really an SQL keyword. The same thing
106294 ** might be implemented more directly using a hand-written hash table.
106295 ** But by using this automatically generated code, the size of the code
106296 ** is substantially reduced. This is important for embedded applications
106297 ** on platforms with limited memory.
106299 /* Hash score: 175 */
106300 static int keywordCode(const char *z, int n){
106301 /* zText[] encodes 811 bytes of keywords in 541 bytes */
106302 /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
106303 /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
106304 /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
106305 /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
106306 /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
106307 /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
106308 /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
106309 /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
106310 /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
106311 /* INITIALLY */
106312 static const char zText[540] = {
106313 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
106314 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
106315 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
106316 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
106317 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
106318 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
106319 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
106320 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
106321 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
106322 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
106323 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
106324 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
106325 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
106326 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
106327 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
106328 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
106329 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
106330 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
106331 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
106332 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
106333 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
106334 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
106335 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
106336 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
106337 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
106338 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
106339 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
106340 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
106341 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
106342 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
106344 static const unsigned char aHash[127] = {
106345 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
106346 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
106347 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
106348 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
106349 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
106350 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
106351 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
106352 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
106353 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
106354 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
106356 static const unsigned char aNext[121] = {
106357 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
106358 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
106359 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
106360 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
106361 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
106362 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
106363 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
106364 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
106365 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
106366 35, 64, 0, 0,
106368 static const unsigned char aLen[121] = {
106369 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
106370 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
106371 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
106372 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
106373 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
106374 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
106375 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
106376 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
106377 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
106378 6, 4, 9, 3,
106380 static const unsigned short int aOffset[121] = {
106381 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
106382 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
106383 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
106384 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
106385 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
106386 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
106387 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
106388 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
106389 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
106390 521, 527, 531, 536,
106392 static const unsigned char aCode[121] = {
106393 TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
106394 TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
106395 TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
106396 TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
106397 TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
106398 TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
106399 TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
106400 TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
106401 TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
106402 TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
106403 TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
106404 TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
106405 TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
106406 TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
106407 TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
106408 TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
106409 TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
106410 TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
106411 TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
106412 TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
106413 TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
106414 TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
106415 TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
106416 TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
106417 TK_ALL,
106419 int h, i;
106420 if( n<2 ) return TK_ID;
106421 h = ((charMap(z[0])*4) ^
106422 (charMap(z[n-1])*3) ^
106423 n) % 127;
106424 for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
106425 if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
106426 testcase( i==0 ); /* REINDEX */
106427 testcase( i==1 ); /* INDEXED */
106428 testcase( i==2 ); /* INDEX */
106429 testcase( i==3 ); /* DESC */
106430 testcase( i==4 ); /* ESCAPE */
106431 testcase( i==5 ); /* EACH */
106432 testcase( i==6 ); /* CHECK */
106433 testcase( i==7 ); /* KEY */
106434 testcase( i==8 ); /* BEFORE */
106435 testcase( i==9 ); /* FOREIGN */
106436 testcase( i==10 ); /* FOR */
106437 testcase( i==11 ); /* IGNORE */
106438 testcase( i==12 ); /* REGEXP */
106439 testcase( i==13 ); /* EXPLAIN */
106440 testcase( i==14 ); /* INSTEAD */
106441 testcase( i==15 ); /* ADD */
106442 testcase( i==16 ); /* DATABASE */
106443 testcase( i==17 ); /* AS */
106444 testcase( i==18 ); /* SELECT */
106445 testcase( i==19 ); /* TABLE */
106446 testcase( i==20 ); /* LEFT */
106447 testcase( i==21 ); /* THEN */
106448 testcase( i==22 ); /* END */
106449 testcase( i==23 ); /* DEFERRABLE */
106450 testcase( i==24 ); /* ELSE */
106451 testcase( i==25 ); /* EXCEPT */
106452 testcase( i==26 ); /* TRANSACTION */
106453 testcase( i==27 ); /* ACTION */
106454 testcase( i==28 ); /* ON */
106455 testcase( i==29 ); /* NATURAL */
106456 testcase( i==30 ); /* ALTER */
106457 testcase( i==31 ); /* RAISE */
106458 testcase( i==32 ); /* EXCLUSIVE */
106459 testcase( i==33 ); /* EXISTS */
106460 testcase( i==34 ); /* SAVEPOINT */
106461 testcase( i==35 ); /* INTERSECT */
106462 testcase( i==36 ); /* TRIGGER */
106463 testcase( i==37 ); /* REFERENCES */
106464 testcase( i==38 ); /* CONSTRAINT */
106465 testcase( i==39 ); /* INTO */
106466 testcase( i==40 ); /* OFFSET */
106467 testcase( i==41 ); /* OF */
106468 testcase( i==42 ); /* SET */
106469 testcase( i==43 ); /* TEMPORARY */
106470 testcase( i==44 ); /* TEMP */
106471 testcase( i==45 ); /* OR */
106472 testcase( i==46 ); /* UNIQUE */
106473 testcase( i==47 ); /* QUERY */
106474 testcase( i==48 ); /* ATTACH */
106475 testcase( i==49 ); /* HAVING */
106476 testcase( i==50 ); /* GROUP */
106477 testcase( i==51 ); /* UPDATE */
106478 testcase( i==52 ); /* BEGIN */
106479 testcase( i==53 ); /* INNER */
106480 testcase( i==54 ); /* RELEASE */
106481 testcase( i==55 ); /* BETWEEN */
106482 testcase( i==56 ); /* NOTNULL */
106483 testcase( i==57 ); /* NOT */
106484 testcase( i==58 ); /* NO */
106485 testcase( i==59 ); /* NULL */
106486 testcase( i==60 ); /* LIKE */
106487 testcase( i==61 ); /* CASCADE */
106488 testcase( i==62 ); /* ASC */
106489 testcase( i==63 ); /* DELETE */
106490 testcase( i==64 ); /* CASE */
106491 testcase( i==65 ); /* COLLATE */
106492 testcase( i==66 ); /* CREATE */
106493 testcase( i==67 ); /* CURRENT_DATE */
106494 testcase( i==68 ); /* DETACH */
106495 testcase( i==69 ); /* IMMEDIATE */
106496 testcase( i==70 ); /* JOIN */
106497 testcase( i==71 ); /* INSERT */
106498 testcase( i==72 ); /* MATCH */
106499 testcase( i==73 ); /* PLAN */
106500 testcase( i==74 ); /* ANALYZE */
106501 testcase( i==75 ); /* PRAGMA */
106502 testcase( i==76 ); /* ABORT */
106503 testcase( i==77 ); /* VALUES */
106504 testcase( i==78 ); /* VIRTUAL */
106505 testcase( i==79 ); /* LIMIT */
106506 testcase( i==80 ); /* WHEN */
106507 testcase( i==81 ); /* WHERE */
106508 testcase( i==82 ); /* RENAME */
106509 testcase( i==83 ); /* AFTER */
106510 testcase( i==84 ); /* REPLACE */
106511 testcase( i==85 ); /* AND */
106512 testcase( i==86 ); /* DEFAULT */
106513 testcase( i==87 ); /* AUTOINCREMENT */
106514 testcase( i==88 ); /* TO */
106515 testcase( i==89 ); /* IN */
106516 testcase( i==90 ); /* CAST */
106517 testcase( i==91 ); /* COLUMN */
106518 testcase( i==92 ); /* COMMIT */
106519 testcase( i==93 ); /* CONFLICT */
106520 testcase( i==94 ); /* CROSS */
106521 testcase( i==95 ); /* CURRENT_TIMESTAMP */
106522 testcase( i==96 ); /* CURRENT_TIME */
106523 testcase( i==97 ); /* PRIMARY */
106524 testcase( i==98 ); /* DEFERRED */
106525 testcase( i==99 ); /* DISTINCT */
106526 testcase( i==100 ); /* IS */
106527 testcase( i==101 ); /* DROP */
106528 testcase( i==102 ); /* FAIL */
106529 testcase( i==103 ); /* FROM */
106530 testcase( i==104 ); /* FULL */
106531 testcase( i==105 ); /* GLOB */
106532 testcase( i==106 ); /* BY */
106533 testcase( i==107 ); /* IF */
106534 testcase( i==108 ); /* ISNULL */
106535 testcase( i==109 ); /* ORDER */
106536 testcase( i==110 ); /* RESTRICT */
106537 testcase( i==111 ); /* OUTER */
106538 testcase( i==112 ); /* RIGHT */
106539 testcase( i==113 ); /* ROLLBACK */
106540 testcase( i==114 ); /* ROW */
106541 testcase( i==115 ); /* UNION */
106542 testcase( i==116 ); /* USING */
106543 testcase( i==117 ); /* VACUUM */
106544 testcase( i==118 ); /* VIEW */
106545 testcase( i==119 ); /* INITIALLY */
106546 testcase( i==120 ); /* ALL */
106547 return aCode[i];
106550 return TK_ID;
106552 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
106553 return keywordCode((char*)z, n);
106555 #define SQLITE_N_KEYWORD 121
106557 /************** End of keywordhash.h *****************************************/
106558 /************** Continuing where we left off in tokenize.c *******************/
106562 ** If X is a character that can be used in an identifier then
106563 ** IdChar(X) will be true. Otherwise it is false.
106565 ** For ASCII, any character with the high-order bit set is
106566 ** allowed in an identifier. For 7-bit characters,
106567 ** sqlite3IsIdChar[X] must be 1.
106569 ** For EBCDIC, the rules are more complex but have the same
106570 ** end result.
106572 ** Ticket #1066. the SQL standard does not allow '$' in the
106573 ** middle of identfiers. But many SQL implementations do.
106574 ** SQLite will allow '$' in identifiers for compatibility.
106575 ** But the feature is undocumented.
106577 #ifdef SQLITE_ASCII
106578 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
106579 #endif
106580 #ifdef SQLITE_EBCDIC
106581 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
106582 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
106583 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
106584 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
106585 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
106586 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
106587 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
106588 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
106589 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
106590 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
106591 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
106592 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
106593 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
106594 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
106596 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
106597 #endif
106601 ** Return the length of the token that begins at z[0].
106602 ** Store the token type in *tokenType before returning.
106604 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
106605 int i, c;
106606 switch( *z ){
106607 case ' ': case '\t': case '\n': case '\f': case '\r': {
106608 testcase( z[0]==' ' );
106609 testcase( z[0]=='\t' );
106610 testcase( z[0]=='\n' );
106611 testcase( z[0]=='\f' );
106612 testcase( z[0]=='\r' );
106613 for(i=1; sqlite3Isspace(z[i]); i++){}
106614 *tokenType = TK_SPACE;
106615 return i;
106617 case '-': {
106618 if( z[1]=='-' ){
106619 /* IMP: R-15891-05542 -- syntax diagram for comments */
106620 for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
106621 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
106622 return i;
106624 *tokenType = TK_MINUS;
106625 return 1;
106627 case '(': {
106628 *tokenType = TK_LP;
106629 return 1;
106631 case ')': {
106632 *tokenType = TK_RP;
106633 return 1;
106635 case ';': {
106636 *tokenType = TK_SEMI;
106637 return 1;
106639 case '+': {
106640 *tokenType = TK_PLUS;
106641 return 1;
106643 case '*': {
106644 *tokenType = TK_STAR;
106645 return 1;
106647 case '/': {
106648 if( z[1]!='*' || z[2]==0 ){
106649 *tokenType = TK_SLASH;
106650 return 1;
106652 /* IMP: R-15891-05542 -- syntax diagram for comments */
106653 for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
106654 if( c ) i++;
106655 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
106656 return i;
106658 case '%': {
106659 *tokenType = TK_REM;
106660 return 1;
106662 case '=': {
106663 *tokenType = TK_EQ;
106664 return 1 + (z[1]=='=');
106666 case '<': {
106667 if( (c=z[1])=='=' ){
106668 *tokenType = TK_LE;
106669 return 2;
106670 }else if( c=='>' ){
106671 *tokenType = TK_NE;
106672 return 2;
106673 }else if( c=='<' ){
106674 *tokenType = TK_LSHIFT;
106675 return 2;
106676 }else{
106677 *tokenType = TK_LT;
106678 return 1;
106681 case '>': {
106682 if( (c=z[1])=='=' ){
106683 *tokenType = TK_GE;
106684 return 2;
106685 }else if( c=='>' ){
106686 *tokenType = TK_RSHIFT;
106687 return 2;
106688 }else{
106689 *tokenType = TK_GT;
106690 return 1;
106693 case '!': {
106694 if( z[1]!='=' ){
106695 *tokenType = TK_ILLEGAL;
106696 return 2;
106697 }else{
106698 *tokenType = TK_NE;
106699 return 2;
106702 case '|': {
106703 if( z[1]!='|' ){
106704 *tokenType = TK_BITOR;
106705 return 1;
106706 }else{
106707 *tokenType = TK_CONCAT;
106708 return 2;
106711 case ',': {
106712 *tokenType = TK_COMMA;
106713 return 1;
106715 case '&': {
106716 *tokenType = TK_BITAND;
106717 return 1;
106719 case '~': {
106720 *tokenType = TK_BITNOT;
106721 return 1;
106723 case '`':
106724 case '\'':
106725 case '"': {
106726 int delim = z[0];
106727 testcase( delim=='`' );
106728 testcase( delim=='\'' );
106729 testcase( delim=='"' );
106730 for(i=1; (c=z[i])!=0; i++){
106731 if( c==delim ){
106732 if( z[i+1]==delim ){
106734 }else{
106735 break;
106739 if( c=='\'' ){
106740 *tokenType = TK_STRING;
106741 return i+1;
106742 }else if( c!=0 ){
106743 *tokenType = TK_ID;
106744 return i+1;
106745 }else{
106746 *tokenType = TK_ILLEGAL;
106747 return i;
106750 case '.': {
106751 #ifndef SQLITE_OMIT_FLOATING_POINT
106752 if( !sqlite3Isdigit(z[1]) )
106753 #endif
106755 *tokenType = TK_DOT;
106756 return 1;
106758 /* If the next character is a digit, this is a floating point
106759 ** number that begins with ".". Fall thru into the next case */
106761 case '0': case '1': case '2': case '3': case '4':
106762 case '5': case '6': case '7': case '8': case '9': {
106763 testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
106764 testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
106765 testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
106766 testcase( z[0]=='9' );
106767 *tokenType = TK_INTEGER;
106768 for(i=0; sqlite3Isdigit(z[i]); i++){}
106769 #ifndef SQLITE_OMIT_FLOATING_POINT
106770 if( z[i]=='.' ){
106772 while( sqlite3Isdigit(z[i]) ){ i++; }
106773 *tokenType = TK_FLOAT;
106775 if( (z[i]=='e' || z[i]=='E') &&
106776 ( sqlite3Isdigit(z[i+1])
106777 || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
106780 i += 2;
106781 while( sqlite3Isdigit(z[i]) ){ i++; }
106782 *tokenType = TK_FLOAT;
106784 #endif
106785 while( IdChar(z[i]) ){
106786 *tokenType = TK_ILLEGAL;
106789 return i;
106791 case '[': {
106792 for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
106793 *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
106794 return i;
106796 case '?': {
106797 *tokenType = TK_VARIABLE;
106798 for(i=1; sqlite3Isdigit(z[i]); i++){}
106799 return i;
106801 case '#': {
106802 for(i=1; sqlite3Isdigit(z[i]); i++){}
106803 if( i>1 ){
106804 /* Parameters of the form #NNN (where NNN is a number) are used
106805 ** internally by sqlite3NestedParse. */
106806 *tokenType = TK_REGISTER;
106807 return i;
106809 /* Fall through into the next case if the '#' is not followed by
106810 ** a digit. Try to match #AAAA where AAAA is a parameter name. */
106812 #ifndef SQLITE_OMIT_TCL_VARIABLE
106813 case '$':
106814 #endif
106815 case '@': /* For compatibility with MS SQL Server */
106816 case ':': {
106817 int n = 0;
106818 testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
106819 *tokenType = TK_VARIABLE;
106820 for(i=1; (c=z[i])!=0; i++){
106821 if( IdChar(c) ){
106823 #ifndef SQLITE_OMIT_TCL_VARIABLE
106824 }else if( c=='(' && n>0 ){
106827 }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
106828 if( c==')' ){
106830 }else{
106831 *tokenType = TK_ILLEGAL;
106833 break;
106834 }else if( c==':' && z[i+1]==':' ){
106836 #endif
106837 }else{
106838 break;
106841 if( n==0 ) *tokenType = TK_ILLEGAL;
106842 return i;
106844 #ifndef SQLITE_OMIT_BLOB_LITERAL
106845 case 'x': case 'X': {
106846 testcase( z[0]=='x' ); testcase( z[0]=='X' );
106847 if( z[1]=='\'' ){
106848 *tokenType = TK_BLOB;
106849 for(i=2; (c=z[i])!=0 && c!='\''; i++){
106850 if( !sqlite3Isxdigit(c) ){
106851 *tokenType = TK_ILLEGAL;
106854 if( i%2 || !c ) *tokenType = TK_ILLEGAL;
106855 if( c ) i++;
106856 return i;
106858 /* Otherwise fall through to the next case */
106860 #endif
106861 default: {
106862 if( !IdChar(*z) ){
106863 break;
106865 for(i=1; IdChar(z[i]); i++){}
106866 *tokenType = keywordCode((char*)z, i);
106867 return i;
106870 *tokenType = TK_ILLEGAL;
106871 return 1;
106875 ** Run the parser on the given SQL string. The parser structure is
106876 ** passed in. An SQLITE_ status code is returned. If an error occurs
106877 ** then an and attempt is made to write an error message into
106878 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
106879 ** error message.
106881 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
106882 int nErr = 0; /* Number of errors encountered */
106883 int i; /* Loop counter */
106884 void *pEngine; /* The LEMON-generated LALR(1) parser */
106885 int tokenType; /* type of the next token */
106886 int lastTokenParsed = -1; /* type of the previous token */
106887 u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
106888 sqlite3 *db = pParse->db; /* The database connection */
106889 int mxSqlLen; /* Max length of an SQL string */
106892 mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
106893 if( db->activeVdbeCnt==0 ){
106894 db->u1.isInterrupted = 0;
106896 pParse->rc = SQLITE_OK;
106897 pParse->zTail = zSql;
106898 i = 0;
106899 assert( pzErrMsg!=0 );
106900 pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
106901 if( pEngine==0 ){
106902 db->mallocFailed = 1;
106903 return SQLITE_NOMEM;
106905 assert( pParse->pNewTable==0 );
106906 assert( pParse->pNewTrigger==0 );
106907 assert( pParse->nVar==0 );
106908 assert( pParse->nVarExpr==0 );
106909 assert( pParse->nVarExprAlloc==0 );
106910 assert( pParse->apVarExpr==0 );
106911 enableLookaside = db->lookaside.bEnabled;
106912 if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
106913 while( !db->mallocFailed && zSql[i]!=0 ){
106914 assert( i>=0 );
106915 pParse->sLastToken.z = &zSql[i];
106916 pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
106917 i += pParse->sLastToken.n;
106918 if( i>mxSqlLen ){
106919 pParse->rc = SQLITE_TOOBIG;
106920 break;
106922 switch( tokenType ){
106923 case TK_SPACE: {
106924 if( db->u1.isInterrupted ){
106925 sqlite3ErrorMsg(pParse, "interrupt");
106926 pParse->rc = SQLITE_INTERRUPT;
106927 goto abort_parse;
106929 break;
106931 case TK_ILLEGAL: {
106932 sqlite3DbFree(db, *pzErrMsg);
106933 *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
106934 &pParse->sLastToken);
106935 nErr++;
106936 goto abort_parse;
106938 case TK_SEMI: {
106939 pParse->zTail = &zSql[i];
106940 /* Fall thru into the default case */
106942 default: {
106943 sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
106944 lastTokenParsed = tokenType;
106945 if( pParse->rc!=SQLITE_OK ){
106946 goto abort_parse;
106948 break;
106952 abort_parse:
106953 if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
106954 if( lastTokenParsed!=TK_SEMI ){
106955 sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
106956 pParse->zTail = &zSql[i];
106958 sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
106960 #ifdef YYTRACKMAXSTACKDEPTH
106961 sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
106962 sqlite3ParserStackPeak(pEngine)
106964 #endif /* YYDEBUG */
106965 sqlite3ParserFree(pEngine, sqlite3_free);
106966 db->lookaside.bEnabled = enableLookaside;
106967 if( db->mallocFailed ){
106968 pParse->rc = SQLITE_NOMEM;
106970 if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
106971 sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
106973 assert( pzErrMsg!=0 );
106974 if( pParse->zErrMsg ){
106975 *pzErrMsg = pParse->zErrMsg;
106976 sqlite3_log(pParse->rc, "%s", *pzErrMsg);
106977 pParse->zErrMsg = 0;
106978 nErr++;
106980 if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
106981 sqlite3VdbeDelete(pParse->pVdbe);
106982 pParse->pVdbe = 0;
106984 #ifndef SQLITE_OMIT_SHARED_CACHE
106985 if( pParse->nested==0 ){
106986 sqlite3DbFree(db, pParse->aTableLock);
106987 pParse->aTableLock = 0;
106988 pParse->nTableLock = 0;
106990 #endif
106991 #ifndef SQLITE_OMIT_VIRTUALTABLE
106992 sqlite3_free(pParse->apVtabLock);
106993 #endif
106995 if( !IN_DECLARE_VTAB ){
106996 /* If the pParse->declareVtab flag is set, do not delete any table
106997 ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
106998 ** will take responsibility for freeing the Table structure.
107000 sqlite3DeleteTable(db, pParse->pNewTable);
107003 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
107004 sqlite3DbFree(db, pParse->apVarExpr);
107005 sqlite3DbFree(db, pParse->aAlias);
107006 while( pParse->pAinc ){
107007 AutoincInfo *p = pParse->pAinc;
107008 pParse->pAinc = p->pNext;
107009 sqlite3DbFree(db, p);
107011 while( pParse->pZombieTab ){
107012 Table *p = pParse->pZombieTab;
107013 pParse->pZombieTab = p->pNextZombie;
107014 sqlite3DeleteTable(db, p);
107016 if( nErr>0 && pParse->rc==SQLITE_OK ){
107017 pParse->rc = SQLITE_ERROR;
107019 return nErr;
107022 /************** End of tokenize.c ********************************************/
107023 /************** Begin file complete.c ****************************************/
107025 ** 2001 September 15
107027 ** The author disclaims copyright to this source code. In place of
107028 ** a legal notice, here is a blessing:
107030 ** May you do good and not evil.
107031 ** May you find forgiveness for yourself and forgive others.
107032 ** May you share freely, never taking more than you give.
107034 *************************************************************************
107035 ** An tokenizer for SQL
107037 ** This file contains C code that implements the sqlite3_complete() API.
107038 ** This code used to be part of the tokenizer.c source file. But by
107039 ** separating it out, the code will be automatically omitted from
107040 ** static links that do not use it.
107042 #ifndef SQLITE_OMIT_COMPLETE
107045 ** This is defined in tokenize.c. We just have to import the definition.
107047 #ifndef SQLITE_AMALGAMATION
107048 #ifdef SQLITE_ASCII
107049 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
107050 #endif
107051 #ifdef SQLITE_EBCDIC
107052 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
107053 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
107054 #endif
107055 #endif /* SQLITE_AMALGAMATION */
107059 ** Token types used by the sqlite3_complete() routine. See the header
107060 ** comments on that procedure for additional information.
107062 #define tkSEMI 0
107063 #define tkWS 1
107064 #define tkOTHER 2
107065 #ifndef SQLITE_OMIT_TRIGGER
107066 #define tkEXPLAIN 3
107067 #define tkCREATE 4
107068 #define tkTEMP 5
107069 #define tkTRIGGER 6
107070 #define tkEND 7
107071 #endif
107074 ** Return TRUE if the given SQL string ends in a semicolon.
107076 ** Special handling is require for CREATE TRIGGER statements.
107077 ** Whenever the CREATE TRIGGER keywords are seen, the statement
107078 ** must end with ";END;".
107080 ** This implementation uses a state machine with 8 states:
107082 ** (0) INVALID We have not yet seen a non-whitespace character.
107084 ** (1) START At the beginning or end of an SQL statement. This routine
107085 ** returns 1 if it ends in the START state and 0 if it ends
107086 ** in any other state.
107088 ** (2) NORMAL We are in the middle of statement which ends with a single
107089 ** semicolon.
107091 ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
107092 ** a statement.
107094 ** (4) CREATE The keyword CREATE has been seen at the beginning of a
107095 ** statement, possibly preceeded by EXPLAIN and/or followed by
107096 ** TEMP or TEMPORARY
107098 ** (5) TRIGGER We are in the middle of a trigger definition that must be
107099 ** ended by a semicolon, the keyword END, and another semicolon.
107101 ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
107102 ** the end of a trigger definition.
107104 ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
107105 ** of a trigger difinition.
107107 ** Transitions between states above are determined by tokens extracted
107108 ** from the input. The following tokens are significant:
107110 ** (0) tkSEMI A semicolon.
107111 ** (1) tkWS Whitespace.
107112 ** (2) tkOTHER Any other SQL token.
107113 ** (3) tkEXPLAIN The "explain" keyword.
107114 ** (4) tkCREATE The "create" keyword.
107115 ** (5) tkTEMP The "temp" or "temporary" keyword.
107116 ** (6) tkTRIGGER The "trigger" keyword.
107117 ** (7) tkEND The "end" keyword.
107119 ** Whitespace never causes a state transition and is always ignored.
107120 ** This means that a SQL string of all whitespace is invalid.
107122 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
107123 ** to recognize the end of a trigger can be omitted. All we have to do
107124 ** is look for a semicolon that is not part of an string or comment.
107126 SQLITE_API int sqlite3_complete(const char *zSql){
107127 u8 state = 0; /* Current state, using numbers defined in header comment */
107128 u8 token; /* Value of the next token */
107130 #ifndef SQLITE_OMIT_TRIGGER
107131 /* A complex statement machine used to detect the end of a CREATE TRIGGER
107132 ** statement. This is the normal case.
107134 static const u8 trans[8][8] = {
107135 /* Token: */
107136 /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
107137 /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
107138 /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
107139 /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
107140 /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
107141 /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
107142 /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
107143 /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
107144 /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
107146 #else
107147 /* If triggers are not supported by this compile then the statement machine
107148 ** used to detect the end of a statement is much simplier
107150 static const u8 trans[3][3] = {
107151 /* Token: */
107152 /* State: ** SEMI WS OTHER */
107153 /* 0 INVALID: */ { 1, 0, 2, },
107154 /* 1 START: */ { 1, 1, 2, },
107155 /* 2 NORMAL: */ { 1, 2, 2, },
107157 #endif /* SQLITE_OMIT_TRIGGER */
107159 while( *zSql ){
107160 switch( *zSql ){
107161 case ';': { /* A semicolon */
107162 token = tkSEMI;
107163 break;
107165 case ' ':
107166 case '\r':
107167 case '\t':
107168 case '\n':
107169 case '\f': { /* White space is ignored */
107170 token = tkWS;
107171 break;
107173 case '/': { /* C-style comments */
107174 if( zSql[1]!='*' ){
107175 token = tkOTHER;
107176 break;
107178 zSql += 2;
107179 while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
107180 if( zSql[0]==0 ) return 0;
107181 zSql++;
107182 token = tkWS;
107183 break;
107185 case '-': { /* SQL-style comments from "--" to end of line */
107186 if( zSql[1]!='-' ){
107187 token = tkOTHER;
107188 break;
107190 while( *zSql && *zSql!='\n' ){ zSql++; }
107191 if( *zSql==0 ) return state==1;
107192 token = tkWS;
107193 break;
107195 case '[': { /* Microsoft-style identifiers in [...] */
107196 zSql++;
107197 while( *zSql && *zSql!=']' ){ zSql++; }
107198 if( *zSql==0 ) return 0;
107199 token = tkOTHER;
107200 break;
107202 case '`': /* Grave-accent quoted symbols used by MySQL */
107203 case '"': /* single- and double-quoted strings */
107204 case '\'': {
107205 int c = *zSql;
107206 zSql++;
107207 while( *zSql && *zSql!=c ){ zSql++; }
107208 if( *zSql==0 ) return 0;
107209 token = tkOTHER;
107210 break;
107212 default: {
107213 #ifdef SQLITE_EBCDIC
107214 unsigned char c;
107215 #endif
107216 if( IdChar((u8)*zSql) ){
107217 /* Keywords and unquoted identifiers */
107218 int nId;
107219 for(nId=1; IdChar(zSql[nId]); nId++){}
107220 #ifdef SQLITE_OMIT_TRIGGER
107221 token = tkOTHER;
107222 #else
107223 switch( *zSql ){
107224 case 'c': case 'C': {
107225 if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
107226 token = tkCREATE;
107227 }else{
107228 token = tkOTHER;
107230 break;
107232 case 't': case 'T': {
107233 if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
107234 token = tkTRIGGER;
107235 }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
107236 token = tkTEMP;
107237 }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
107238 token = tkTEMP;
107239 }else{
107240 token = tkOTHER;
107242 break;
107244 case 'e': case 'E': {
107245 if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
107246 token = tkEND;
107247 }else
107248 #ifndef SQLITE_OMIT_EXPLAIN
107249 if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
107250 token = tkEXPLAIN;
107251 }else
107252 #endif
107254 token = tkOTHER;
107256 break;
107258 default: {
107259 token = tkOTHER;
107260 break;
107263 #endif /* SQLITE_OMIT_TRIGGER */
107264 zSql += nId-1;
107265 }else{
107266 /* Operators and special symbols */
107267 token = tkOTHER;
107269 break;
107272 state = trans[state][token];
107273 zSql++;
107275 return state==1;
107278 #ifndef SQLITE_OMIT_UTF16
107280 ** This routine is the same as the sqlite3_complete() routine described
107281 ** above, except that the parameter is required to be UTF-16 encoded, not
107282 ** UTF-8.
107284 SQLITE_API int sqlite3_complete16(const void *zSql){
107285 sqlite3_value *pVal;
107286 char const *zSql8;
107287 int rc = SQLITE_NOMEM;
107289 #ifndef SQLITE_OMIT_AUTOINIT
107290 rc = sqlite3_initialize();
107291 if( rc ) return rc;
107292 #endif
107293 pVal = sqlite3ValueNew(0);
107294 sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
107295 zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
107296 if( zSql8 ){
107297 rc = sqlite3_complete(zSql8);
107298 }else{
107299 rc = SQLITE_NOMEM;
107301 sqlite3ValueFree(pVal);
107302 return sqlite3ApiExit(0, rc);
107304 #endif /* SQLITE_OMIT_UTF16 */
107305 #endif /* SQLITE_OMIT_COMPLETE */
107307 /************** End of complete.c ********************************************/
107308 /************** Begin file main.c ********************************************/
107310 ** 2001 September 15
107312 ** The author disclaims copyright to this source code. In place of
107313 ** a legal notice, here is a blessing:
107315 ** May you do good and not evil.
107316 ** May you find forgiveness for yourself and forgive others.
107317 ** May you share freely, never taking more than you give.
107319 *************************************************************************
107320 ** Main file for the SQLite library. The routines in this file
107321 ** implement the programmer interface to the library. Routines in
107322 ** other files are for internal use by SQLite and should not be
107323 ** accessed by users of the library.
107326 #ifdef SQLITE_ENABLE_FTS3
107327 /************** Include fts3.h in the middle of main.c ***********************/
107328 /************** Begin file fts3.h ********************************************/
107330 ** 2006 Oct 10
107332 ** The author disclaims copyright to this source code. In place of
107333 ** a legal notice, here is a blessing:
107335 ** May you do good and not evil.
107336 ** May you find forgiveness for yourself and forgive others.
107337 ** May you share freely, never taking more than you give.
107339 ******************************************************************************
107341 ** This header file is used by programs that want to link against the
107342 ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
107345 #if 0
107346 extern "C" {
107347 #endif /* __cplusplus */
107349 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
107351 #if 0
107352 } /* extern "C" */
107353 #endif /* __cplusplus */
107355 /************** End of fts3.h ************************************************/
107356 /************** Continuing where we left off in main.c ***********************/
107357 #endif
107358 #ifdef SQLITE_ENABLE_RTREE
107359 /************** Include rtree.h in the middle of main.c **********************/
107360 /************** Begin file rtree.h *******************************************/
107362 ** 2008 May 26
107364 ** The author disclaims copyright to this source code. In place of
107365 ** a legal notice, here is a blessing:
107367 ** May you do good and not evil.
107368 ** May you find forgiveness for yourself and forgive others.
107369 ** May you share freely, never taking more than you give.
107371 ******************************************************************************
107373 ** This header file is used by programs that want to link against the
107374 ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
107377 #if 0
107378 extern "C" {
107379 #endif /* __cplusplus */
107381 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
107383 #if 0
107384 } /* extern "C" */
107385 #endif /* __cplusplus */
107387 /************** End of rtree.h ***********************************************/
107388 /************** Continuing where we left off in main.c ***********************/
107389 #endif
107390 #ifdef SQLITE_ENABLE_ICU
107391 /************** Include sqliteicu.h in the middle of main.c ******************/
107392 /************** Begin file sqliteicu.h ***************************************/
107394 ** 2008 May 26
107396 ** The author disclaims copyright to this source code. In place of
107397 ** a legal notice, here is a blessing:
107399 ** May you do good and not evil.
107400 ** May you find forgiveness for yourself and forgive others.
107401 ** May you share freely, never taking more than you give.
107403 ******************************************************************************
107405 ** This header file is used by programs that want to link against the
107406 ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
107409 #if 0
107410 extern "C" {
107411 #endif /* __cplusplus */
107413 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
107415 #if 0
107416 } /* extern "C" */
107417 #endif /* __cplusplus */
107420 /************** End of sqliteicu.h *******************************************/
107421 /************** Continuing where we left off in main.c ***********************/
107422 #endif
107424 #ifndef SQLITE_AMALGAMATION
107425 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
107426 ** contains the text of SQLITE_VERSION macro.
107428 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
107429 #endif
107431 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
107432 ** a pointer to the to the sqlite3_version[] string constant.
107434 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
107436 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
107437 ** pointer to a string constant whose value is the same as the
107438 ** SQLITE_SOURCE_ID C preprocessor macro.
107440 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
107442 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
107443 ** returns an integer equal to SQLITE_VERSION_NUMBER.
107445 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
107447 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
107448 ** zero if and only if SQLite was compiled mutexing code omitted due to
107449 ** the SQLITE_THREADSAFE compile-time option being set to 0.
107451 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
107453 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
107455 ** If the following function pointer is not NULL and if
107456 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
107457 ** I/O active are written using this function. These messages
107458 ** are intended for debugging activity only.
107460 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
107461 #endif
107464 ** If the following global variable points to a string which is the
107465 ** name of a directory, then that directory will be used to store
107466 ** temporary files.
107468 ** See also the "PRAGMA temp_store_directory" SQL command.
107470 SQLITE_API char *sqlite3_temp_directory = 0;
107473 ** Initialize SQLite.
107475 ** This routine must be called to initialize the memory allocation,
107476 ** VFS, and mutex subsystems prior to doing any serious work with
107477 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
107478 ** this routine will be called automatically by key routines such as
107479 ** sqlite3_open().
107481 ** This routine is a no-op except on its very first call for the process,
107482 ** or for the first call after a call to sqlite3_shutdown.
107484 ** The first thread to call this routine runs the initialization to
107485 ** completion. If subsequent threads call this routine before the first
107486 ** thread has finished the initialization process, then the subsequent
107487 ** threads must block until the first thread finishes with the initialization.
107489 ** The first thread might call this routine recursively. Recursive
107490 ** calls to this routine should not block, of course. Otherwise the
107491 ** initialization process would never complete.
107493 ** Let X be the first thread to enter this routine. Let Y be some other
107494 ** thread. Then while the initial invocation of this routine by X is
107495 ** incomplete, it is required that:
107497 ** * Calls to this routine from Y must block until the outer-most
107498 ** call by X completes.
107500 ** * Recursive calls to this routine from thread X return immediately
107501 ** without blocking.
107503 SQLITE_API int sqlite3_initialize(void){
107504 sqlite3_mutex *pMaster; /* The main static mutex */
107505 int rc; /* Result code */
107507 #ifdef SQLITE_OMIT_WSD
107508 rc = sqlite3_wsd_init(4096, 24);
107509 if( rc!=SQLITE_OK ){
107510 return rc;
107512 #endif
107514 /* If SQLite is already completely initialized, then this call
107515 ** to sqlite3_initialize() should be a no-op. But the initialization
107516 ** must be complete. So isInit must not be set until the very end
107517 ** of this routine.
107519 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
107521 /* Make sure the mutex subsystem is initialized. If unable to
107522 ** initialize the mutex subsystem, return early with the error.
107523 ** If the system is so sick that we are unable to allocate a mutex,
107524 ** there is not much SQLite is going to be able to do.
107526 ** The mutex subsystem must take care of serializing its own
107527 ** initialization.
107529 rc = sqlite3MutexInit();
107530 if( rc ) return rc;
107532 /* Initialize the malloc() system and the recursive pInitMutex mutex.
107533 ** This operation is protected by the STATIC_MASTER mutex. Note that
107534 ** MutexAlloc() is called for a static mutex prior to initializing the
107535 ** malloc subsystem - this implies that the allocation of a static
107536 ** mutex must not require support from the malloc subsystem.
107538 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
107539 sqlite3_mutex_enter(pMaster);
107540 sqlite3GlobalConfig.isMutexInit = 1;
107541 if( !sqlite3GlobalConfig.isMallocInit ){
107542 rc = sqlite3MallocInit();
107544 if( rc==SQLITE_OK ){
107545 sqlite3GlobalConfig.isMallocInit = 1;
107546 if( !sqlite3GlobalConfig.pInitMutex ){
107547 sqlite3GlobalConfig.pInitMutex =
107548 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
107549 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
107550 rc = SQLITE_NOMEM;
107554 if( rc==SQLITE_OK ){
107555 sqlite3GlobalConfig.nRefInitMutex++;
107557 sqlite3_mutex_leave(pMaster);
107559 /* If rc is not SQLITE_OK at this point, then either the malloc
107560 ** subsystem could not be initialized or the system failed to allocate
107561 ** the pInitMutex mutex. Return an error in either case. */
107562 if( rc!=SQLITE_OK ){
107563 return rc;
107566 /* Do the rest of the initialization under the recursive mutex so
107567 ** that we will be able to handle recursive calls into
107568 ** sqlite3_initialize(). The recursive calls normally come through
107569 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
107570 ** recursive calls might also be possible.
107572 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
107573 ** to the xInit method, so the xInit method need not be threadsafe.
107575 ** The following mutex is what serializes access to the appdef pcache xInit
107576 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
107577 ** call to sqlite3PcacheInitialize().
107579 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
107580 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
107581 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
107582 sqlite3GlobalConfig.inProgress = 1;
107583 memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
107584 sqlite3RegisterGlobalFunctions();
107585 if( sqlite3GlobalConfig.isPCacheInit==0 ){
107586 rc = sqlite3PcacheInitialize();
107588 if( rc==SQLITE_OK ){
107589 sqlite3GlobalConfig.isPCacheInit = 1;
107590 rc = sqlite3OsInit();
107592 if( rc==SQLITE_OK ){
107593 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
107594 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
107595 sqlite3GlobalConfig.isInit = 1;
107597 sqlite3GlobalConfig.inProgress = 0;
107599 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
107601 /* Go back under the static mutex and clean up the recursive
107602 ** mutex to prevent a resource leak.
107604 sqlite3_mutex_enter(pMaster);
107605 sqlite3GlobalConfig.nRefInitMutex--;
107606 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
107607 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
107608 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
107609 sqlite3GlobalConfig.pInitMutex = 0;
107611 sqlite3_mutex_leave(pMaster);
107613 /* The following is just a sanity check to make sure SQLite has
107614 ** been compiled correctly. It is important to run this code, but
107615 ** we don't want to run it too often and soak up CPU cycles for no
107616 ** reason. So we run it once during initialization.
107618 #ifndef NDEBUG
107619 #ifndef SQLITE_OMIT_FLOATING_POINT
107620 /* This section of code's only "output" is via assert() statements. */
107621 if ( rc==SQLITE_OK ){
107622 u64 x = (((u64)1)<<63)-1;
107623 double y;
107624 assert(sizeof(x)==8);
107625 assert(sizeof(x)==sizeof(y));
107626 memcpy(&y, &x, 8);
107627 assert( sqlite3IsNaN(y) );
107629 #endif
107630 #endif
107632 return rc;
107636 ** Undo the effects of sqlite3_initialize(). Must not be called while
107637 ** there are outstanding database connections or memory allocations or
107638 ** while any part of SQLite is otherwise in use in any thread. This
107639 ** routine is not threadsafe. But it is safe to invoke this routine
107640 ** on when SQLite is already shut down. If SQLite is already shut down
107641 ** when this routine is invoked, then this routine is a harmless no-op.
107643 SQLITE_API int sqlite3_shutdown(void){
107644 if( sqlite3GlobalConfig.isInit ){
107645 sqlite3_os_end();
107646 sqlite3_reset_auto_extension();
107647 sqlite3GlobalConfig.isInit = 0;
107649 if( sqlite3GlobalConfig.isPCacheInit ){
107650 sqlite3PcacheShutdown();
107651 sqlite3GlobalConfig.isPCacheInit = 0;
107653 if( sqlite3GlobalConfig.isMallocInit ){
107654 sqlite3MallocEnd();
107655 sqlite3GlobalConfig.isMallocInit = 0;
107657 if( sqlite3GlobalConfig.isMutexInit ){
107658 sqlite3MutexEnd();
107659 sqlite3GlobalConfig.isMutexInit = 0;
107662 return SQLITE_OK;
107666 ** This API allows applications to modify the global configuration of
107667 ** the SQLite library at run-time.
107669 ** This routine should only be called when there are no outstanding
107670 ** database connections or memory allocations. This routine is not
107671 ** threadsafe. Failure to heed these warnings can lead to unpredictable
107672 ** behavior.
107674 SQLITE_API int sqlite3_config(int op, ...){
107675 va_list ap;
107676 int rc = SQLITE_OK;
107678 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
107679 ** the SQLite library is in use. */
107680 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
107682 va_start(ap, op);
107683 switch( op ){
107685 /* Mutex configuration options are only available in a threadsafe
107686 ** compile.
107688 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
107689 case SQLITE_CONFIG_SINGLETHREAD: {
107690 /* Disable all mutexing */
107691 sqlite3GlobalConfig.bCoreMutex = 0;
107692 sqlite3GlobalConfig.bFullMutex = 0;
107693 break;
107695 case SQLITE_CONFIG_MULTITHREAD: {
107696 /* Disable mutexing of database connections */
107697 /* Enable mutexing of core data structures */
107698 sqlite3GlobalConfig.bCoreMutex = 1;
107699 sqlite3GlobalConfig.bFullMutex = 0;
107700 break;
107702 case SQLITE_CONFIG_SERIALIZED: {
107703 /* Enable all mutexing */
107704 sqlite3GlobalConfig.bCoreMutex = 1;
107705 sqlite3GlobalConfig.bFullMutex = 1;
107706 break;
107708 case SQLITE_CONFIG_MUTEX: {
107709 /* Specify an alternative mutex implementation */
107710 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
107711 break;
107713 case SQLITE_CONFIG_GETMUTEX: {
107714 /* Retrieve the current mutex implementation */
107715 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
107716 break;
107718 #endif
107721 case SQLITE_CONFIG_MALLOC: {
107722 /* Specify an alternative malloc implementation */
107723 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
107724 break;
107726 case SQLITE_CONFIG_GETMALLOC: {
107727 /* Retrieve the current malloc() implementation */
107728 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
107729 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
107730 break;
107732 case SQLITE_CONFIG_MEMSTATUS: {
107733 /* Enable or disable the malloc status collection */
107734 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
107735 break;
107737 case SQLITE_CONFIG_SCRATCH: {
107738 /* Designate a buffer for scratch memory space */
107739 sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
107740 sqlite3GlobalConfig.szScratch = va_arg(ap, int);
107741 sqlite3GlobalConfig.nScratch = va_arg(ap, int);
107742 break;
107744 case SQLITE_CONFIG_PAGECACHE: {
107745 /* Designate a buffer for page cache memory space */
107746 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
107747 sqlite3GlobalConfig.szPage = va_arg(ap, int);
107748 sqlite3GlobalConfig.nPage = va_arg(ap, int);
107749 break;
107752 case SQLITE_CONFIG_PCACHE: {
107753 /* Specify an alternative page cache implementation */
107754 sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
107755 break;
107758 case SQLITE_CONFIG_GETPCACHE: {
107759 if( sqlite3GlobalConfig.pcache.xInit==0 ){
107760 sqlite3PCacheSetDefault();
107762 *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
107763 break;
107766 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
107767 case SQLITE_CONFIG_HEAP: {
107768 /* Designate a buffer for heap memory space */
107769 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
107770 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
107771 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
107773 if( sqlite3GlobalConfig.mnReq<1 ){
107774 sqlite3GlobalConfig.mnReq = 1;
107775 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
107776 /* cap min request size at 2^12 */
107777 sqlite3GlobalConfig.mnReq = (1<<12);
107780 if( sqlite3GlobalConfig.pHeap==0 ){
107781 /* If the heap pointer is NULL, then restore the malloc implementation
107782 ** back to NULL pointers too. This will cause the malloc to go
107783 ** back to its default implementation when sqlite3_initialize() is
107784 ** run.
107786 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
107787 }else{
107788 /* The heap pointer is not NULL, then install one of the
107789 ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
107790 ** ENABLE_MEMSYS5 is defined, return an error.
107792 #ifdef SQLITE_ENABLE_MEMSYS3
107793 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
107794 #endif
107795 #ifdef SQLITE_ENABLE_MEMSYS5
107796 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
107797 #endif
107799 break;
107801 #endif
107803 case SQLITE_CONFIG_LOOKASIDE: {
107804 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
107805 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
107806 break;
107809 /* Record a pointer to the logger funcction and its first argument.
107810 ** The default is NULL. Logging is disabled if the function pointer is
107811 ** NULL.
107813 case SQLITE_CONFIG_LOG: {
107814 /* MSVC is picky about pulling func ptrs from va lists.
107815 ** http://support.microsoft.com/kb/47961
107816 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
107818 typedef void(*LOGFUNC_t)(void*,int,const char*);
107819 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
107820 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
107821 break;
107824 default: {
107825 rc = SQLITE_ERROR;
107826 break;
107829 va_end(ap);
107830 return rc;
107834 ** Set up the lookaside buffers for a database connection.
107835 ** Return SQLITE_OK on success.
107836 ** If lookaside is already active, return SQLITE_BUSY.
107838 ** The sz parameter is the number of bytes in each lookaside slot.
107839 ** The cnt parameter is the number of slots. If pStart is NULL the
107840 ** space for the lookaside memory is obtained from sqlite3_malloc().
107841 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
107842 ** the lookaside memory.
107844 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
107845 void *pStart;
107846 if( db->lookaside.nOut ){
107847 return SQLITE_BUSY;
107849 /* Free any existing lookaside buffer for this handle before
107850 ** allocating a new one so we don't have to have space for
107851 ** both at the same time.
107853 if( db->lookaside.bMalloced ){
107854 sqlite3_free(db->lookaside.pStart);
107856 /* The size of a lookaside slot needs to be larger than a pointer
107857 ** to be useful.
107859 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
107860 if( cnt<0 ) cnt = 0;
107861 if( sz==0 || cnt==0 ){
107862 sz = 0;
107863 pStart = 0;
107864 }else if( pBuf==0 ){
107865 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
107866 sqlite3BeginBenignMalloc();
107867 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
107868 sqlite3EndBenignMalloc();
107869 }else{
107870 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
107871 pStart = pBuf;
107873 db->lookaside.pStart = pStart;
107874 db->lookaside.pFree = 0;
107875 db->lookaside.sz = (u16)sz;
107876 if( pStart ){
107877 int i;
107878 LookasideSlot *p;
107879 assert( sz > (int)sizeof(LookasideSlot*) );
107880 p = (LookasideSlot*)pStart;
107881 for(i=cnt-1; i>=0; i--){
107882 p->pNext = db->lookaside.pFree;
107883 db->lookaside.pFree = p;
107884 p = (LookasideSlot*)&((u8*)p)[sz];
107886 db->lookaside.pEnd = p;
107887 db->lookaside.bEnabled = 1;
107888 db->lookaside.bMalloced = pBuf==0 ?1:0;
107889 }else{
107890 db->lookaside.pEnd = 0;
107891 db->lookaside.bEnabled = 0;
107892 db->lookaside.bMalloced = 0;
107894 return SQLITE_OK;
107898 ** Return the mutex associated with a database connection.
107900 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
107901 return db->mutex;
107905 ** Configuration settings for an individual database connection
107907 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
107908 va_list ap;
107909 int rc;
107910 va_start(ap, op);
107911 switch( op ){
107912 case SQLITE_DBCONFIG_LOOKASIDE: {
107913 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
107914 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
107915 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
107916 rc = setupLookaside(db, pBuf, sz, cnt);
107917 break;
107919 default: {
107920 static const struct {
107921 int op; /* The opcode */
107922 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
107923 } aFlagOp[] = {
107924 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
107925 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
107927 unsigned int i;
107928 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
107929 for(i=0; i<ArraySize(aFlagOp); i++){
107930 if( aFlagOp[i].op==op ){
107931 int onoff = va_arg(ap, int);
107932 int *pRes = va_arg(ap, int*);
107933 int oldFlags = db->flags;
107934 if( onoff>0 ){
107935 db->flags |= aFlagOp[i].mask;
107936 }else if( onoff==0 ){
107937 db->flags &= ~aFlagOp[i].mask;
107939 if( oldFlags!=db->flags ){
107940 sqlite3ExpirePreparedStatements(db);
107942 if( pRes ){
107943 *pRes = (db->flags & aFlagOp[i].mask)!=0;
107945 rc = SQLITE_OK;
107946 break;
107949 break;
107952 va_end(ap);
107953 return rc;
107958 ** Return true if the buffer z[0..n-1] contains all spaces.
107960 static int allSpaces(const char *z, int n){
107961 while( n>0 && z[n-1]==' ' ){ n--; }
107962 return n==0;
107966 ** This is the default collating function named "BINARY" which is always
107967 ** available.
107969 ** If the padFlag argument is not NULL then space padding at the end
107970 ** of strings is ignored. This implements the RTRIM collation.
107972 static int binCollFunc(
107973 void *padFlag,
107974 int nKey1, const void *pKey1,
107975 int nKey2, const void *pKey2
107977 int rc, n;
107978 n = nKey1<nKey2 ? nKey1 : nKey2;
107979 rc = memcmp(pKey1, pKey2, n);
107980 if( rc==0 ){
107981 if( padFlag
107982 && allSpaces(((char*)pKey1)+n, nKey1-n)
107983 && allSpaces(((char*)pKey2)+n, nKey2-n)
107985 /* Leave rc unchanged at 0 */
107986 }else{
107987 rc = nKey1 - nKey2;
107990 return rc;
107994 ** Another built-in collating sequence: NOCASE.
107996 ** This collating sequence is intended to be used for "case independant
107997 ** comparison". SQLite's knowledge of upper and lower case equivalents
107998 ** extends only to the 26 characters used in the English language.
108000 ** At the moment there is only a UTF-8 implementation.
108002 static int nocaseCollatingFunc(
108003 void *NotUsed,
108004 int nKey1, const void *pKey1,
108005 int nKey2, const void *pKey2
108007 int r = sqlite3StrNICmp(
108008 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
108009 UNUSED_PARAMETER(NotUsed);
108010 if( 0==r ){
108011 r = nKey1-nKey2;
108013 return r;
108017 ** Return the ROWID of the most recent insert
108019 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
108020 return db->lastRowid;
108024 ** Return the number of changes in the most recent call to sqlite3_exec().
108026 SQLITE_API int sqlite3_changes(sqlite3 *db){
108027 return db->nChange;
108031 ** Return the number of changes since the database handle was opened.
108033 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
108034 return db->nTotalChange;
108038 ** Close all open savepoints. This function only manipulates fields of the
108039 ** database handle object, it does not close any savepoints that may be open
108040 ** at the b-tree/pager level.
108042 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
108043 while( db->pSavepoint ){
108044 Savepoint *pTmp = db->pSavepoint;
108045 db->pSavepoint = pTmp->pNext;
108046 sqlite3DbFree(db, pTmp);
108048 db->nSavepoint = 0;
108049 db->nStatement = 0;
108050 db->isTransactionSavepoint = 0;
108054 ** Invoke the destructor function associated with FuncDef p, if any. Except,
108055 ** if this is not the last copy of the function, do not invoke it. Multiple
108056 ** copies of a single function are created when create_function() is called
108057 ** with SQLITE_ANY as the encoding.
108059 static void functionDestroy(sqlite3 *db, FuncDef *p){
108060 FuncDestructor *pDestructor = p->pDestructor;
108061 if( pDestructor ){
108062 pDestructor->nRef--;
108063 if( pDestructor->nRef==0 ){
108064 pDestructor->xDestroy(pDestructor->pUserData);
108065 sqlite3DbFree(db, pDestructor);
108071 ** Close an existing SQLite database
108073 SQLITE_API int sqlite3_close(sqlite3 *db){
108074 HashElem *i; /* Hash table iterator */
108075 int j;
108077 if( !db ){
108078 return SQLITE_OK;
108080 if( !sqlite3SafetyCheckSickOrOk(db) ){
108081 return SQLITE_MISUSE_BKPT;
108083 sqlite3_mutex_enter(db->mutex);
108085 /* Force xDestroy calls on all virtual tables */
108086 sqlite3ResetInternalSchema(db, -1);
108088 /* If a transaction is open, the ResetInternalSchema() call above
108089 ** will not have called the xDisconnect() method on any virtual
108090 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
108091 ** call will do so. We need to do this before the check for active
108092 ** SQL statements below, as the v-table implementation may be storing
108093 ** some prepared statements internally.
108095 sqlite3VtabRollback(db);
108097 /* If there are any outstanding VMs, return SQLITE_BUSY. */
108098 if( db->pVdbe ){
108099 sqlite3Error(db, SQLITE_BUSY,
108100 "unable to close due to unfinalised statements");
108101 sqlite3_mutex_leave(db->mutex);
108102 return SQLITE_BUSY;
108104 assert( sqlite3SafetyCheckSickOrOk(db) );
108106 for(j=0; j<db->nDb; j++){
108107 Btree *pBt = db->aDb[j].pBt;
108108 if( pBt && sqlite3BtreeIsInBackup(pBt) ){
108109 sqlite3Error(db, SQLITE_BUSY,
108110 "unable to close due to unfinished backup operation");
108111 sqlite3_mutex_leave(db->mutex);
108112 return SQLITE_BUSY;
108116 /* Free any outstanding Savepoint structures. */
108117 sqlite3CloseSavepoints(db);
108119 for(j=0; j<db->nDb; j++){
108120 struct Db *pDb = &db->aDb[j];
108121 if( pDb->pBt ){
108122 sqlite3BtreeClose(pDb->pBt);
108123 pDb->pBt = 0;
108124 if( j!=1 ){
108125 pDb->pSchema = 0;
108129 sqlite3ResetInternalSchema(db, -1);
108131 /* Tell the code in notify.c that the connection no longer holds any
108132 ** locks and does not require any further unlock-notify callbacks.
108134 sqlite3ConnectionClosed(db);
108136 assert( db->nDb<=2 );
108137 assert( db->aDb==db->aDbStatic );
108138 for(j=0; j<ArraySize(db->aFunc.a); j++){
108139 FuncDef *pNext, *pHash, *p;
108140 for(p=db->aFunc.a[j]; p; p=pHash){
108141 pHash = p->pHash;
108142 while( p ){
108143 functionDestroy(db, p);
108144 pNext = p->pNext;
108145 sqlite3DbFree(db, p);
108146 p = pNext;
108150 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
108151 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
108152 /* Invoke any destructors registered for collation sequence user data. */
108153 for(j=0; j<3; j++){
108154 if( pColl[j].xDel ){
108155 pColl[j].xDel(pColl[j].pUser);
108158 sqlite3DbFree(db, pColl);
108160 sqlite3HashClear(&db->aCollSeq);
108161 #ifndef SQLITE_OMIT_VIRTUALTABLE
108162 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
108163 Module *pMod = (Module *)sqliteHashData(i);
108164 if( pMod->xDestroy ){
108165 pMod->xDestroy(pMod->pAux);
108167 sqlite3DbFree(db, pMod);
108169 sqlite3HashClear(&db->aModule);
108170 #endif
108172 sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
108173 if( db->pErr ){
108174 sqlite3ValueFree(db->pErr);
108176 sqlite3CloseExtensions(db);
108178 db->magic = SQLITE_MAGIC_ERROR;
108180 /* The temp-database schema is allocated differently from the other schema
108181 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
108182 ** So it needs to be freed here. Todo: Why not roll the temp schema into
108183 ** the same sqliteMalloc() as the one that allocates the database
108184 ** structure?
108186 sqlite3DbFree(db, db->aDb[1].pSchema);
108187 sqlite3_mutex_leave(db->mutex);
108188 db->magic = SQLITE_MAGIC_CLOSED;
108189 sqlite3_mutex_free(db->mutex);
108190 assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
108191 if( db->lookaside.bMalloced ){
108192 sqlite3_free(db->lookaside.pStart);
108194 sqlite3_free(db);
108195 return SQLITE_OK;
108199 ** Rollback all database files.
108201 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
108202 int i;
108203 int inTrans = 0;
108204 assert( sqlite3_mutex_held(db->mutex) );
108205 sqlite3BeginBenignMalloc();
108206 for(i=0; i<db->nDb; i++){
108207 if( db->aDb[i].pBt ){
108208 if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
108209 inTrans = 1;
108211 sqlite3BtreeRollback(db->aDb[i].pBt);
108212 db->aDb[i].inTrans = 0;
108215 sqlite3VtabRollback(db);
108216 sqlite3EndBenignMalloc();
108218 if( db->flags&SQLITE_InternChanges ){
108219 sqlite3ExpirePreparedStatements(db);
108220 sqlite3ResetInternalSchema(db, -1);
108223 /* Any deferred constraint violations have now been resolved. */
108224 db->nDeferredCons = 0;
108226 /* If one has been configured, invoke the rollback-hook callback */
108227 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
108228 db->xRollbackCallback(db->pRollbackArg);
108233 ** Return a static string that describes the kind of error specified in the
108234 ** argument.
108236 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
108237 static const char* const aMsg[] = {
108238 /* SQLITE_OK */ "not an error",
108239 /* SQLITE_ERROR */ "SQL logic error or missing database",
108240 /* SQLITE_INTERNAL */ 0,
108241 /* SQLITE_PERM */ "access permission denied",
108242 /* SQLITE_ABORT */ "callback requested query abort",
108243 /* SQLITE_BUSY */ "database is locked",
108244 /* SQLITE_LOCKED */ "database table is locked",
108245 /* SQLITE_NOMEM */ "out of memory",
108246 /* SQLITE_READONLY */ "attempt to write a readonly database",
108247 /* SQLITE_INTERRUPT */ "interrupted",
108248 /* SQLITE_IOERR */ "disk I/O error",
108249 /* SQLITE_CORRUPT */ "database disk image is malformed",
108250 /* SQLITE_NOTFOUND */ "unknown operation",
108251 /* SQLITE_FULL */ "database or disk is full",
108252 /* SQLITE_CANTOPEN */ "unable to open database file",
108253 /* SQLITE_PROTOCOL */ "locking protocol",
108254 /* SQLITE_EMPTY */ "table contains no data",
108255 /* SQLITE_SCHEMA */ "database schema has changed",
108256 /* SQLITE_TOOBIG */ "string or blob too big",
108257 /* SQLITE_CONSTRAINT */ "constraint failed",
108258 /* SQLITE_MISMATCH */ "datatype mismatch",
108259 /* SQLITE_MISUSE */ "library routine called out of sequence",
108260 /* SQLITE_NOLFS */ "large file support is disabled",
108261 /* SQLITE_AUTH */ "authorization denied",
108262 /* SQLITE_FORMAT */ "auxiliary database format error",
108263 /* SQLITE_RANGE */ "bind or column index out of range",
108264 /* SQLITE_NOTADB */ "file is encrypted or is not a database",
108266 rc &= 0xff;
108267 if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
108268 return aMsg[rc];
108269 }else{
108270 return "unknown error";
108275 ** This routine implements a busy callback that sleeps and tries
108276 ** again until a timeout value is reached. The timeout value is
108277 ** an integer number of milliseconds passed in as the first
108278 ** argument.
108280 static int sqliteDefaultBusyCallback(
108281 void *ptr, /* Database connection */
108282 int count /* Number of times table has been busy */
108284 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
108285 static const u8 delays[] =
108286 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
108287 static const u8 totals[] =
108288 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
108289 # define NDELAY ArraySize(delays)
108290 sqlite3 *db = (sqlite3 *)ptr;
108291 int timeout = db->busyTimeout;
108292 int delay, prior;
108294 assert( count>=0 );
108295 if( count < NDELAY ){
108296 delay = delays[count];
108297 prior = totals[count];
108298 }else{
108299 delay = delays[NDELAY-1];
108300 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
108302 if( prior + delay > timeout ){
108303 delay = timeout - prior;
108304 if( delay<=0 ) return 0;
108306 sqlite3OsSleep(db->pVfs, delay*1000);
108307 return 1;
108308 #else
108309 sqlite3 *db = (sqlite3 *)ptr;
108310 int timeout = ((sqlite3 *)ptr)->busyTimeout;
108311 if( (count+1)*1000 > timeout ){
108312 return 0;
108314 sqlite3OsSleep(db->pVfs, 1000000);
108315 return 1;
108316 #endif
108320 ** Invoke the given busy handler.
108322 ** This routine is called when an operation failed with a lock.
108323 ** If this routine returns non-zero, the lock is retried. If it
108324 ** returns 0, the operation aborts with an SQLITE_BUSY error.
108326 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
108327 int rc;
108328 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
108329 rc = p->xFunc(p->pArg, p->nBusy);
108330 if( rc==0 ){
108331 p->nBusy = -1;
108332 }else{
108333 p->nBusy++;
108335 return rc;
108339 ** This routine sets the busy callback for an Sqlite database to the
108340 ** given callback function with the given argument.
108342 SQLITE_API int sqlite3_busy_handler(
108343 sqlite3 *db,
108344 int (*xBusy)(void*,int),
108345 void *pArg
108347 sqlite3_mutex_enter(db->mutex);
108348 db->busyHandler.xFunc = xBusy;
108349 db->busyHandler.pArg = pArg;
108350 db->busyHandler.nBusy = 0;
108351 sqlite3_mutex_leave(db->mutex);
108352 return SQLITE_OK;
108355 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
108357 ** This routine sets the progress callback for an Sqlite database to the
108358 ** given callback function with the given argument. The progress callback will
108359 ** be invoked every nOps opcodes.
108361 SQLITE_API void sqlite3_progress_handler(
108362 sqlite3 *db,
108363 int nOps,
108364 int (*xProgress)(void*),
108365 void *pArg
108367 sqlite3_mutex_enter(db->mutex);
108368 if( nOps>0 ){
108369 db->xProgress = xProgress;
108370 db->nProgressOps = nOps;
108371 db->pProgressArg = pArg;
108372 }else{
108373 db->xProgress = 0;
108374 db->nProgressOps = 0;
108375 db->pProgressArg = 0;
108377 sqlite3_mutex_leave(db->mutex);
108379 #endif
108383 ** This routine installs a default busy handler that waits for the
108384 ** specified number of milliseconds before returning 0.
108386 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
108387 if( ms>0 ){
108388 db->busyTimeout = ms;
108389 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
108390 }else{
108391 sqlite3_busy_handler(db, 0, 0);
108393 return SQLITE_OK;
108397 ** Cause any pending operation to stop at its earliest opportunity.
108399 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
108400 db->u1.isInterrupted = 1;
108405 ** This function is exactly the same as sqlite3_create_function(), except
108406 ** that it is designed to be called by internal code. The difference is
108407 ** that if a malloc() fails in sqlite3_create_function(), an error code
108408 ** is returned and the mallocFailed flag cleared.
108410 SQLITE_PRIVATE int sqlite3CreateFunc(
108411 sqlite3 *db,
108412 const char *zFunctionName,
108413 int nArg,
108414 int enc,
108415 void *pUserData,
108416 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108417 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108418 void (*xFinal)(sqlite3_context*),
108419 FuncDestructor *pDestructor
108421 FuncDef *p;
108422 int nName;
108424 assert( sqlite3_mutex_held(db->mutex) );
108425 if( zFunctionName==0 ||
108426 (xFunc && (xFinal || xStep)) ||
108427 (!xFunc && (xFinal && !xStep)) ||
108428 (!xFunc && (!xFinal && xStep)) ||
108429 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
108430 (255<(nName = sqlite3Strlen30( zFunctionName))) ){
108431 return SQLITE_MISUSE_BKPT;
108434 #ifndef SQLITE_OMIT_UTF16
108435 /* If SQLITE_UTF16 is specified as the encoding type, transform this
108436 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
108437 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
108439 ** If SQLITE_ANY is specified, add three versions of the function
108440 ** to the hash table.
108442 if( enc==SQLITE_UTF16 ){
108443 enc = SQLITE_UTF16NATIVE;
108444 }else if( enc==SQLITE_ANY ){
108445 int rc;
108446 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
108447 pUserData, xFunc, xStep, xFinal, pDestructor);
108448 if( rc==SQLITE_OK ){
108449 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
108450 pUserData, xFunc, xStep, xFinal, pDestructor);
108452 if( rc!=SQLITE_OK ){
108453 return rc;
108455 enc = SQLITE_UTF16BE;
108457 #else
108458 enc = SQLITE_UTF8;
108459 #endif
108461 /* Check if an existing function is being overridden or deleted. If so,
108462 ** and there are active VMs, then return SQLITE_BUSY. If a function
108463 ** is being overridden/deleted but there are no active VMs, allow the
108464 ** operation to continue but invalidate all precompiled statements.
108466 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
108467 if( p && p->iPrefEnc==enc && p->nArg==nArg ){
108468 if( db->activeVdbeCnt ){
108469 sqlite3Error(db, SQLITE_BUSY,
108470 "unable to delete/modify user-function due to active statements");
108471 assert( !db->mallocFailed );
108472 return SQLITE_BUSY;
108473 }else{
108474 sqlite3ExpirePreparedStatements(db);
108478 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
108479 assert(p || db->mallocFailed);
108480 if( !p ){
108481 return SQLITE_NOMEM;
108484 /* If an older version of the function with a configured destructor is
108485 ** being replaced invoke the destructor function here. */
108486 functionDestroy(db, p);
108488 if( pDestructor ){
108489 pDestructor->nRef++;
108491 p->pDestructor = pDestructor;
108492 p->flags = 0;
108493 p->xFunc = xFunc;
108494 p->xStep = xStep;
108495 p->xFinalize = xFinal;
108496 p->pUserData = pUserData;
108497 p->nArg = (u16)nArg;
108498 return SQLITE_OK;
108502 ** Create new user functions.
108504 SQLITE_API int sqlite3_create_function(
108505 sqlite3 *db,
108506 const char *zFunc,
108507 int nArg,
108508 int enc,
108509 void *p,
108510 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108511 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108512 void (*xFinal)(sqlite3_context*)
108514 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
108515 xFinal, 0);
108518 SQLITE_API int sqlite3_create_function_v2(
108519 sqlite3 *db,
108520 const char *zFunc,
108521 int nArg,
108522 int enc,
108523 void *p,
108524 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108525 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108526 void (*xFinal)(sqlite3_context*),
108527 void (*xDestroy)(void *)
108529 int rc = SQLITE_ERROR;
108530 FuncDestructor *pArg = 0;
108531 sqlite3_mutex_enter(db->mutex);
108532 if( xDestroy ){
108533 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
108534 if( !pArg ){
108535 xDestroy(p);
108536 goto out;
108538 pArg->xDestroy = xDestroy;
108539 pArg->pUserData = p;
108541 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
108542 if( pArg && pArg->nRef==0 ){
108543 assert( rc!=SQLITE_OK );
108544 xDestroy(p);
108545 sqlite3DbFree(db, pArg);
108549 rc = sqlite3ApiExit(db, rc);
108550 sqlite3_mutex_leave(db->mutex);
108551 return rc;
108554 #ifndef SQLITE_OMIT_UTF16
108555 SQLITE_API int sqlite3_create_function16(
108556 sqlite3 *db,
108557 const void *zFunctionName,
108558 int nArg,
108559 int eTextRep,
108560 void *p,
108561 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108562 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108563 void (*xFinal)(sqlite3_context*)
108565 int rc;
108566 char *zFunc8;
108567 sqlite3_mutex_enter(db->mutex);
108568 assert( !db->mallocFailed );
108569 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
108570 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
108571 sqlite3DbFree(db, zFunc8);
108572 rc = sqlite3ApiExit(db, rc);
108573 sqlite3_mutex_leave(db->mutex);
108574 return rc;
108576 #endif
108580 ** Declare that a function has been overloaded by a virtual table.
108582 ** If the function already exists as a regular global function, then
108583 ** this routine is a no-op. If the function does not exist, then create
108584 ** a new one that always throws a run-time error.
108586 ** When virtual tables intend to provide an overloaded function, they
108587 ** should call this routine to make sure the global function exists.
108588 ** A global function must exist in order for name resolution to work
108589 ** properly.
108591 SQLITE_API int sqlite3_overload_function(
108592 sqlite3 *db,
108593 const char *zName,
108594 int nArg
108596 int nName = sqlite3Strlen30(zName);
108597 int rc;
108598 sqlite3_mutex_enter(db->mutex);
108599 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
108600 sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
108601 0, sqlite3InvalidFunction, 0, 0, 0);
108603 rc = sqlite3ApiExit(db, SQLITE_OK);
108604 sqlite3_mutex_leave(db->mutex);
108605 return rc;
108608 #ifndef SQLITE_OMIT_TRACE
108610 ** Register a trace function. The pArg from the previously registered trace
108611 ** is returned.
108613 ** A NULL trace function means that no tracing is executes. A non-NULL
108614 ** trace is a pointer to a function that is invoked at the start of each
108615 ** SQL statement.
108617 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
108618 void *pOld;
108619 sqlite3_mutex_enter(db->mutex);
108620 pOld = db->pTraceArg;
108621 db->xTrace = xTrace;
108622 db->pTraceArg = pArg;
108623 sqlite3_mutex_leave(db->mutex);
108624 return pOld;
108627 ** Register a profile function. The pArg from the previously registered
108628 ** profile function is returned.
108630 ** A NULL profile function means that no profiling is executes. A non-NULL
108631 ** profile is a pointer to a function that is invoked at the conclusion of
108632 ** each SQL statement that is run.
108634 SQLITE_API void *sqlite3_profile(
108635 sqlite3 *db,
108636 void (*xProfile)(void*,const char*,sqlite_uint64),
108637 void *pArg
108639 void *pOld;
108640 sqlite3_mutex_enter(db->mutex);
108641 pOld = db->pProfileArg;
108642 db->xProfile = xProfile;
108643 db->pProfileArg = pArg;
108644 sqlite3_mutex_leave(db->mutex);
108645 return pOld;
108647 #endif /* SQLITE_OMIT_TRACE */
108649 /*** EXPERIMENTAL ***
108651 ** Register a function to be invoked when a transaction comments.
108652 ** If the invoked function returns non-zero, then the commit becomes a
108653 ** rollback.
108655 SQLITE_API void *sqlite3_commit_hook(
108656 sqlite3 *db, /* Attach the hook to this database */
108657 int (*xCallback)(void*), /* Function to invoke on each commit */
108658 void *pArg /* Argument to the function */
108660 void *pOld;
108661 sqlite3_mutex_enter(db->mutex);
108662 pOld = db->pCommitArg;
108663 db->xCommitCallback = xCallback;
108664 db->pCommitArg = pArg;
108665 sqlite3_mutex_leave(db->mutex);
108666 return pOld;
108670 ** Register a callback to be invoked each time a row is updated,
108671 ** inserted or deleted using this database connection.
108673 SQLITE_API void *sqlite3_update_hook(
108674 sqlite3 *db, /* Attach the hook to this database */
108675 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
108676 void *pArg /* Argument to the function */
108678 void *pRet;
108679 sqlite3_mutex_enter(db->mutex);
108680 pRet = db->pUpdateArg;
108681 db->xUpdateCallback = xCallback;
108682 db->pUpdateArg = pArg;
108683 sqlite3_mutex_leave(db->mutex);
108684 return pRet;
108688 ** Register a callback to be invoked each time a transaction is rolled
108689 ** back by this database connection.
108691 SQLITE_API void *sqlite3_rollback_hook(
108692 sqlite3 *db, /* Attach the hook to this database */
108693 void (*xCallback)(void*), /* Callback function */
108694 void *pArg /* Argument to the function */
108696 void *pRet;
108697 sqlite3_mutex_enter(db->mutex);
108698 pRet = db->pRollbackArg;
108699 db->xRollbackCallback = xCallback;
108700 db->pRollbackArg = pArg;
108701 sqlite3_mutex_leave(db->mutex);
108702 return pRet;
108705 #ifndef SQLITE_OMIT_WAL
108707 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
108708 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
108709 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
108710 ** wal_autocheckpoint()).
108712 SQLITE_PRIVATE int sqlite3WalDefaultHook(
108713 void *pClientData, /* Argument */
108714 sqlite3 *db, /* Connection */
108715 const char *zDb, /* Database */
108716 int nFrame /* Size of WAL */
108718 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
108719 sqlite3BeginBenignMalloc();
108720 sqlite3_wal_checkpoint(db, zDb);
108721 sqlite3EndBenignMalloc();
108723 return SQLITE_OK;
108725 #endif /* SQLITE_OMIT_WAL */
108728 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
108729 ** a database after committing a transaction if there are nFrame or
108730 ** more frames in the log file. Passing zero or a negative value as the
108731 ** nFrame parameter disables automatic checkpoints entirely.
108733 ** The callback registered by this function replaces any existing callback
108734 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
108735 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
108736 ** configured by this function.
108738 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
108739 #ifdef SQLITE_OMIT_WAL
108740 UNUSED_PARAMETER(db);
108741 UNUSED_PARAMETER(nFrame);
108742 #else
108743 if( nFrame>0 ){
108744 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
108745 }else{
108746 sqlite3_wal_hook(db, 0, 0);
108748 #endif
108749 return SQLITE_OK;
108753 ** Register a callback to be invoked each time a transaction is written
108754 ** into the write-ahead-log by this database connection.
108756 SQLITE_API void *sqlite3_wal_hook(
108757 sqlite3 *db, /* Attach the hook to this db handle */
108758 int(*xCallback)(void *, sqlite3*, const char*, int),
108759 void *pArg /* First argument passed to xCallback() */
108761 #ifndef SQLITE_OMIT_WAL
108762 void *pRet;
108763 sqlite3_mutex_enter(db->mutex);
108764 pRet = db->pWalArg;
108765 db->xWalCallback = xCallback;
108766 db->pWalArg = pArg;
108767 sqlite3_mutex_leave(db->mutex);
108768 return pRet;
108769 #else
108770 return 0;
108771 #endif
108775 ** Checkpoint database zDb.
108777 SQLITE_API int sqlite3_wal_checkpoint_v2(
108778 sqlite3 *db, /* Database handle */
108779 const char *zDb, /* Name of attached database (or NULL) */
108780 int eMode, /* SQLITE_CHECKPOINT_* value */
108781 int *pnLog, /* OUT: Size of WAL log in frames */
108782 int *pnCkpt /* OUT: Total number of frames checkpointed */
108784 #ifdef SQLITE_OMIT_WAL
108785 return SQLITE_OK;
108786 #else
108787 int rc; /* Return code */
108788 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
108790 /* Initialize the output variables to -1 in case an error occurs. */
108791 if( pnLog ) *pnLog = -1;
108792 if( pnCkpt ) *pnCkpt = -1;
108794 assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
108795 assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
108796 assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
108797 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
108798 return SQLITE_MISUSE;
108801 sqlite3_mutex_enter(db->mutex);
108802 if( zDb && zDb[0] ){
108803 iDb = sqlite3FindDbName(db, zDb);
108805 if( iDb<0 ){
108806 rc = SQLITE_ERROR;
108807 sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
108808 }else{
108809 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
108810 sqlite3Error(db, rc, 0);
108812 rc = sqlite3ApiExit(db, rc);
108813 sqlite3_mutex_leave(db->mutex);
108814 return rc;
108815 #endif
108820 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
108821 ** to contains a zero-length string, all attached databases are
108822 ** checkpointed.
108824 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
108825 return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
108828 #ifndef SQLITE_OMIT_WAL
108830 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
108831 ** not currently open in WAL mode.
108833 ** If a transaction is open on the database being checkpointed, this
108834 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
108835 ** an error occurs while running the checkpoint, an SQLite error code is
108836 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
108838 ** The mutex on database handle db should be held by the caller. The mutex
108839 ** associated with the specific b-tree being checkpointed is taken by
108840 ** this function while the checkpoint is running.
108842 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
108843 ** checkpointed. If an error is encountered it is returned immediately -
108844 ** no attempt is made to checkpoint any remaining databases.
108846 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
108848 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
108849 int rc = SQLITE_OK; /* Return code */
108850 int i; /* Used to iterate through attached dbs */
108851 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
108853 assert( sqlite3_mutex_held(db->mutex) );
108854 assert( !pnLog || *pnLog==-1 );
108855 assert( !pnCkpt || *pnCkpt==-1 );
108857 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
108858 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
108859 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
108860 pnLog = 0;
108861 pnCkpt = 0;
108862 if( rc==SQLITE_BUSY ){
108863 bBusy = 1;
108864 rc = SQLITE_OK;
108869 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
108871 #endif /* SQLITE_OMIT_WAL */
108874 ** This function returns true if main-memory should be used instead of
108875 ** a temporary file for transient pager files and statement journals.
108876 ** The value returned depends on the value of db->temp_store (runtime
108877 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
108878 ** following table describes the relationship between these two values
108879 ** and this functions return value.
108881 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
108882 ** ----------------- -------------- ------------------------------
108883 ** 0 any file (return 0)
108884 ** 1 1 file (return 0)
108885 ** 1 2 memory (return 1)
108886 ** 1 0 file (return 0)
108887 ** 2 1 file (return 0)
108888 ** 2 2 memory (return 1)
108889 ** 2 0 memory (return 1)
108890 ** 3 any memory (return 1)
108892 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
108893 #if SQLITE_TEMP_STORE==1
108894 return ( db->temp_store==2 );
108895 #endif
108896 #if SQLITE_TEMP_STORE==2
108897 return ( db->temp_store!=1 );
108898 #endif
108899 #if SQLITE_TEMP_STORE==3
108900 return 1;
108901 #endif
108902 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
108903 return 0;
108904 #endif
108908 ** Return UTF-8 encoded English language explanation of the most recent
108909 ** error.
108911 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
108912 const char *z;
108913 if( !db ){
108914 return sqlite3ErrStr(SQLITE_NOMEM);
108916 if( !sqlite3SafetyCheckSickOrOk(db) ){
108917 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
108919 sqlite3_mutex_enter(db->mutex);
108920 if( db->mallocFailed ){
108921 z = sqlite3ErrStr(SQLITE_NOMEM);
108922 }else{
108923 z = (char*)sqlite3_value_text(db->pErr);
108924 assert( !db->mallocFailed );
108925 if( z==0 ){
108926 z = sqlite3ErrStr(db->errCode);
108929 sqlite3_mutex_leave(db->mutex);
108930 return z;
108933 #ifndef SQLITE_OMIT_UTF16
108935 ** Return UTF-16 encoded English language explanation of the most recent
108936 ** error.
108938 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
108939 static const u16 outOfMem[] = {
108940 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
108942 static const u16 misuse[] = {
108943 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
108944 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
108945 'c', 'a', 'l', 'l', 'e', 'd', ' ',
108946 'o', 'u', 't', ' ',
108947 'o', 'f', ' ',
108948 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
108951 const void *z;
108952 if( !db ){
108953 return (void *)outOfMem;
108955 if( !sqlite3SafetyCheckSickOrOk(db) ){
108956 return (void *)misuse;
108958 sqlite3_mutex_enter(db->mutex);
108959 if( db->mallocFailed ){
108960 z = (void *)outOfMem;
108961 }else{
108962 z = sqlite3_value_text16(db->pErr);
108963 if( z==0 ){
108964 sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
108965 SQLITE_UTF8, SQLITE_STATIC);
108966 z = sqlite3_value_text16(db->pErr);
108968 /* A malloc() may have failed within the call to sqlite3_value_text16()
108969 ** above. If this is the case, then the db->mallocFailed flag needs to
108970 ** be cleared before returning. Do this directly, instead of via
108971 ** sqlite3ApiExit(), to avoid setting the database handle error message.
108973 db->mallocFailed = 0;
108975 sqlite3_mutex_leave(db->mutex);
108976 return z;
108978 #endif /* SQLITE_OMIT_UTF16 */
108981 ** Return the most recent error code generated by an SQLite routine. If NULL is
108982 ** passed to this function, we assume a malloc() failed during sqlite3_open().
108984 SQLITE_API int sqlite3_errcode(sqlite3 *db){
108985 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
108986 return SQLITE_MISUSE_BKPT;
108988 if( !db || db->mallocFailed ){
108989 return SQLITE_NOMEM;
108991 return db->errCode & db->errMask;
108993 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
108994 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
108995 return SQLITE_MISUSE_BKPT;
108997 if( !db || db->mallocFailed ){
108998 return SQLITE_NOMEM;
109000 return db->errCode;
109004 ** Create a new collating function for database "db". The name is zName
109005 ** and the encoding is enc.
109007 static int createCollation(
109008 sqlite3* db,
109009 const char *zName,
109010 u8 enc,
109011 u8 collType,
109012 void* pCtx,
109013 int(*xCompare)(void*,int,const void*,int,const void*),
109014 void(*xDel)(void*)
109016 CollSeq *pColl;
109017 int enc2;
109018 int nName = sqlite3Strlen30(zName);
109020 assert( sqlite3_mutex_held(db->mutex) );
109022 /* If SQLITE_UTF16 is specified as the encoding type, transform this
109023 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
109024 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
109026 enc2 = enc;
109027 testcase( enc2==SQLITE_UTF16 );
109028 testcase( enc2==SQLITE_UTF16_ALIGNED );
109029 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
109030 enc2 = SQLITE_UTF16NATIVE;
109032 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
109033 return SQLITE_MISUSE_BKPT;
109036 /* Check if this call is removing or replacing an existing collation
109037 ** sequence. If so, and there are active VMs, return busy. If there
109038 ** are no active VMs, invalidate any pre-compiled statements.
109040 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
109041 if( pColl && pColl->xCmp ){
109042 if( db->activeVdbeCnt ){
109043 sqlite3Error(db, SQLITE_BUSY,
109044 "unable to delete/modify collation sequence due to active statements");
109045 return SQLITE_BUSY;
109047 sqlite3ExpirePreparedStatements(db);
109049 /* If collation sequence pColl was created directly by a call to
109050 ** sqlite3_create_collation, and not generated by synthCollSeq(),
109051 ** then any copies made by synthCollSeq() need to be invalidated.
109052 ** Also, collation destructor - CollSeq.xDel() - function may need
109053 ** to be called.
109055 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
109056 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
109057 int j;
109058 for(j=0; j<3; j++){
109059 CollSeq *p = &aColl[j];
109060 if( p->enc==pColl->enc ){
109061 if( p->xDel ){
109062 p->xDel(p->pUser);
109064 p->xCmp = 0;
109070 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
109071 if( pColl==0 ) return SQLITE_NOMEM;
109072 pColl->xCmp = xCompare;
109073 pColl->pUser = pCtx;
109074 pColl->xDel = xDel;
109075 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
109076 pColl->type = collType;
109077 sqlite3Error(db, SQLITE_OK, 0);
109078 return SQLITE_OK;
109083 ** This array defines hard upper bounds on limit values. The
109084 ** initializer must be kept in sync with the SQLITE_LIMIT_*
109085 ** #defines in sqlite3.h.
109087 static const int aHardLimit[] = {
109088 SQLITE_MAX_LENGTH,
109089 SQLITE_MAX_SQL_LENGTH,
109090 SQLITE_MAX_COLUMN,
109091 SQLITE_MAX_EXPR_DEPTH,
109092 SQLITE_MAX_COMPOUND_SELECT,
109093 SQLITE_MAX_VDBE_OP,
109094 SQLITE_MAX_FUNCTION_ARG,
109095 SQLITE_MAX_ATTACHED,
109096 SQLITE_MAX_LIKE_PATTERN_LENGTH,
109097 SQLITE_MAX_VARIABLE_NUMBER,
109098 SQLITE_MAX_TRIGGER_DEPTH,
109102 ** Make sure the hard limits are set to reasonable values
109104 #if SQLITE_MAX_LENGTH<100
109105 # error SQLITE_MAX_LENGTH must be at least 100
109106 #endif
109107 #if SQLITE_MAX_SQL_LENGTH<100
109108 # error SQLITE_MAX_SQL_LENGTH must be at least 100
109109 #endif
109110 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
109111 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
109112 #endif
109113 #if SQLITE_MAX_COMPOUND_SELECT<2
109114 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
109115 #endif
109116 #if SQLITE_MAX_VDBE_OP<40
109117 # error SQLITE_MAX_VDBE_OP must be at least 40
109118 #endif
109119 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
109120 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
109121 #endif
109122 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
109123 # error SQLITE_MAX_ATTACHED must be between 0 and 62
109124 #endif
109125 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
109126 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
109127 #endif
109128 #if SQLITE_MAX_COLUMN>32767
109129 # error SQLITE_MAX_COLUMN must not exceed 32767
109130 #endif
109131 #if SQLITE_MAX_TRIGGER_DEPTH<1
109132 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
109133 #endif
109137 ** Change the value of a limit. Report the old value.
109138 ** If an invalid limit index is supplied, report -1.
109139 ** Make no changes but still report the old value if the
109140 ** new limit is negative.
109142 ** A new lower limit does not shrink existing constructs.
109143 ** It merely prevents new constructs that exceed the limit
109144 ** from forming.
109146 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
109147 int oldLimit;
109150 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
109151 ** there is a hard upper bound set at compile-time by a C preprocessor
109152 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
109153 ** "_MAX_".)
109155 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
109156 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
109157 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
109158 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
109159 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
109160 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
109161 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
109162 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
109163 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
109164 SQLITE_MAX_LIKE_PATTERN_LENGTH );
109165 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
109166 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
109167 assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
109170 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
109171 return -1;
109173 oldLimit = db->aLimit[limitId];
109174 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
109175 if( newLimit>aHardLimit[limitId] ){
109176 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
109178 db->aLimit[limitId] = newLimit;
109180 return oldLimit; /* IMP: R-53341-35419 */
109184 ** This routine does the work of opening a database on behalf of
109185 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
109186 ** is UTF-8 encoded.
109188 static int openDatabase(
109189 const char *zFilename, /* Database filename UTF-8 encoded */
109190 sqlite3 **ppDb, /* OUT: Returned database handle */
109191 unsigned flags, /* Operational flags */
109192 const char *zVfs /* Name of the VFS to use */
109194 sqlite3 *db;
109195 int rc;
109196 int isThreadsafe;
109198 *ppDb = 0;
109199 #ifndef SQLITE_OMIT_AUTOINIT
109200 rc = sqlite3_initialize();
109201 if( rc ) return rc;
109202 #endif
109204 /* Only allow sensible combinations of bits in the flags argument.
109205 ** Throw an error if any non-sense combination is used. If we
109206 ** do not block illegal combinations here, it could trigger
109207 ** assert() statements in deeper layers. Sensible combinations
109208 ** are:
109210 ** 1: SQLITE_OPEN_READONLY
109211 ** 2: SQLITE_OPEN_READWRITE
109212 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
109214 assert( SQLITE_OPEN_READONLY == 0x01 );
109215 assert( SQLITE_OPEN_READWRITE == 0x02 );
109216 assert( SQLITE_OPEN_CREATE == 0x04 );
109217 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
109218 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
109219 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
109220 if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
109222 if( sqlite3GlobalConfig.bCoreMutex==0 ){
109223 isThreadsafe = 0;
109224 }else if( flags & SQLITE_OPEN_NOMUTEX ){
109225 isThreadsafe = 0;
109226 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
109227 isThreadsafe = 1;
109228 }else{
109229 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
109231 if( flags & SQLITE_OPEN_PRIVATECACHE ){
109232 flags &= ~SQLITE_OPEN_SHAREDCACHE;
109233 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
109234 flags |= SQLITE_OPEN_SHAREDCACHE;
109237 /* Remove harmful bits from the flags parameter
109239 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
109240 ** dealt with in the previous code block. Besides these, the only
109241 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
109242 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
109243 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
109244 ** off all other flags.
109246 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
109247 SQLITE_OPEN_EXCLUSIVE |
109248 SQLITE_OPEN_MAIN_DB |
109249 SQLITE_OPEN_TEMP_DB |
109250 SQLITE_OPEN_TRANSIENT_DB |
109251 SQLITE_OPEN_MAIN_JOURNAL |
109252 SQLITE_OPEN_TEMP_JOURNAL |
109253 SQLITE_OPEN_SUBJOURNAL |
109254 SQLITE_OPEN_MASTER_JOURNAL |
109255 SQLITE_OPEN_NOMUTEX |
109256 SQLITE_OPEN_FULLMUTEX |
109257 SQLITE_OPEN_WAL
109260 /* Allocate the sqlite data structure */
109261 db = sqlite3MallocZero( sizeof(sqlite3) );
109262 if( db==0 ) goto opendb_out;
109263 if( isThreadsafe ){
109264 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
109265 if( db->mutex==0 ){
109266 sqlite3_free(db);
109267 db = 0;
109268 goto opendb_out;
109271 sqlite3_mutex_enter(db->mutex);
109272 db->errMask = 0xff;
109273 db->nDb = 2;
109274 db->magic = SQLITE_MAGIC_BUSY;
109275 db->aDb = db->aDbStatic;
109277 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
109278 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
109279 db->autoCommit = 1;
109280 db->nextAutovac = -1;
109281 db->nextPagesize = 0;
109282 db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
109283 #if SQLITE_DEFAULT_FILE_FORMAT<4
109284 | SQLITE_LegacyFileFmt
109285 #endif
109286 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
109287 | SQLITE_LoadExtension
109288 #endif
109289 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
109290 | SQLITE_RecTriggers
109291 #endif
109292 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
109293 | SQLITE_ForeignKeys
109294 #endif
109296 sqlite3HashInit(&db->aCollSeq);
109297 #ifndef SQLITE_OMIT_VIRTUALTABLE
109298 sqlite3HashInit(&db->aModule);
109299 #endif
109301 db->pVfs = sqlite3_vfs_find(zVfs);
109302 if( !db->pVfs ){
109303 rc = SQLITE_ERROR;
109304 sqlite3Error(db, rc, "no such vfs: %s", zVfs);
109305 goto opendb_out;
109308 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
109309 ** and UTF-16, so add a version for each to avoid any unnecessary
109310 ** conversions. The only error that can occur here is a malloc() failure.
109312 createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
109313 binCollFunc, 0);
109314 createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
109315 binCollFunc, 0);
109316 createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
109317 binCollFunc, 0);
109318 createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
109319 binCollFunc, 0);
109320 if( db->mallocFailed ){
109321 goto opendb_out;
109323 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
109324 assert( db->pDfltColl!=0 );
109326 /* Also add a UTF-8 case-insensitive collation sequence. */
109327 createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
109328 nocaseCollatingFunc, 0);
109330 /* Open the backend database driver */
109331 db->openFlags = flags;
109332 rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
109333 flags | SQLITE_OPEN_MAIN_DB);
109334 if( rc!=SQLITE_OK ){
109335 if( rc==SQLITE_IOERR_NOMEM ){
109336 rc = SQLITE_NOMEM;
109338 sqlite3Error(db, rc, 0);
109339 goto opendb_out;
109341 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
109342 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
109345 /* The default safety_level for the main database is 'full'; for the temp
109346 ** database it is 'NONE'. This matches the pager layer defaults.
109348 db->aDb[0].zName = "main";
109349 db->aDb[0].safety_level = 3;
109350 db->aDb[1].zName = "temp";
109351 db->aDb[1].safety_level = 1;
109353 db->magic = SQLITE_MAGIC_OPEN;
109354 if( db->mallocFailed ){
109355 goto opendb_out;
109358 /* Register all built-in functions, but do not attempt to read the
109359 ** database schema yet. This is delayed until the first time the database
109360 ** is accessed.
109362 sqlite3Error(db, SQLITE_OK, 0);
109363 sqlite3RegisterBuiltinFunctions(db);
109365 /* Load automatic extensions - extensions that have been registered
109366 ** using the sqlite3_automatic_extension() API.
109368 sqlite3AutoLoadExtensions(db);
109369 rc = sqlite3_errcode(db);
109370 if( rc!=SQLITE_OK ){
109371 goto opendb_out;
109374 #ifdef SQLITE_ENABLE_FTS1
109375 if( !db->mallocFailed ){
109376 extern int sqlite3Fts1Init(sqlite3*);
109377 rc = sqlite3Fts1Init(db);
109379 #endif
109381 #ifdef SQLITE_ENABLE_FTS2
109382 if( !db->mallocFailed && rc==SQLITE_OK ){
109383 extern int sqlite3Fts2Init(sqlite3*);
109384 rc = sqlite3Fts2Init(db);
109386 #endif
109388 #ifdef SQLITE_ENABLE_FTS3
109389 if( !db->mallocFailed && rc==SQLITE_OK ){
109390 rc = sqlite3Fts3Init(db);
109392 #endif
109394 #ifdef SQLITE_ENABLE_ICU
109395 if( !db->mallocFailed && rc==SQLITE_OK ){
109396 rc = sqlite3IcuInit(db);
109398 #endif
109400 #ifdef SQLITE_ENABLE_RTREE
109401 if( !db->mallocFailed && rc==SQLITE_OK){
109402 rc = sqlite3RtreeInit(db);
109404 #endif
109406 sqlite3Error(db, rc, 0);
109408 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
109409 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
109410 ** mode. Doing nothing at all also makes NORMAL the default.
109412 #ifdef SQLITE_DEFAULT_LOCKING_MODE
109413 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
109414 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
109415 SQLITE_DEFAULT_LOCKING_MODE);
109416 #endif
109418 /* Enable the lookaside-malloc subsystem */
109419 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
109420 sqlite3GlobalConfig.nLookaside);
109422 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
109424 opendb_out:
109425 if( db ){
109426 assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
109427 sqlite3_mutex_leave(db->mutex);
109429 rc = sqlite3_errcode(db);
109430 if( rc==SQLITE_NOMEM ){
109431 sqlite3_close(db);
109432 db = 0;
109433 }else if( rc!=SQLITE_OK ){
109434 db->magic = SQLITE_MAGIC_SICK;
109436 *ppDb = db;
109437 return sqlite3ApiExit(0, rc);
109441 ** Open a new database handle.
109443 SQLITE_API int sqlite3_open(
109444 const char *zFilename,
109445 sqlite3 **ppDb
109447 return openDatabase(zFilename, ppDb,
109448 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
109450 SQLITE_API int sqlite3_open_v2(
109451 const char *filename, /* Database filename (UTF-8) */
109452 sqlite3 **ppDb, /* OUT: SQLite db handle */
109453 int flags, /* Flags */
109454 const char *zVfs /* Name of VFS module to use */
109456 return openDatabase(filename, ppDb, flags, zVfs);
109459 #ifndef SQLITE_OMIT_UTF16
109461 ** Open a new database handle.
109463 SQLITE_API int sqlite3_open16(
109464 const void *zFilename,
109465 sqlite3 **ppDb
109467 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
109468 sqlite3_value *pVal;
109469 int rc;
109471 assert( zFilename );
109472 assert( ppDb );
109473 *ppDb = 0;
109474 #ifndef SQLITE_OMIT_AUTOINIT
109475 rc = sqlite3_initialize();
109476 if( rc ) return rc;
109477 #endif
109478 pVal = sqlite3ValueNew(0);
109479 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
109480 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
109481 if( zFilename8 ){
109482 rc = openDatabase(zFilename8, ppDb,
109483 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
109484 assert( *ppDb || rc==SQLITE_NOMEM );
109485 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
109486 ENC(*ppDb) = SQLITE_UTF16NATIVE;
109488 }else{
109489 rc = SQLITE_NOMEM;
109491 sqlite3ValueFree(pVal);
109493 return sqlite3ApiExit(0, rc);
109495 #endif /* SQLITE_OMIT_UTF16 */
109498 ** Register a new collation sequence with the database handle db.
109500 SQLITE_API int sqlite3_create_collation(
109501 sqlite3* db,
109502 const char *zName,
109503 int enc,
109504 void* pCtx,
109505 int(*xCompare)(void*,int,const void*,int,const void*)
109507 int rc;
109508 sqlite3_mutex_enter(db->mutex);
109509 assert( !db->mallocFailed );
109510 rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
109511 rc = sqlite3ApiExit(db, rc);
109512 sqlite3_mutex_leave(db->mutex);
109513 return rc;
109517 ** Register a new collation sequence with the database handle db.
109519 SQLITE_API int sqlite3_create_collation_v2(
109520 sqlite3* db,
109521 const char *zName,
109522 int enc,
109523 void* pCtx,
109524 int(*xCompare)(void*,int,const void*,int,const void*),
109525 void(*xDel)(void*)
109527 int rc;
109528 sqlite3_mutex_enter(db->mutex);
109529 assert( !db->mallocFailed );
109530 rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
109531 rc = sqlite3ApiExit(db, rc);
109532 sqlite3_mutex_leave(db->mutex);
109533 return rc;
109536 #ifndef SQLITE_OMIT_UTF16
109538 ** Register a new collation sequence with the database handle db.
109540 SQLITE_API int sqlite3_create_collation16(
109541 sqlite3* db,
109542 const void *zName,
109543 int enc,
109544 void* pCtx,
109545 int(*xCompare)(void*,int,const void*,int,const void*)
109547 int rc = SQLITE_OK;
109548 char *zName8;
109549 sqlite3_mutex_enter(db->mutex);
109550 assert( !db->mallocFailed );
109551 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
109552 if( zName8 ){
109553 rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
109554 sqlite3DbFree(db, zName8);
109556 rc = sqlite3ApiExit(db, rc);
109557 sqlite3_mutex_leave(db->mutex);
109558 return rc;
109560 #endif /* SQLITE_OMIT_UTF16 */
109563 ** Register a collation sequence factory callback with the database handle
109564 ** db. Replace any previously installed collation sequence factory.
109566 SQLITE_API int sqlite3_collation_needed(
109567 sqlite3 *db,
109568 void *pCollNeededArg,
109569 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
109571 sqlite3_mutex_enter(db->mutex);
109572 db->xCollNeeded = xCollNeeded;
109573 db->xCollNeeded16 = 0;
109574 db->pCollNeededArg = pCollNeededArg;
109575 sqlite3_mutex_leave(db->mutex);
109576 return SQLITE_OK;
109579 #ifndef SQLITE_OMIT_UTF16
109581 ** Register a collation sequence factory callback with the database handle
109582 ** db. Replace any previously installed collation sequence factory.
109584 SQLITE_API int sqlite3_collation_needed16(
109585 sqlite3 *db,
109586 void *pCollNeededArg,
109587 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
109589 sqlite3_mutex_enter(db->mutex);
109590 db->xCollNeeded = 0;
109591 db->xCollNeeded16 = xCollNeeded16;
109592 db->pCollNeededArg = pCollNeededArg;
109593 sqlite3_mutex_leave(db->mutex);
109594 return SQLITE_OK;
109596 #endif /* SQLITE_OMIT_UTF16 */
109598 #ifndef SQLITE_OMIT_DEPRECATED
109600 ** This function is now an anachronism. It used to be used to recover from a
109601 ** malloc() failure, but SQLite now does this automatically.
109603 SQLITE_API int sqlite3_global_recover(void){
109604 return SQLITE_OK;
109606 #endif
109609 ** Test to see whether or not the database connection is in autocommit
109610 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
109611 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
109612 ** by the next COMMIT or ROLLBACK.
109614 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
109616 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
109617 return db->autoCommit;
109621 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
109622 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
109623 ** constants. They server two purposes:
109625 ** 1. Serve as a convenient place to set a breakpoint in a debugger
109626 ** to detect when version error conditions occurs.
109628 ** 2. Invoke sqlite3_log() to provide the source code location where
109629 ** a low-level error is first detected.
109631 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
109632 testcase( sqlite3GlobalConfig.xLog!=0 );
109633 sqlite3_log(SQLITE_CORRUPT,
109634 "database corruption at line %d of [%.10s]",
109635 lineno, 20+sqlite3_sourceid());
109636 return SQLITE_CORRUPT;
109638 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
109639 testcase( sqlite3GlobalConfig.xLog!=0 );
109640 sqlite3_log(SQLITE_MISUSE,
109641 "misuse at line %d of [%.10s]",
109642 lineno, 20+sqlite3_sourceid());
109643 return SQLITE_MISUSE;
109645 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
109646 testcase( sqlite3GlobalConfig.xLog!=0 );
109647 sqlite3_log(SQLITE_CANTOPEN,
109648 "cannot open file at line %d of [%.10s]",
109649 lineno, 20+sqlite3_sourceid());
109650 return SQLITE_CANTOPEN;
109654 #ifndef SQLITE_OMIT_DEPRECATED
109656 ** This is a convenience routine that makes sure that all thread-specific
109657 ** data for this thread has been deallocated.
109659 ** SQLite no longer uses thread-specific data so this routine is now a
109660 ** no-op. It is retained for historical compatibility.
109662 SQLITE_API void sqlite3_thread_cleanup(void){
109664 #endif
109667 ** Return meta information about a specific column of a database table.
109668 ** See comment in sqlite3.h (sqlite.h.in) for details.
109670 #ifdef SQLITE_ENABLE_COLUMN_METADATA
109671 SQLITE_API int sqlite3_table_column_metadata(
109672 sqlite3 *db, /* Connection handle */
109673 const char *zDbName, /* Database name or NULL */
109674 const char *zTableName, /* Table name */
109675 const char *zColumnName, /* Column name */
109676 char const **pzDataType, /* OUTPUT: Declared data type */
109677 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
109678 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
109679 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
109680 int *pAutoinc /* OUTPUT: True if column is auto-increment */
109682 int rc;
109683 char *zErrMsg = 0;
109684 Table *pTab = 0;
109685 Column *pCol = 0;
109686 int iCol;
109688 char const *zDataType = 0;
109689 char const *zCollSeq = 0;
109690 int notnull = 0;
109691 int primarykey = 0;
109692 int autoinc = 0;
109694 /* Ensure the database schema has been loaded */
109695 sqlite3_mutex_enter(db->mutex);
109696 sqlite3BtreeEnterAll(db);
109697 rc = sqlite3Init(db, &zErrMsg);
109698 if( SQLITE_OK!=rc ){
109699 goto error_out;
109702 /* Locate the table in question */
109703 pTab = sqlite3FindTable(db, zTableName, zDbName);
109704 if( !pTab || pTab->pSelect ){
109705 pTab = 0;
109706 goto error_out;
109709 /* Find the column for which info is requested */
109710 if( sqlite3IsRowid(zColumnName) ){
109711 iCol = pTab->iPKey;
109712 if( iCol>=0 ){
109713 pCol = &pTab->aCol[iCol];
109715 }else{
109716 for(iCol=0; iCol<pTab->nCol; iCol++){
109717 pCol = &pTab->aCol[iCol];
109718 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
109719 break;
109722 if( iCol==pTab->nCol ){
109723 pTab = 0;
109724 goto error_out;
109728 /* The following block stores the meta information that will be returned
109729 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
109730 ** and autoinc. At this point there are two possibilities:
109732 ** 1. The specified column name was rowid", "oid" or "_rowid_"
109733 ** and there is no explicitly declared IPK column.
109735 ** 2. The table is not a view and the column name identified an
109736 ** explicitly declared column. Copy meta information from *pCol.
109738 if( pCol ){
109739 zDataType = pCol->zType;
109740 zCollSeq = pCol->zColl;
109741 notnull = pCol->notNull!=0;
109742 primarykey = pCol->isPrimKey!=0;
109743 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
109744 }else{
109745 zDataType = "INTEGER";
109746 primarykey = 1;
109748 if( !zCollSeq ){
109749 zCollSeq = "BINARY";
109752 error_out:
109753 sqlite3BtreeLeaveAll(db);
109755 /* Whether the function call succeeded or failed, set the output parameters
109756 ** to whatever their local counterparts contain. If an error did occur,
109757 ** this has the effect of zeroing all output parameters.
109759 if( pzDataType ) *pzDataType = zDataType;
109760 if( pzCollSeq ) *pzCollSeq = zCollSeq;
109761 if( pNotNull ) *pNotNull = notnull;
109762 if( pPrimaryKey ) *pPrimaryKey = primarykey;
109763 if( pAutoinc ) *pAutoinc = autoinc;
109765 if( SQLITE_OK==rc && !pTab ){
109766 sqlite3DbFree(db, zErrMsg);
109767 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
109768 zColumnName);
109769 rc = SQLITE_ERROR;
109771 sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
109772 sqlite3DbFree(db, zErrMsg);
109773 rc = sqlite3ApiExit(db, rc);
109774 sqlite3_mutex_leave(db->mutex);
109775 return rc;
109777 #endif
109780 ** Sleep for a little while. Return the amount of time slept.
109782 SQLITE_API int sqlite3_sleep(int ms){
109783 sqlite3_vfs *pVfs;
109784 int rc;
109785 pVfs = sqlite3_vfs_find(0);
109786 if( pVfs==0 ) return 0;
109788 /* This function works in milliseconds, but the underlying OsSleep()
109789 ** API uses microseconds. Hence the 1000's.
109791 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
109792 return rc;
109796 ** Enable or disable the extended result codes.
109798 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
109799 sqlite3_mutex_enter(db->mutex);
109800 db->errMask = onoff ? 0xffffffff : 0xff;
109801 sqlite3_mutex_leave(db->mutex);
109802 return SQLITE_OK;
109806 ** Invoke the xFileControl method on a particular database.
109808 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
109809 int rc = SQLITE_ERROR;
109810 int iDb;
109811 sqlite3_mutex_enter(db->mutex);
109812 if( zDbName==0 ){
109813 iDb = 0;
109814 }else{
109815 for(iDb=0; iDb<db->nDb; iDb++){
109816 if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
109819 if( iDb<db->nDb ){
109820 Btree *pBtree = db->aDb[iDb].pBt;
109821 if( pBtree ){
109822 Pager *pPager;
109823 sqlite3_file *fd;
109824 sqlite3BtreeEnter(pBtree);
109825 pPager = sqlite3BtreePager(pBtree);
109826 assert( pPager!=0 );
109827 fd = sqlite3PagerFile(pPager);
109828 assert( fd!=0 );
109829 if( op==SQLITE_FCNTL_FILE_POINTER ){
109830 *(sqlite3_file**)pArg = fd;
109831 rc = SQLITE_OK;
109832 }else if( fd->pMethods ){
109833 rc = sqlite3OsFileControl(fd, op, pArg);
109834 }else{
109835 rc = SQLITE_NOTFOUND;
109837 sqlite3BtreeLeave(pBtree);
109840 sqlite3_mutex_leave(db->mutex);
109841 return rc;
109845 ** Interface to the testing logic.
109847 SQLITE_API int sqlite3_test_control(int op, ...){
109848 int rc = 0;
109849 #ifndef SQLITE_OMIT_BUILTIN_TEST
109850 va_list ap;
109851 va_start(ap, op);
109852 switch( op ){
109855 ** Save the current state of the PRNG.
109857 case SQLITE_TESTCTRL_PRNG_SAVE: {
109858 sqlite3PrngSaveState();
109859 break;
109863 ** Restore the state of the PRNG to the last state saved using
109864 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
109865 ** this verb acts like PRNG_RESET.
109867 case SQLITE_TESTCTRL_PRNG_RESTORE: {
109868 sqlite3PrngRestoreState();
109869 break;
109873 ** Reset the PRNG back to its uninitialized state. The next call
109874 ** to sqlite3_randomness() will reseed the PRNG using a single call
109875 ** to the xRandomness method of the default VFS.
109877 case SQLITE_TESTCTRL_PRNG_RESET: {
109878 sqlite3PrngResetState();
109879 break;
109883 ** sqlite3_test_control(BITVEC_TEST, size, program)
109885 ** Run a test against a Bitvec object of size. The program argument
109886 ** is an array of integers that defines the test. Return -1 on a
109887 ** memory allocation error, 0 on success, or non-zero for an error.
109888 ** See the sqlite3BitvecBuiltinTest() for additional information.
109890 case SQLITE_TESTCTRL_BITVEC_TEST: {
109891 int sz = va_arg(ap, int);
109892 int *aProg = va_arg(ap, int*);
109893 rc = sqlite3BitvecBuiltinTest(sz, aProg);
109894 break;
109898 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
109900 ** Register hooks to call to indicate which malloc() failures
109901 ** are benign.
109903 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
109904 typedef void (*void_function)(void);
109905 void_function xBenignBegin;
109906 void_function xBenignEnd;
109907 xBenignBegin = va_arg(ap, void_function);
109908 xBenignEnd = va_arg(ap, void_function);
109909 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
109910 break;
109914 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
109916 ** Set the PENDING byte to the value in the argument, if X>0.
109917 ** Make no changes if X==0. Return the value of the pending byte
109918 ** as it existing before this routine was called.
109920 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
109921 ** an incompatible database file format. Changing the PENDING byte
109922 ** while any database connection is open results in undefined and
109923 ** dileterious behavior.
109925 case SQLITE_TESTCTRL_PENDING_BYTE: {
109926 rc = PENDING_BYTE;
109927 #ifndef SQLITE_OMIT_WSD
109929 unsigned int newVal = va_arg(ap, unsigned int);
109930 if( newVal ) sqlite3PendingByte = newVal;
109932 #endif
109933 break;
109937 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
109939 ** This action provides a run-time test to see whether or not
109940 ** assert() was enabled at compile-time. If X is true and assert()
109941 ** is enabled, then the return value is true. If X is true and
109942 ** assert() is disabled, then the return value is zero. If X is
109943 ** false and assert() is enabled, then the assertion fires and the
109944 ** process aborts. If X is false and assert() is disabled, then the
109945 ** return value is zero.
109947 case SQLITE_TESTCTRL_ASSERT: {
109948 volatile int x = 0;
109949 assert( (x = va_arg(ap,int))!=0 );
109950 rc = x;
109951 break;
109956 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
109958 ** This action provides a run-time test to see how the ALWAYS and
109959 ** NEVER macros were defined at compile-time.
109961 ** The return value is ALWAYS(X).
109963 ** The recommended test is X==2. If the return value is 2, that means
109964 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
109965 ** default setting. If the return value is 1, then ALWAYS() is either
109966 ** hard-coded to true or else it asserts if its argument is false.
109967 ** The first behavior (hard-coded to true) is the case if
109968 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
109969 ** behavior (assert if the argument to ALWAYS() is false) is the case if
109970 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
109972 ** The run-time test procedure might look something like this:
109974 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
109975 ** // ALWAYS() and NEVER() are no-op pass-through macros
109976 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
109977 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
109978 ** }else{
109979 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
109982 case SQLITE_TESTCTRL_ALWAYS: {
109983 int x = va_arg(ap,int);
109984 rc = ALWAYS(x);
109985 break;
109988 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
109990 ** Set the nReserve size to N for the main database on the database
109991 ** connection db.
109993 case SQLITE_TESTCTRL_RESERVE: {
109994 sqlite3 *db = va_arg(ap, sqlite3*);
109995 int x = va_arg(ap,int);
109996 sqlite3_mutex_enter(db->mutex);
109997 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
109998 sqlite3_mutex_leave(db->mutex);
109999 break;
110002 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
110004 ** Enable or disable various optimizations for testing purposes. The
110005 ** argument N is a bitmask of optimizations to be disabled. For normal
110006 ** operation N should be 0. The idea is that a test program (like the
110007 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
110008 ** with various optimizations disabled to verify that the same answer
110009 ** is obtained in every case.
110011 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
110012 sqlite3 *db = va_arg(ap, sqlite3*);
110013 int x = va_arg(ap,int);
110014 db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
110015 break;
110018 #ifdef SQLITE_N_KEYWORD
110019 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
110021 ** If zWord is a keyword recognized by the parser, then return the
110022 ** number of keywords. Or if zWord is not a keyword, return 0.
110024 ** This test feature is only available in the amalgamation since
110025 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
110026 ** is built using separate source files.
110028 case SQLITE_TESTCTRL_ISKEYWORD: {
110029 const char *zWord = va_arg(ap, const char*);
110030 int n = sqlite3Strlen30(zWord);
110031 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
110032 break;
110034 #endif
110036 /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
110038 ** Return the size of a pcache header in bytes.
110040 case SQLITE_TESTCTRL_PGHDRSZ: {
110041 rc = sizeof(PgHdr);
110042 break;
110045 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
110047 ** Pass pFree into sqlite3ScratchFree().
110048 ** If sz>0 then allocate a scratch buffer into pNew.
110050 case SQLITE_TESTCTRL_SCRATCHMALLOC: {
110051 void *pFree, **ppNew;
110052 int sz;
110053 sz = va_arg(ap, int);
110054 ppNew = va_arg(ap, void**);
110055 pFree = va_arg(ap, void*);
110056 if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
110057 sqlite3ScratchFree(pFree);
110058 break;
110062 va_end(ap);
110063 #endif /* SQLITE_OMIT_BUILTIN_TEST */
110064 return rc;
110067 /************** End of main.c ************************************************/
110068 /************** Begin file notify.c ******************************************/
110070 ** 2009 March 3
110072 ** The author disclaims copyright to this source code. In place of
110073 ** a legal notice, here is a blessing:
110075 ** May you do good and not evil.
110076 ** May you find forgiveness for yourself and forgive others.
110077 ** May you share freely, never taking more than you give.
110079 *************************************************************************
110081 ** This file contains the implementation of the sqlite3_unlock_notify()
110082 ** API method and its associated functionality.
110085 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
110086 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
110089 ** Public interfaces:
110091 ** sqlite3ConnectionBlocked()
110092 ** sqlite3ConnectionUnlocked()
110093 ** sqlite3ConnectionClosed()
110094 ** sqlite3_unlock_notify()
110097 #define assertMutexHeld() \
110098 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
110101 ** Head of a linked list of all sqlite3 objects created by this process
110102 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
110103 ** is not NULL. This variable may only accessed while the STATIC_MASTER
110104 ** mutex is held.
110106 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
110108 #ifndef NDEBUG
110110 ** This function is a complex assert() that verifies the following
110111 ** properties of the blocked connections list:
110113 ** 1) Each entry in the list has a non-NULL value for either
110114 ** pUnlockConnection or pBlockingConnection, or both.
110116 ** 2) All entries in the list that share a common value for
110117 ** xUnlockNotify are grouped together.
110119 ** 3) If the argument db is not NULL, then none of the entries in the
110120 ** blocked connections list have pUnlockConnection or pBlockingConnection
110121 ** set to db. This is used when closing connection db.
110123 static void checkListProperties(sqlite3 *db){
110124 sqlite3 *p;
110125 for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
110126 int seen = 0;
110127 sqlite3 *p2;
110129 /* Verify property (1) */
110130 assert( p->pUnlockConnection || p->pBlockingConnection );
110132 /* Verify property (2) */
110133 for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
110134 if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
110135 assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
110136 assert( db==0 || p->pUnlockConnection!=db );
110137 assert( db==0 || p->pBlockingConnection!=db );
110141 #else
110142 # define checkListProperties(x)
110143 #endif
110146 ** Remove connection db from the blocked connections list. If connection
110147 ** db is not currently a part of the list, this function is a no-op.
110149 static void removeFromBlockedList(sqlite3 *db){
110150 sqlite3 **pp;
110151 assertMutexHeld();
110152 for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
110153 if( *pp==db ){
110154 *pp = (*pp)->pNextBlocked;
110155 break;
110161 ** Add connection db to the blocked connections list. It is assumed
110162 ** that it is not already a part of the list.
110164 static void addToBlockedList(sqlite3 *db){
110165 sqlite3 **pp;
110166 assertMutexHeld();
110168 pp=&sqlite3BlockedList;
110169 *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
110170 pp=&(*pp)->pNextBlocked
110172 db->pNextBlocked = *pp;
110173 *pp = db;
110177 ** Obtain the STATIC_MASTER mutex.
110179 static void enterMutex(void){
110180 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
110181 checkListProperties(0);
110185 ** Release the STATIC_MASTER mutex.
110187 static void leaveMutex(void){
110188 assertMutexHeld();
110189 checkListProperties(0);
110190 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
110194 ** Register an unlock-notify callback.
110196 ** This is called after connection "db" has attempted some operation
110197 ** but has received an SQLITE_LOCKED error because another connection
110198 ** (call it pOther) in the same process was busy using the same shared
110199 ** cache. pOther is found by looking at db->pBlockingConnection.
110201 ** If there is no blocking connection, the callback is invoked immediately,
110202 ** before this routine returns.
110204 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
110205 ** a deadlock.
110207 ** Otherwise, make arrangements to invoke xNotify when pOther drops
110208 ** its locks.
110210 ** Each call to this routine overrides any prior callbacks registered
110211 ** on the same "db". If xNotify==0 then any prior callbacks are immediately
110212 ** cancelled.
110214 SQLITE_API int sqlite3_unlock_notify(
110215 sqlite3 *db,
110216 void (*xNotify)(void **, int),
110217 void *pArg
110219 int rc = SQLITE_OK;
110221 sqlite3_mutex_enter(db->mutex);
110222 enterMutex();
110224 if( xNotify==0 ){
110225 removeFromBlockedList(db);
110226 db->pBlockingConnection = 0;
110227 db->pUnlockConnection = 0;
110228 db->xUnlockNotify = 0;
110229 db->pUnlockArg = 0;
110230 }else if( 0==db->pBlockingConnection ){
110231 /* The blocking transaction has been concluded. Or there never was a
110232 ** blocking transaction. In either case, invoke the notify callback
110233 ** immediately.
110235 xNotify(&pArg, 1);
110236 }else{
110237 sqlite3 *p;
110239 for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
110240 if( p ){
110241 rc = SQLITE_LOCKED; /* Deadlock detected. */
110242 }else{
110243 db->pUnlockConnection = db->pBlockingConnection;
110244 db->xUnlockNotify = xNotify;
110245 db->pUnlockArg = pArg;
110246 removeFromBlockedList(db);
110247 addToBlockedList(db);
110251 leaveMutex();
110252 assert( !db->mallocFailed );
110253 sqlite3Error(db, rc, (rc?"database is deadlocked":0));
110254 sqlite3_mutex_leave(db->mutex);
110255 return rc;
110259 ** This function is called while stepping or preparing a statement
110260 ** associated with connection db. The operation will return SQLITE_LOCKED
110261 ** to the user because it requires a lock that will not be available
110262 ** until connection pBlocker concludes its current transaction.
110264 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
110265 enterMutex();
110266 if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
110267 addToBlockedList(db);
110269 db->pBlockingConnection = pBlocker;
110270 leaveMutex();
110274 ** This function is called when
110275 ** the transaction opened by database db has just finished. Locks held
110276 ** by database connection db have been released.
110278 ** This function loops through each entry in the blocked connections
110279 ** list and does the following:
110281 ** 1) If the sqlite3.pBlockingConnection member of a list entry is
110282 ** set to db, then set pBlockingConnection=0.
110284 ** 2) If the sqlite3.pUnlockConnection member of a list entry is
110285 ** set to db, then invoke the configured unlock-notify callback and
110286 ** set pUnlockConnection=0.
110288 ** 3) If the two steps above mean that pBlockingConnection==0 and
110289 ** pUnlockConnection==0, remove the entry from the blocked connections
110290 ** list.
110292 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
110293 void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
110294 int nArg = 0; /* Number of entries in aArg[] */
110295 sqlite3 **pp; /* Iterator variable */
110296 void **aArg; /* Arguments to the unlock callback */
110297 void **aDyn = 0; /* Dynamically allocated space for aArg[] */
110298 void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
110300 aArg = aStatic;
110301 enterMutex(); /* Enter STATIC_MASTER mutex */
110303 /* This loop runs once for each entry in the blocked-connections list. */
110304 for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
110305 sqlite3 *p = *pp;
110307 /* Step 1. */
110308 if( p->pBlockingConnection==db ){
110309 p->pBlockingConnection = 0;
110312 /* Step 2. */
110313 if( p->pUnlockConnection==db ){
110314 assert( p->xUnlockNotify );
110315 if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
110316 xUnlockNotify(aArg, nArg);
110317 nArg = 0;
110320 sqlite3BeginBenignMalloc();
110321 assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
110322 assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
110323 if( (!aDyn && nArg==(int)ArraySize(aStatic))
110324 || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
110326 /* The aArg[] array needs to grow. */
110327 void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
110328 if( pNew ){
110329 memcpy(pNew, aArg, nArg*sizeof(void *));
110330 sqlite3_free(aDyn);
110331 aDyn = aArg = pNew;
110332 }else{
110333 /* This occurs when the array of context pointers that need to
110334 ** be passed to the unlock-notify callback is larger than the
110335 ** aStatic[] array allocated on the stack and the attempt to
110336 ** allocate a larger array from the heap has failed.
110338 ** This is a difficult situation to handle. Returning an error
110339 ** code to the caller is insufficient, as even if an error code
110340 ** is returned the transaction on connection db will still be
110341 ** closed and the unlock-notify callbacks on blocked connections
110342 ** will go unissued. This might cause the application to wait
110343 ** indefinitely for an unlock-notify callback that will never
110344 ** arrive.
110346 ** Instead, invoke the unlock-notify callback with the context
110347 ** array already accumulated. We can then clear the array and
110348 ** begin accumulating any further context pointers without
110349 ** requiring any dynamic allocation. This is sub-optimal because
110350 ** it means that instead of one callback with a large array of
110351 ** context pointers the application will receive two or more
110352 ** callbacks with smaller arrays of context pointers, which will
110353 ** reduce the applications ability to prioritize multiple
110354 ** connections. But it is the best that can be done under the
110355 ** circumstances.
110357 xUnlockNotify(aArg, nArg);
110358 nArg = 0;
110361 sqlite3EndBenignMalloc();
110363 aArg[nArg++] = p->pUnlockArg;
110364 xUnlockNotify = p->xUnlockNotify;
110365 p->pUnlockConnection = 0;
110366 p->xUnlockNotify = 0;
110367 p->pUnlockArg = 0;
110370 /* Step 3. */
110371 if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
110372 /* Remove connection p from the blocked connections list. */
110373 *pp = p->pNextBlocked;
110374 p->pNextBlocked = 0;
110375 }else{
110376 pp = &p->pNextBlocked;
110380 if( nArg!=0 ){
110381 xUnlockNotify(aArg, nArg);
110383 sqlite3_free(aDyn);
110384 leaveMutex(); /* Leave STATIC_MASTER mutex */
110388 ** This is called when the database connection passed as an argument is
110389 ** being closed. The connection is removed from the blocked list.
110391 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
110392 sqlite3ConnectionUnlocked(db);
110393 enterMutex();
110394 removeFromBlockedList(db);
110395 checkListProperties(db);
110396 leaveMutex();
110398 #endif
110400 /************** End of notify.c **********************************************/
110401 /************** Begin file fts3.c ********************************************/
110403 ** 2006 Oct 10
110405 ** The author disclaims copyright to this source code. In place of
110406 ** a legal notice, here is a blessing:
110408 ** May you do good and not evil.
110409 ** May you find forgiveness for yourself and forgive others.
110410 ** May you share freely, never taking more than you give.
110412 ******************************************************************************
110414 ** This is an SQLite module implementing full-text search.
110418 ** The code in this file is only compiled if:
110420 ** * The FTS3 module is being built as an extension
110421 ** (in which case SQLITE_CORE is not defined), or
110423 ** * The FTS3 module is being built into the core of
110424 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
110427 /* The full-text index is stored in a series of b+tree (-like)
110428 ** structures called segments which map terms to doclists. The
110429 ** structures are like b+trees in layout, but are constructed from the
110430 ** bottom up in optimal fashion and are not updatable. Since trees
110431 ** are built from the bottom up, things will be described from the
110432 ** bottom up.
110435 **** Varints ****
110436 ** The basic unit of encoding is a variable-length integer called a
110437 ** varint. We encode variable-length integers in little-endian order
110438 ** using seven bits * per byte as follows:
110440 ** KEY:
110441 ** A = 0xxxxxxx 7 bits of data and one flag bit
110442 ** B = 1xxxxxxx 7 bits of data and one flag bit
110444 ** 7 bits - A
110445 ** 14 bits - BA
110446 ** 21 bits - BBA
110447 ** and so on.
110449 ** This is similar in concept to how sqlite encodes "varints" but
110450 ** the encoding is not the same. SQLite varints are big-endian
110451 ** are are limited to 9 bytes in length whereas FTS3 varints are
110452 ** little-endian and can be up to 10 bytes in length (in theory).
110454 ** Example encodings:
110456 ** 1: 0x01
110457 ** 127: 0x7f
110458 ** 128: 0x81 0x00
110461 **** Document lists ****
110462 ** A doclist (document list) holds a docid-sorted list of hits for a
110463 ** given term. Doclists hold docids and associated token positions.
110464 ** A docid is the unique integer identifier for a single document.
110465 ** A position is the index of a word within the document. The first
110466 ** word of the document has a position of 0.
110468 ** FTS3 used to optionally store character offsets using a compile-time
110469 ** option. But that functionality is no longer supported.
110471 ** A doclist is stored like this:
110473 ** array {
110474 ** varint docid;
110475 ** array { (position list for column 0)
110476 ** varint position; (2 more than the delta from previous position)
110478 ** array {
110479 ** varint POS_COLUMN; (marks start of position list for new column)
110480 ** varint column; (index of new column)
110481 ** array {
110482 ** varint position; (2 more than the delta from previous position)
110485 ** varint POS_END; (marks end of positions for this document.
110488 ** Here, array { X } means zero or more occurrences of X, adjacent in
110489 ** memory. A "position" is an index of a token in the token stream
110490 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
110491 ** in the same logical place as the position element, and act as sentinals
110492 ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
110493 ** The positions numbers are not stored literally but rather as two more
110494 ** than the difference from the prior position, or the just the position plus
110495 ** 2 for the first position. Example:
110497 ** label: A B C D E F G H I J K
110498 ** value: 123 5 9 1 1 14 35 0 234 72 0
110500 ** The 123 value is the first docid. For column zero in this document
110501 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
110502 ** at D signals the start of a new column; the 1 at E indicates that the
110503 ** new column is column number 1. There are two positions at 12 and 45
110504 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
110505 ** 234 at I is the next docid. It has one position 72 (72-2) and then
110506 ** terminates with the 0 at K.
110508 ** A "position-list" is the list of positions for multiple columns for
110509 ** a single docid. A "column-list" is the set of positions for a single
110510 ** column. Hence, a position-list consists of one or more column-lists,
110511 ** a document record consists of a docid followed by a position-list and
110512 ** a doclist consists of one or more document records.
110514 ** A bare doclist omits the position information, becoming an
110515 ** array of varint-encoded docids.
110517 **** Segment leaf nodes ****
110518 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
110519 ** nodes are written using LeafWriter, and read using LeafReader (to
110520 ** iterate through a single leaf node's data) and LeavesReader (to
110521 ** iterate through a segment's entire leaf layer). Leaf nodes have
110522 ** the format:
110524 ** varint iHeight; (height from leaf level, always 0)
110525 ** varint nTerm; (length of first term)
110526 ** char pTerm[nTerm]; (content of first term)
110527 ** varint nDoclist; (length of term's associated doclist)
110528 ** char pDoclist[nDoclist]; (content of doclist)
110529 ** array {
110530 ** (further terms are delta-encoded)
110531 ** varint nPrefix; (length of prefix shared with previous term)
110532 ** varint nSuffix; (length of unshared suffix)
110533 ** char pTermSuffix[nSuffix];(unshared suffix of next term)
110534 ** varint nDoclist; (length of term's associated doclist)
110535 ** char pDoclist[nDoclist]; (content of doclist)
110538 ** Here, array { X } means zero or more occurrences of X, adjacent in
110539 ** memory.
110541 ** Leaf nodes are broken into blocks which are stored contiguously in
110542 ** the %_segments table in sorted order. This means that when the end
110543 ** of a node is reached, the next term is in the node with the next
110544 ** greater node id.
110546 ** New data is spilled to a new leaf node when the current node
110547 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
110548 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
110549 ** node (a leaf node with a single term and doclist). The goal of
110550 ** these settings is to pack together groups of small doclists while
110551 ** making it efficient to directly access large doclists. The
110552 ** assumption is that large doclists represent terms which are more
110553 ** likely to be query targets.
110555 ** TODO(shess) It may be useful for blocking decisions to be more
110556 ** dynamic. For instance, it may make more sense to have a 2.5k leaf
110557 ** node rather than splitting into 2k and .5k nodes. My intuition is
110558 ** that this might extend through 2x or 4x the pagesize.
110561 **** Segment interior nodes ****
110562 ** Segment interior nodes store blockids for subtree nodes and terms
110563 ** to describe what data is stored by the each subtree. Interior
110564 ** nodes are written using InteriorWriter, and read using
110565 ** InteriorReader. InteriorWriters are created as needed when
110566 ** SegmentWriter creates new leaf nodes, or when an interior node
110567 ** itself grows too big and must be split. The format of interior
110568 ** nodes:
110570 ** varint iHeight; (height from leaf level, always >0)
110571 ** varint iBlockid; (block id of node's leftmost subtree)
110572 ** optional {
110573 ** varint nTerm; (length of first term)
110574 ** char pTerm[nTerm]; (content of first term)
110575 ** array {
110576 ** (further terms are delta-encoded)
110577 ** varint nPrefix; (length of shared prefix with previous term)
110578 ** varint nSuffix; (length of unshared suffix)
110579 ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
110583 ** Here, optional { X } means an optional element, while array { X }
110584 ** means zero or more occurrences of X, adjacent in memory.
110586 ** An interior node encodes n terms separating n+1 subtrees. The
110587 ** subtree blocks are contiguous, so only the first subtree's blockid
110588 ** is encoded. The subtree at iBlockid will contain all terms less
110589 ** than the first term encoded (or all terms if no term is encoded).
110590 ** Otherwise, for terms greater than or equal to pTerm[i] but less
110591 ** than pTerm[i+1], the subtree for that term will be rooted at
110592 ** iBlockid+i. Interior nodes only store enough term data to
110593 ** distinguish adjacent children (if the rightmost term of the left
110594 ** child is "something", and the leftmost term of the right child is
110595 ** "wicked", only "w" is stored).
110597 ** New data is spilled to a new interior node at the same height when
110598 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
110599 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
110600 ** interior nodes and making the tree too skinny. The interior nodes
110601 ** at a given height are naturally tracked by interior nodes at
110602 ** height+1, and so on.
110605 **** Segment directory ****
110606 ** The segment directory in table %_segdir stores meta-information for
110607 ** merging and deleting segments, and also the root node of the
110608 ** segment's tree.
110610 ** The root node is the top node of the segment's tree after encoding
110611 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
110612 ** This could be either a leaf node or an interior node. If the top
110613 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
110614 ** and a new root interior node is generated (which should always fit
110615 ** within ROOT_MAX because it only needs space for 2 varints, the
110616 ** height and the blockid of the previous root).
110618 ** The meta-information in the segment directory is:
110619 ** level - segment level (see below)
110620 ** idx - index within level
110621 ** - (level,idx uniquely identify a segment)
110622 ** start_block - first leaf node
110623 ** leaves_end_block - last leaf node
110624 ** end_block - last block (including interior nodes)
110625 ** root - contents of root node
110627 ** If the root node is a leaf node, then start_block,
110628 ** leaves_end_block, and end_block are all 0.
110631 **** Segment merging ****
110632 ** To amortize update costs, segments are grouped into levels and
110633 ** merged in batches. Each increase in level represents exponentially
110634 ** more documents.
110636 ** New documents (actually, document updates) are tokenized and
110637 ** written individually (using LeafWriter) to a level 0 segment, with
110638 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
110639 ** level 0 segments are merged into a single level 1 segment. Level 1
110640 ** is populated like level 0, and eventually MERGE_COUNT level 1
110641 ** segments are merged to a single level 2 segment (representing
110642 ** MERGE_COUNT^2 updates), and so on.
110644 ** A segment merge traverses all segments at a given level in
110645 ** parallel, performing a straightforward sorted merge. Since segment
110646 ** leaf nodes are written in to the %_segments table in order, this
110647 ** merge traverses the underlying sqlite disk structures efficiently.
110648 ** After the merge, all segment blocks from the merged level are
110649 ** deleted.
110651 ** MERGE_COUNT controls how often we merge segments. 16 seems to be
110652 ** somewhat of a sweet spot for insertion performance. 32 and 64 show
110653 ** very similar performance numbers to 16 on insertion, though they're
110654 ** a tiny bit slower (perhaps due to more overhead in merge-time
110655 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
110656 ** 16, 2 about 66% slower than 16.
110658 ** At query time, high MERGE_COUNT increases the number of segments
110659 ** which need to be scanned and merged. For instance, with 100k docs
110660 ** inserted:
110662 ** MERGE_COUNT segments
110663 ** 16 25
110664 ** 8 12
110665 ** 4 10
110666 ** 2 6
110668 ** This appears to have only a moderate impact on queries for very
110669 ** frequent terms (which are somewhat dominated by segment merge
110670 ** costs), and infrequent and non-existent terms still seem to be fast
110671 ** even with many segments.
110673 ** TODO(shess) That said, it would be nice to have a better query-side
110674 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
110675 ** optimizations to things like doclist merging will swing the sweet
110676 ** spot around.
110680 **** Handling of deletions and updates ****
110681 ** Since we're using a segmented structure, with no docid-oriented
110682 ** index into the term index, we clearly cannot simply update the term
110683 ** index when a document is deleted or updated. For deletions, we
110684 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
110685 ** we simply write the new doclist. Segment merges overwrite older
110686 ** data for a particular docid with newer data, so deletes or updates
110687 ** will eventually overtake the earlier data and knock it out. The
110688 ** query logic likewise merges doclists so that newer data knocks out
110689 ** older data.
110691 ** TODO(shess) Provide a VACUUM type operation to clear out all
110692 ** deletions and duplications. This would basically be a forced merge
110693 ** into a single segment.
110695 #define CHROMIUM_FTS3_CHANGES 1
110697 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110699 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
110700 # define SQLITE_CORE 1
110701 #endif
110703 /************** Include fts3Int.h in the middle of fts3.c ********************/
110704 /************** Begin file fts3Int.h *****************************************/
110706 ** 2009 Nov 12
110708 ** The author disclaims copyright to this source code. In place of
110709 ** a legal notice, here is a blessing:
110711 ** May you do good and not evil.
110712 ** May you find forgiveness for yourself and forgive others.
110713 ** May you share freely, never taking more than you give.
110715 ******************************************************************************
110719 #ifndef _FTSINT_H
110720 #define _FTSINT_H
110722 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
110723 # define NDEBUG 1
110724 #endif
110726 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
110727 /************** Begin file fts3_tokenizer.h **********************************/
110729 ** 2006 July 10
110731 ** The author disclaims copyright to this source code.
110733 *************************************************************************
110734 ** Defines the interface to tokenizers used by fulltext-search. There
110735 ** are three basic components:
110737 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
110738 ** interface functions. This is essentially the class structure for
110739 ** tokenizers.
110741 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
110742 ** including customization information defined at creation time.
110744 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
110745 ** tokens from a particular input.
110747 #ifndef _FTS3_TOKENIZER_H_
110748 #define _FTS3_TOKENIZER_H_
110750 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
110751 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
110752 ** we will need a way to register the API consistently.
110756 ** Structures used by the tokenizer interface. When a new tokenizer
110757 ** implementation is registered, the caller provides a pointer to
110758 ** an sqlite3_tokenizer_module containing pointers to the callback
110759 ** functions that make up an implementation.
110761 ** When an fts3 table is created, it passes any arguments passed to
110762 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
110763 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
110764 ** implementation. The xCreate() function in turn returns an
110765 ** sqlite3_tokenizer structure representing the specific tokenizer to
110766 ** be used for the fts3 table (customized by the tokenizer clause arguments).
110768 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
110769 ** method is called. It returns an sqlite3_tokenizer_cursor object
110770 ** that may be used to tokenize a specific input buffer based on
110771 ** the tokenization rules supplied by a specific sqlite3_tokenizer
110772 ** object.
110774 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
110775 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
110776 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
110778 struct sqlite3_tokenizer_module {
110781 ** Structure version. Should always be set to 0.
110783 int iVersion;
110786 ** Create a new tokenizer. The values in the argv[] array are the
110787 ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
110788 ** TABLE statement that created the fts3 table. For example, if
110789 ** the following SQL is executed:
110791 ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
110793 ** then argc is set to 2, and the argv[] array contains pointers
110794 ** to the strings "arg1" and "arg2".
110796 ** This method should return either SQLITE_OK (0), or an SQLite error
110797 ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
110798 ** to point at the newly created tokenizer structure. The generic
110799 ** sqlite3_tokenizer.pModule variable should not be initialised by
110800 ** this callback. The caller will do so.
110802 int (*xCreate)(
110803 int argc, /* Size of argv array */
110804 const char *const*argv, /* Tokenizer argument strings */
110805 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
110809 ** Destroy an existing tokenizer. The fts3 module calls this method
110810 ** exactly once for each successful call to xCreate().
110812 int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
110815 ** Create a tokenizer cursor to tokenize an input buffer. The caller
110816 ** is responsible for ensuring that the input buffer remains valid
110817 ** until the cursor is closed (using the xClose() method).
110819 int (*xOpen)(
110820 sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
110821 const char *pInput, int nBytes, /* Input buffer */
110822 sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
110826 ** Destroy an existing tokenizer cursor. The fts3 module calls this
110827 ** method exactly once for each successful call to xOpen().
110829 int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
110832 ** Retrieve the next token from the tokenizer cursor pCursor. This
110833 ** method should either return SQLITE_OK and set the values of the
110834 ** "OUT" variables identified below, or SQLITE_DONE to indicate that
110835 ** the end of the buffer has been reached, or an SQLite error code.
110837 ** *ppToken should be set to point at a buffer containing the
110838 ** normalized version of the token (i.e. after any case-folding and/or
110839 ** stemming has been performed). *pnBytes should be set to the length
110840 ** of this buffer in bytes. The input text that generated the token is
110841 ** identified by the byte offsets returned in *piStartOffset and
110842 ** *piEndOffset. *piStartOffset should be set to the index of the first
110843 ** byte of the token in the input buffer. *piEndOffset should be set
110844 ** to the index of the first byte just past the end of the token in
110845 ** the input buffer.
110847 ** The buffer *ppToken is set to point at is managed by the tokenizer
110848 ** implementation. It is only required to be valid until the next call
110849 ** to xNext() or xClose().
110851 /* TODO(shess) current implementation requires pInput to be
110852 ** nul-terminated. This should either be fixed, or pInput/nBytes
110853 ** should be converted to zInput.
110855 int (*xNext)(
110856 sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
110857 const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
110858 int *piStartOffset, /* OUT: Byte offset of token in input buffer */
110859 int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
110860 int *piPosition /* OUT: Number of tokens returned before this one */
110864 struct sqlite3_tokenizer {
110865 const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
110866 /* Tokenizer implementations will typically add additional fields */
110869 struct sqlite3_tokenizer_cursor {
110870 sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
110871 /* Tokenizer implementations will typically add additional fields */
110874 int fts3_global_term_cnt(int iTerm, int iCol);
110875 int fts3_term_cnt(int iTerm, int iCol);
110878 #endif /* _FTS3_TOKENIZER_H_ */
110880 /************** End of fts3_tokenizer.h **************************************/
110881 /************** Continuing where we left off in fts3Int.h ********************/
110882 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
110883 /************** Begin file fts3_hash.h ***************************************/
110885 ** 2001 September 22
110887 ** The author disclaims copyright to this source code. In place of
110888 ** a legal notice, here is a blessing:
110890 ** May you do good and not evil.
110891 ** May you find forgiveness for yourself and forgive others.
110892 ** May you share freely, never taking more than you give.
110894 *************************************************************************
110895 ** This is the header file for the generic hash-table implemenation
110896 ** used in SQLite. We've modified it slightly to serve as a standalone
110897 ** hash table implementation for the full-text indexing module.
110900 #ifndef _FTS3_HASH_H_
110901 #define _FTS3_HASH_H_
110903 /* Forward declarations of structures. */
110904 typedef struct Fts3Hash Fts3Hash;
110905 typedef struct Fts3HashElem Fts3HashElem;
110907 /* A complete hash table is an instance of the following structure.
110908 ** The internals of this structure are intended to be opaque -- client
110909 ** code should not attempt to access or modify the fields of this structure
110910 ** directly. Change this structure only by using the routines below.
110911 ** However, many of the "procedures" and "functions" for modifying and
110912 ** accessing this structure are really macros, so we can't really make
110913 ** this structure opaque.
110915 struct Fts3Hash {
110916 char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
110917 char copyKey; /* True if copy of key made on insert */
110918 int count; /* Number of entries in this table */
110919 Fts3HashElem *first; /* The first element of the array */
110920 int htsize; /* Number of buckets in the hash table */
110921 struct _fts3ht { /* the hash table */
110922 int count; /* Number of entries with this hash */
110923 Fts3HashElem *chain; /* Pointer to first entry with this hash */
110924 } *ht;
110927 /* Each element in the hash table is an instance of the following
110928 ** structure. All elements are stored on a single doubly-linked list.
110930 ** Again, this structure is intended to be opaque, but it can't really
110931 ** be opaque because it is used by macros.
110933 struct Fts3HashElem {
110934 Fts3HashElem *next, *prev; /* Next and previous elements in the table */
110935 void *data; /* Data associated with this element */
110936 void *pKey; int nKey; /* Key associated with this element */
110940 ** There are 2 different modes of operation for a hash table:
110942 ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
110943 ** (including the null-terminator, if any). Case
110944 ** is respected in comparisons.
110946 ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
110947 ** memcmp() is used to compare keys.
110949 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
110951 #define FTS3_HASH_STRING 1
110952 #define FTS3_HASH_BINARY 2
110955 ** Access routines. To delete, insert a NULL pointer.
110957 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
110958 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
110959 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
110960 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
110961 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
110964 ** Shorthand for the functions above
110966 #define fts3HashInit sqlite3Fts3HashInit
110967 #define fts3HashInsert sqlite3Fts3HashInsert
110968 #define fts3HashFind sqlite3Fts3HashFind
110969 #define fts3HashClear sqlite3Fts3HashClear
110970 #define fts3HashFindElem sqlite3Fts3HashFindElem
110973 ** Macros for looping over all elements of a hash table. The idiom is
110974 ** like this:
110976 ** Fts3Hash h;
110977 ** Fts3HashElem *p;
110978 ** ...
110979 ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
110980 ** SomeStructure *pData = fts3HashData(p);
110981 ** // do something with pData
110984 #define fts3HashFirst(H) ((H)->first)
110985 #define fts3HashNext(E) ((E)->next)
110986 #define fts3HashData(E) ((E)->data)
110987 #define fts3HashKey(E) ((E)->pKey)
110988 #define fts3HashKeysize(E) ((E)->nKey)
110991 ** Number of entries in a hash table
110993 #define fts3HashCount(H) ((H)->count)
110995 #endif /* _FTS3_HASH_H_ */
110997 /************** End of fts3_hash.h *******************************************/
110998 /************** Continuing where we left off in fts3Int.h ********************/
111001 ** This constant controls how often segments are merged. Once there are
111002 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
111003 ** segment of level N+1.
111005 #define FTS3_MERGE_COUNT 16
111008 ** This is the maximum amount of data (in bytes) to store in the
111009 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
111010 ** populated as documents are inserted/updated/deleted in a transaction
111011 ** and used to create a new segment when the transaction is committed.
111012 ** However if this limit is reached midway through a transaction, a new
111013 ** segment is created and the hash table cleared immediately.
111015 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
111018 ** Macro to return the number of elements in an array. SQLite has a
111019 ** similar macro called ArraySize(). Use a different name to avoid
111020 ** a collision when building an amalgamation with built-in FTS3.
111022 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
111025 ** Maximum length of a varint encoded integer. The varint format is different
111026 ** from that used by SQLite, so the maximum length is 10, not 9.
111028 #define FTS3_VARINT_MAX 10
111031 ** The testcase() macro is only used by the amalgamation. If undefined,
111032 ** make it a no-op.
111034 #ifndef testcase
111035 # define testcase(X)
111036 #endif
111039 ** Terminator values for position-lists and column-lists.
111041 #define POS_COLUMN (1) /* Column-list terminator */
111042 #define POS_END (0) /* Position-list terminator */
111045 ** This section provides definitions to allow the
111046 ** FTS3 extension to be compiled outside of the
111047 ** amalgamation.
111049 #ifndef SQLITE_AMALGAMATION
111051 ** Macros indicating that conditional expressions are always true or
111052 ** false.
111054 #ifdef SQLITE_COVERAGE_TEST
111055 # define ALWAYS(x) (1)
111056 # define NEVER(X) (0)
111057 #else
111058 # define ALWAYS(x) (x)
111059 # define NEVER(X) (x)
111060 #endif
111063 ** Internal types used by SQLite.
111065 typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
111066 typedef short int i16; /* 2-byte (or larger) signed integer */
111067 typedef unsigned int u32; /* 4-byte unsigned integer */
111068 typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
111070 ** Macro used to suppress compiler warnings for unused parameters.
111072 #define UNUSED_PARAMETER(x) (void)(x)
111073 #endif
111075 typedef struct Fts3Table Fts3Table;
111076 typedef struct Fts3Cursor Fts3Cursor;
111077 typedef struct Fts3Expr Fts3Expr;
111078 typedef struct Fts3Phrase Fts3Phrase;
111079 typedef struct Fts3PhraseToken Fts3PhraseToken;
111081 typedef struct Fts3SegFilter Fts3SegFilter;
111082 typedef struct Fts3DeferredToken Fts3DeferredToken;
111083 typedef struct Fts3SegReader Fts3SegReader;
111084 typedef struct Fts3SegReaderCursor Fts3SegReaderCursor;
111087 ** A connection to a fulltext index is an instance of the following
111088 ** structure. The xCreate and xConnect methods create an instance
111089 ** of this structure and xDestroy and xDisconnect free that instance.
111090 ** All other methods receive a pointer to the structure as one of their
111091 ** arguments.
111093 struct Fts3Table {
111094 sqlite3_vtab base; /* Base class used by SQLite core */
111095 sqlite3 *db; /* The database connection */
111096 const char *zDb; /* logical database name */
111097 const char *zName; /* virtual table name */
111098 int nColumn; /* number of named columns in virtual table */
111099 char **azColumn; /* column names. malloced */
111100 sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
111102 /* Precompiled statements used by the implementation. Each of these
111103 ** statements is run and reset within a single virtual table API call.
111105 sqlite3_stmt *aStmt[24];
111107 char *zReadExprlist;
111108 char *zWriteExprlist;
111110 int nNodeSize; /* Soft limit for node size */
111111 u8 bHasStat; /* True if %_stat table exists */
111112 u8 bHasDocsize; /* True if %_docsize table exists */
111113 int nPgsz; /* Page size for host database */
111114 char *zSegmentsTbl; /* Name of %_segments table */
111115 sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
111117 /* The following hash table is used to buffer pending index updates during
111118 ** transactions. Variable nPendingData estimates the memory size of the
111119 ** pending data, including hash table overhead, but not malloc overhead.
111120 ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
111121 ** automatically. Variable iPrevDocid is the docid of the most recently
111122 ** inserted record.
111124 int nMaxPendingData;
111125 int nPendingData;
111126 sqlite_int64 iPrevDocid;
111127 Fts3Hash pendingTerms;
111131 ** When the core wants to read from the virtual table, it creates a
111132 ** virtual table cursor (an instance of the following structure) using
111133 ** the xOpen method. Cursors are destroyed using the xClose method.
111135 struct Fts3Cursor {
111136 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
111137 i16 eSearch; /* Search strategy (see below) */
111138 u8 isEof; /* True if at End Of Results */
111139 u8 isRequireSeek; /* True if must seek pStmt to %_content row */
111140 sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
111141 Fts3Expr *pExpr; /* Parsed MATCH query string */
111142 int nPhrase; /* Number of matchable phrases in query */
111143 Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
111144 sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
111145 char *pNextId; /* Pointer into the body of aDoclist */
111146 char *aDoclist; /* List of docids for full-text queries */
111147 int nDoclist; /* Size of buffer at aDoclist */
111148 int eEvalmode; /* An FTS3_EVAL_XX constant */
111149 int nRowAvg; /* Average size of database rows, in pages */
111151 int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
111152 u32 *aMatchinfo; /* Information about most recent match */
111153 int nMatchinfo; /* Number of elements in aMatchinfo[] */
111154 char *zMatchinfo; /* Matchinfo specification */
111157 #define FTS3_EVAL_FILTER 0
111158 #define FTS3_EVAL_NEXT 1
111159 #define FTS3_EVAL_MATCHINFO 2
111162 ** The Fts3Cursor.eSearch member is always set to one of the following.
111163 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
111164 ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
111165 ** of the column to be searched. For example, in
111167 ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
111168 ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
111170 ** Because the LHS of the MATCH operator is 2nd column "b",
111171 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
111172 ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
111173 ** indicating that all columns should be searched,
111174 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
111176 #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
111177 #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
111178 #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
111181 ** A "phrase" is a sequence of one or more tokens that must match in
111182 ** sequence. A single token is the base case and the most common case.
111183 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
111184 ** nToken will be the number of tokens in the string.
111186 ** The nDocMatch and nMatch variables contain data that may be used by the
111187 ** matchinfo() function. They are populated when the full-text index is
111188 ** queried for hits on the phrase. If one or more tokens in the phrase
111189 ** are deferred, the nDocMatch and nMatch variables are populated based
111190 ** on the assumption that the
111192 struct Fts3PhraseToken {
111193 char *z; /* Text of the token */
111194 int n; /* Number of bytes in buffer z */
111195 int isPrefix; /* True if token ends with a "*" character */
111196 int bFulltext; /* True if full-text index was used */
111197 Fts3SegReaderCursor *pSegcsr; /* Segment-reader for this token */
111198 Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
111201 struct Fts3Phrase {
111202 /* Variables populated by fts3_expr.c when parsing a MATCH expression */
111203 int nToken; /* Number of tokens in the phrase */
111204 int iColumn; /* Index of column this phrase must match */
111205 int isNot; /* Phrase prefixed by unary not (-) operator */
111206 Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
111210 ** A tree of these objects forms the RHS of a MATCH operator.
111212 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
111213 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
111214 ** containing the results of the NEAR or phrase query in FTS3 doclist
111215 ** format. As usual, the initial "Length" field found in doclists stored
111216 ** on disk is omitted from this buffer.
111218 ** Variable pCurrent always points to the start of a docid field within
111219 ** aDoclist. Since the doclist is usually scanned in docid order, this can
111220 ** be used to accelerate seeking to the required docid within the doclist.
111222 struct Fts3Expr {
111223 int eType; /* One of the FTSQUERY_XXX values defined below */
111224 int nNear; /* Valid if eType==FTSQUERY_NEAR */
111225 Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
111226 Fts3Expr *pLeft; /* Left operand */
111227 Fts3Expr *pRight; /* Right operand */
111228 Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
111230 int isLoaded; /* True if aDoclist/nDoclist are initialized. */
111231 char *aDoclist; /* Buffer containing doclist */
111232 int nDoclist; /* Size of aDoclist in bytes */
111234 sqlite3_int64 iCurrent;
111235 char *pCurrent;
111239 ** Candidate values for Fts3Query.eType. Note that the order of the first
111240 ** four values is in order of precedence when parsing expressions. For
111241 ** example, the following:
111243 ** "a OR b AND c NOT d NEAR e"
111245 ** is equivalent to:
111247 ** "a OR (b AND (c NOT (d NEAR e)))"
111249 #define FTSQUERY_NEAR 1
111250 #define FTSQUERY_NOT 2
111251 #define FTSQUERY_AND 3
111252 #define FTSQUERY_OR 4
111253 #define FTSQUERY_PHRASE 5
111256 /* fts3_write.c */
111257 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
111258 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
111259 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
111260 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
111261 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
111262 sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
111263 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
111264 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
111265 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(Fts3Cursor *, Fts3SegReader *, int *);
111266 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, sqlite3_stmt **);
111267 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
111268 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*);
111270 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
111271 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
111273 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
111274 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
111275 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
111276 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
111277 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *, int *);
111278 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
111280 #define FTS3_SEGCURSOR_PENDING -1
111281 #define FTS3_SEGCURSOR_ALL -2
111283 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3SegReaderCursor*, Fts3SegFilter*);
111284 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3SegReaderCursor *);
111285 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3SegReaderCursor *);
111286 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
111287 Fts3Table *, int, const char *, int, int, int, Fts3SegReaderCursor *);
111289 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
111290 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
111291 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
111292 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
111293 #define FTS3_SEGMENT_PREFIX 0x00000008
111294 #define FTS3_SEGMENT_SCAN 0x00000010
111296 /* Type passed as 4th argument to SegmentReaderIterate() */
111297 struct Fts3SegFilter {
111298 const char *zTerm;
111299 int nTerm;
111300 int iCol;
111301 int flags;
111304 struct Fts3SegReaderCursor {
111305 /* Used internally by sqlite3Fts3SegReaderXXX() calls */
111306 Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
111307 int nSegment; /* Size of apSegment array */
111308 int nAdvance; /* How many seg-readers to advance */
111309 Fts3SegFilter *pFilter; /* Pointer to filter object */
111310 char *aBuffer; /* Buffer to merge doclists in */
111311 int nBuffer; /* Allocated size of aBuffer[] in bytes */
111313 /* Cost of running this iterator. Used by fts3.c only. */
111314 int nCost;
111316 /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
111317 char *zTerm; /* Pointer to term buffer */
111318 int nTerm; /* Size of zTerm in bytes */
111319 char *aDoclist; /* Pointer to doclist buffer */
111320 int nDoclist; /* Size of aDoclist[] in bytes */
111323 /* fts3.c */
111324 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
111325 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
111326 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
111327 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
111328 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
111330 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
111331 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *, Fts3Expr *);
111332 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(Fts3Cursor *, Fts3Expr *, char **, int *);
111333 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
111335 /* fts3_tokenizer.c */
111336 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
111337 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
111338 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
111339 sqlite3_tokenizer **, char **
111341 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
111343 /* fts3_snippet.c */
111344 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
111345 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
111346 const char *, const char *, int, int
111348 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
111350 /* fts3_expr.c */
111351 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
111352 char **, int, int, const char *, int, Fts3Expr **
111354 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
111355 #ifdef SQLITE_TEST
111356 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
111357 #endif
111359 /* fts3_aux.c */
111360 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
111362 #endif /* _FTSINT_H */
111364 /************** End of fts3Int.h *********************************************/
111365 /************** Continuing where we left off in fts3.c ***********************/
111368 #ifndef SQLITE_CORE
111369 SQLITE_EXTENSION_INIT1
111370 #endif
111373 ** Write a 64-bit variable-length integer to memory starting at p[0].
111374 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
111375 ** The number of bytes written is returned.
111377 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
111378 unsigned char *q = (unsigned char *) p;
111379 sqlite_uint64 vu = v;
111381 *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
111382 vu >>= 7;
111383 }while( vu!=0 );
111384 q[-1] &= 0x7f; /* turn off high bit in final byte */
111385 assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
111386 return (int) (q - (unsigned char *)p);
111390 ** Read a 64-bit variable-length integer from memory starting at p[0].
111391 ** Return the number of bytes read, or 0 on error.
111392 ** The value is stored in *v.
111394 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
111395 const unsigned char *q = (const unsigned char *) p;
111396 sqlite_uint64 x = 0, y = 1;
111397 while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
111398 x += y * (*q++ & 0x7f);
111399 y <<= 7;
111401 x += y * (*q++);
111402 *v = (sqlite_int64) x;
111403 return (int) (q - (unsigned char *)p);
111407 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
111408 ** 32-bit integer before it is returned.
111410 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
111411 sqlite_int64 i;
111412 int ret = sqlite3Fts3GetVarint(p, &i);
111413 *pi = (int) i;
111414 return ret;
111418 ** Return the number of bytes required to encode v as a varint
111420 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
111421 int i = 0;
111424 v >>= 7;
111425 }while( v!=0 );
111426 return i;
111430 ** Convert an SQL-style quoted string into a normal string by removing
111431 ** the quote characters. The conversion is done in-place. If the
111432 ** input does not begin with a quote character, then this routine
111433 ** is a no-op.
111435 ** Examples:
111437 ** "abc" becomes abc
111438 ** 'xyz' becomes xyz
111439 ** [pqr] becomes pqr
111440 ** `mno` becomes mno
111443 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
111444 char quote; /* Quote character (if any ) */
111446 quote = z[0];
111447 if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
111448 int iIn = 1; /* Index of next byte to read from input */
111449 int iOut = 0; /* Index of next byte to write to output */
111451 /* If the first byte was a '[', then the close-quote character is a ']' */
111452 if( quote=='[' ) quote = ']';
111454 while( ALWAYS(z[iIn]) ){
111455 if( z[iIn]==quote ){
111456 if( z[iIn+1]!=quote ) break;
111457 z[iOut++] = quote;
111458 iIn += 2;
111459 }else{
111460 z[iOut++] = z[iIn++];
111463 z[iOut] = '\0';
111468 ** Read a single varint from the doclist at *pp and advance *pp to point
111469 ** to the first byte past the end of the varint. Add the value of the varint
111470 ** to *pVal.
111472 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
111473 sqlite3_int64 iVal;
111474 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
111475 *pVal += iVal;
111479 ** As long as *pp has not reached its end (pEnd), then do the same
111480 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
111481 ** But if we have reached the end of the varint, just set *pp=0 and
111482 ** leave *pVal unchanged.
111484 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
111485 if( *pp>=pEnd ){
111486 *pp = 0;
111487 }else{
111488 fts3GetDeltaVarint(pp, pVal);
111493 ** The xDisconnect() virtual table method.
111495 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
111496 Fts3Table *p = (Fts3Table *)pVtab;
111497 int i;
111499 assert( p->nPendingData==0 );
111500 assert( p->pSegments==0 );
111502 /* Free any prepared statements held */
111503 for(i=0; i<SizeofArray(p->aStmt); i++){
111504 sqlite3_finalize(p->aStmt[i]);
111506 sqlite3_free(p->zSegmentsTbl);
111507 sqlite3_free(p->zReadExprlist);
111508 sqlite3_free(p->zWriteExprlist);
111510 /* Invoke the tokenizer destructor to free the tokenizer. */
111511 p->pTokenizer->pModule->xDestroy(p->pTokenizer);
111513 sqlite3_free(p);
111514 return SQLITE_OK;
111518 ** Construct one or more SQL statements from the format string given
111519 ** and then evaluate those statements. The success code is written
111520 ** into *pRc.
111522 ** If *pRc is initially non-zero then this routine is a no-op.
111524 static void fts3DbExec(
111525 int *pRc, /* Success code */
111526 sqlite3 *db, /* Database in which to run SQL */
111527 const char *zFormat, /* Format string for SQL */
111528 ... /* Arguments to the format string */
111530 va_list ap;
111531 char *zSql;
111532 if( *pRc ) return;
111533 va_start(ap, zFormat);
111534 zSql = sqlite3_vmprintf(zFormat, ap);
111535 va_end(ap);
111536 if( zSql==0 ){
111537 *pRc = SQLITE_NOMEM;
111538 }else{
111539 *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
111540 sqlite3_free(zSql);
111545 ** The xDestroy() virtual table method.
111547 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
111548 int rc = SQLITE_OK; /* Return code */
111549 Fts3Table *p = (Fts3Table *)pVtab;
111550 sqlite3 *db = p->db;
111552 /* Drop the shadow tables */
111553 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
111554 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
111555 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
111556 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
111557 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
111559 /* If everything has worked, invoke fts3DisconnectMethod() to free the
111560 ** memory associated with the Fts3Table structure and return SQLITE_OK.
111561 ** Otherwise, return an SQLite error code.
111563 return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
111568 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
111569 ** passed as the first argument. This is done as part of the xConnect()
111570 ** and xCreate() methods.
111572 ** If *pRc is non-zero when this function is called, it is a no-op.
111573 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
111574 ** before returning.
111576 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
111577 if( *pRc==SQLITE_OK ){
111578 int i; /* Iterator variable */
111579 int rc; /* Return code */
111580 char *zSql; /* SQL statement passed to declare_vtab() */
111581 char *zCols; /* List of user defined columns */
111583 /* Create a list of user columns for the virtual table */
111584 zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
111585 for(i=1; zCols && i<p->nColumn; i++){
111586 zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
111589 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
111590 zSql = sqlite3_mprintf(
111591 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
111593 if( !zCols || !zSql ){
111594 rc = SQLITE_NOMEM;
111595 }else{
111596 rc = sqlite3_declare_vtab(p->db, zSql);
111599 sqlite3_free(zSql);
111600 sqlite3_free(zCols);
111601 *pRc = rc;
111606 ** Create the backing store tables (%_content, %_segments and %_segdir)
111607 ** required by the FTS3 table passed as the only argument. This is done
111608 ** as part of the vtab xCreate() method.
111610 ** If the p->bHasDocsize boolean is true (indicating that this is an
111611 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
111612 ** %_stat tables required by FTS4.
111614 static int fts3CreateTables(Fts3Table *p){
111615 int rc = SQLITE_OK; /* Return code */
111616 int i; /* Iterator variable */
111617 char *zContentCols; /* Columns of %_content table */
111618 sqlite3 *db = p->db; /* The database connection */
111620 /* Create a list of user columns for the content table */
111621 zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
111622 for(i=0; zContentCols && i<p->nColumn; i++){
111623 char *z = p->azColumn[i];
111624 zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
111626 if( zContentCols==0 ) rc = SQLITE_NOMEM;
111628 /* Create the content table */
111629 fts3DbExec(&rc, db,
111630 "CREATE TABLE %Q.'%q_content'(%s)",
111631 p->zDb, p->zName, zContentCols
111633 sqlite3_free(zContentCols);
111634 /* Create other tables */
111635 fts3DbExec(&rc, db,
111636 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
111637 p->zDb, p->zName
111639 fts3DbExec(&rc, db,
111640 "CREATE TABLE %Q.'%q_segdir'("
111641 "level INTEGER,"
111642 "idx INTEGER,"
111643 "start_block INTEGER,"
111644 "leaves_end_block INTEGER,"
111645 "end_block INTEGER,"
111646 "root BLOB,"
111647 "PRIMARY KEY(level, idx)"
111648 ");",
111649 p->zDb, p->zName
111651 if( p->bHasDocsize ){
111652 fts3DbExec(&rc, db,
111653 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
111654 p->zDb, p->zName
111657 if( p->bHasStat ){
111658 fts3DbExec(&rc, db,
111659 "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
111660 p->zDb, p->zName
111663 return rc;
111667 ** Store the current database page-size in bytes in p->nPgsz.
111669 ** If *pRc is non-zero when this function is called, it is a no-op.
111670 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
111671 ** before returning.
111673 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
111674 if( *pRc==SQLITE_OK ){
111675 int rc; /* Return code */
111676 char *zSql; /* SQL text "PRAGMA %Q.page_size" */
111677 sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
111679 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
111680 if( !zSql ){
111681 rc = SQLITE_NOMEM;
111682 }else{
111683 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
111684 if( rc==SQLITE_OK ){
111685 sqlite3_step(pStmt);
111686 p->nPgsz = sqlite3_column_int(pStmt, 0);
111687 rc = sqlite3_finalize(pStmt);
111688 }else if( rc==SQLITE_AUTH ){
111689 p->nPgsz = 1024;
111690 rc = SQLITE_OK;
111693 assert( p->nPgsz>0 || rc!=SQLITE_OK );
111694 sqlite3_free(zSql);
111695 *pRc = rc;
111700 ** "Special" FTS4 arguments are column specifications of the following form:
111702 ** <key> = <value>
111704 ** There may not be whitespace surrounding the "=" character. The <value>
111705 ** term may be quoted, but the <key> may not.
111707 static int fts3IsSpecialColumn(
111708 const char *z,
111709 int *pnKey,
111710 char **pzValue
111712 char *zValue;
111713 const char *zCsr = z;
111715 while( *zCsr!='=' ){
111716 if( *zCsr=='\0' ) return 0;
111717 zCsr++;
111720 *pnKey = (int)(zCsr-z);
111721 zValue = sqlite3_mprintf("%s", &zCsr[1]);
111722 if( zValue ){
111723 sqlite3Fts3Dequote(zValue);
111725 *pzValue = zValue;
111726 return 1;
111730 ** Append the output of a printf() style formatting to an existing string.
111732 static void fts3Appendf(
111733 int *pRc, /* IN/OUT: Error code */
111734 char **pz, /* IN/OUT: Pointer to string buffer */
111735 const char *zFormat, /* Printf format string to append */
111736 ... /* Arguments for printf format string */
111738 if( *pRc==SQLITE_OK ){
111739 va_list ap;
111740 char *z;
111741 va_start(ap, zFormat);
111742 z = sqlite3_vmprintf(zFormat, ap);
111743 if( z && *pz ){
111744 char *z2 = sqlite3_mprintf("%s%s", *pz, z);
111745 sqlite3_free(z);
111746 z = z2;
111748 if( z==0 ) *pRc = SQLITE_NOMEM;
111749 sqlite3_free(*pz);
111750 *pz = z;
111755 ** Return a copy of input string zInput enclosed in double-quotes (") and
111756 ** with all double quote characters escaped. For example:
111758 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
111760 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
111761 ** is the callers responsibility to call sqlite3_free() to release this
111762 ** memory.
111764 static char *fts3QuoteId(char const *zInput){
111765 int nRet;
111766 char *zRet;
111767 nRet = 2 + strlen(zInput)*2 + 1;
111768 zRet = sqlite3_malloc(nRet);
111769 if( zRet ){
111770 int i;
111771 char *z = zRet;
111772 *(z++) = '"';
111773 for(i=0; zInput[i]; i++){
111774 if( zInput[i]=='"' ) *(z++) = '"';
111775 *(z++) = zInput[i];
111777 *(z++) = '"';
111778 *(z++) = '\0';
111780 return zRet;
111784 ** Return a list of comma separated SQL expressions that could be used
111785 ** in a SELECT statement such as the following:
111787 ** SELECT <list of expressions> FROM %_content AS x ...
111789 ** to return the docid, followed by each column of text data in order
111790 ** from left to write. If parameter zFunc is not NULL, then instead of
111791 ** being returned directly each column of text data is passed to an SQL
111792 ** function named zFunc first. For example, if zFunc is "unzip" and the
111793 ** table has the three user-defined columns "a", "b", and "c", the following
111794 ** string is returned:
111796 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c')"
111798 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
111799 ** is the responsibility of the caller to eventually free it.
111801 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
111802 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
111803 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
111804 ** no error occurs, *pRc is left unmodified.
111806 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
111807 char *zRet = 0;
111808 char *zFree = 0;
111809 char *zFunction;
111810 int i;
111812 if( !zFunc ){
111813 zFunction = "";
111814 }else{
111815 zFree = zFunction = fts3QuoteId(zFunc);
111817 fts3Appendf(pRc, &zRet, "docid");
111818 for(i=0; i<p->nColumn; i++){
111819 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
111821 sqlite3_free(zFree);
111822 return zRet;
111826 ** Return a list of N comma separated question marks, where N is the number
111827 ** of columns in the %_content table (one for the docid plus one for each
111828 ** user-defined text column).
111830 ** If argument zFunc is not NULL, then all but the first question mark
111831 ** is preceded by zFunc and an open bracket, and followed by a closed
111832 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
111833 ** user-defined text columns, the following string is returned:
111835 ** "?, zip(?), zip(?), zip(?)"
111837 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
111838 ** is the responsibility of the caller to eventually free it.
111840 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
111841 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
111842 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
111843 ** no error occurs, *pRc is left unmodified.
111845 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
111846 char *zRet = 0;
111847 char *zFree = 0;
111848 char *zFunction;
111849 int i;
111851 if( !zFunc ){
111852 zFunction = "";
111853 }else{
111854 zFree = zFunction = fts3QuoteId(zFunc);
111856 fts3Appendf(pRc, &zRet, "?");
111857 for(i=0; i<p->nColumn; i++){
111858 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
111860 sqlite3_free(zFree);
111861 return zRet;
111865 ** This function is the implementation of both the xConnect and xCreate
111866 ** methods of the FTS3 virtual table.
111868 ** The argv[] array contains the following:
111870 ** argv[0] -> module name ("fts3" or "fts4")
111871 ** argv[1] -> database name
111872 ** argv[2] -> table name
111873 ** argv[...] -> "column name" and other module argument fields.
111875 static int fts3InitVtab(
111876 int isCreate, /* True for xCreate, false for xConnect */
111877 sqlite3 *db, /* The SQLite database connection */
111878 void *pAux, /* Hash table containing tokenizers */
111879 int argc, /* Number of elements in argv array */
111880 const char * const *argv, /* xCreate/xConnect argument array */
111881 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
111882 char **pzErr /* Write any error message here */
111884 Fts3Hash *pHash = (Fts3Hash *)pAux;
111885 Fts3Table *p = 0; /* Pointer to allocated vtab */
111886 int rc = SQLITE_OK; /* Return code */
111887 int i; /* Iterator variable */
111888 int nByte; /* Size of allocation used for *p */
111889 int iCol; /* Column index */
111890 int nString = 0; /* Bytes required to hold all column names */
111891 int nCol = 0; /* Number of columns in the FTS table */
111892 char *zCsr; /* Space for holding column names */
111893 int nDb; /* Bytes required to hold database name */
111894 int nName; /* Bytes required to hold table name */
111895 int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
111896 int bNoDocsize = 0; /* True to omit %_docsize table */
111897 const char **aCol; /* Array of column names */
111898 sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
111900 char *zCompress = 0;
111901 char *zUncompress = 0;
111903 assert( strlen(argv[0])==4 );
111904 assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
111905 || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
111908 nDb = (int)strlen(argv[1]) + 1;
111909 nName = (int)strlen(argv[2]) + 1;
111911 aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
111912 if( !aCol ) return SQLITE_NOMEM;
111913 memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
111915 /* Loop through all of the arguments passed by the user to the FTS3/4
111916 ** module (i.e. all the column names and special arguments). This loop
111917 ** does the following:
111919 ** + Figures out the number of columns the FTSX table will have, and
111920 ** the number of bytes of space that must be allocated to store copies
111921 ** of the column names.
111923 ** + If there is a tokenizer specification included in the arguments,
111924 ** initializes the tokenizer pTokenizer.
111926 for(i=3; rc==SQLITE_OK && i<argc; i++){
111927 char const *z = argv[i];
111928 int nKey;
111929 char *zVal;
111931 /* Check if this is a tokenizer specification */
111932 if( !pTokenizer
111933 && strlen(z)>8
111934 && 0==sqlite3_strnicmp(z, "tokenize", 8)
111935 && 0==sqlite3Fts3IsIdChar(z[8])
111937 rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
111940 /* Check if it is an FTS4 special argument. */
111941 else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
111942 if( !zVal ){
111943 rc = SQLITE_NOMEM;
111944 goto fts3_init_out;
111946 if( nKey==9 && 0==sqlite3_strnicmp(z, "matchinfo", 9) ){
111947 if( strlen(zVal)==4 && 0==sqlite3_strnicmp(zVal, "fts3", 4) ){
111948 bNoDocsize = 1;
111949 }else{
111950 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
111951 rc = SQLITE_ERROR;
111953 }else if( nKey==8 && 0==sqlite3_strnicmp(z, "compress", 8) ){
111954 zCompress = zVal;
111955 zVal = 0;
111956 }else if( nKey==10 && 0==sqlite3_strnicmp(z, "uncompress", 10) ){
111957 zUncompress = zVal;
111958 zVal = 0;
111959 }else{
111960 *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
111961 rc = SQLITE_ERROR;
111963 sqlite3_free(zVal);
111966 /* Otherwise, the argument is a column name. */
111967 else {
111968 nString += (int)(strlen(z) + 1);
111969 aCol[nCol++] = z;
111972 if( rc!=SQLITE_OK ) goto fts3_init_out;
111974 if( nCol==0 ){
111975 assert( nString==0 );
111976 aCol[0] = "content";
111977 nString = 8;
111978 nCol = 1;
111981 if( pTokenizer==0 ){
111982 rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
111983 if( rc!=SQLITE_OK ) goto fts3_init_out;
111985 assert( pTokenizer );
111988 /* Allocate and populate the Fts3Table structure. */
111989 nByte = sizeof(Fts3Table) + /* Fts3Table */
111990 nCol * sizeof(char *) + /* azColumn */
111991 nName + /* zName */
111992 nDb + /* zDb */
111993 nString; /* Space for azColumn strings */
111994 p = (Fts3Table*)sqlite3_malloc(nByte);
111995 if( p==0 ){
111996 rc = SQLITE_NOMEM;
111997 goto fts3_init_out;
111999 memset(p, 0, nByte);
112000 p->db = db;
112001 p->nColumn = nCol;
112002 p->nPendingData = 0;
112003 p->azColumn = (char **)&p[1];
112004 p->pTokenizer = pTokenizer;
112005 p->nNodeSize = 1000;
112006 p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
112007 p->bHasDocsize = (isFts4 && bNoDocsize==0);
112008 p->bHasStat = isFts4;
112009 fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
112011 /* Fill in the zName and zDb fields of the vtab structure. */
112012 zCsr = (char *)&p->azColumn[nCol];
112013 p->zName = zCsr;
112014 memcpy(zCsr, argv[2], nName);
112015 zCsr += nName;
112016 p->zDb = zCsr;
112017 memcpy(zCsr, argv[1], nDb);
112018 zCsr += nDb;
112020 /* Fill in the azColumn array */
112021 for(iCol=0; iCol<nCol; iCol++){
112022 char *z;
112023 int n;
112024 z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
112025 memcpy(zCsr, z, n);
112026 zCsr[n] = '\0';
112027 sqlite3Fts3Dequote(zCsr);
112028 p->azColumn[iCol] = zCsr;
112029 zCsr += n+1;
112030 assert( zCsr <= &((char *)p)[nByte] );
112033 if( (zCompress==0)!=(zUncompress==0) ){
112034 char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
112035 rc = SQLITE_ERROR;
112036 *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
112038 p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
112039 p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
112040 if( rc!=SQLITE_OK ) goto fts3_init_out;
112042 /* If this is an xCreate call, create the underlying tables in the
112043 ** database. TODO: For xConnect(), it could verify that said tables exist.
112045 if( isCreate ){
112046 rc = fts3CreateTables(p);
112049 /* Figure out the page-size for the database. This is required in order to
112050 ** estimate the cost of loading large doclists from the database (see
112051 ** function sqlite3Fts3SegReaderCost() for details).
112053 fts3DatabasePageSize(&rc, p);
112055 /* Declare the table schema to SQLite. */
112056 fts3DeclareVtab(&rc, p);
112058 fts3_init_out:
112059 sqlite3_free(zCompress);
112060 sqlite3_free(zUncompress);
112061 sqlite3_free((void *)aCol);
112062 if( rc!=SQLITE_OK ){
112063 if( p ){
112064 fts3DisconnectMethod((sqlite3_vtab *)p);
112065 }else if( pTokenizer ){
112066 pTokenizer->pModule->xDestroy(pTokenizer);
112068 }else{
112069 *ppVTab = &p->base;
112071 return rc;
112075 ** The xConnect() and xCreate() methods for the virtual table. All the
112076 ** work is done in function fts3InitVtab().
112078 static int fts3ConnectMethod(
112079 sqlite3 *db, /* Database connection */
112080 void *pAux, /* Pointer to tokenizer hash table */
112081 int argc, /* Number of elements in argv array */
112082 const char * const *argv, /* xCreate/xConnect argument array */
112083 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
112084 char **pzErr /* OUT: sqlite3_malloc'd error message */
112086 return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
112088 static int fts3CreateMethod(
112089 sqlite3 *db, /* Database connection */
112090 void *pAux, /* Pointer to tokenizer hash table */
112091 int argc, /* Number of elements in argv array */
112092 const char * const *argv, /* xCreate/xConnect argument array */
112093 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
112094 char **pzErr /* OUT: sqlite3_malloc'd error message */
112096 return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
112100 ** Implementation of the xBestIndex method for FTS3 tables. There
112101 ** are three possible strategies, in order of preference:
112103 ** 1. Direct lookup by rowid or docid.
112104 ** 2. Full-text search using a MATCH operator on a non-docid column.
112105 ** 3. Linear scan of %_content table.
112107 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
112108 Fts3Table *p = (Fts3Table *)pVTab;
112109 int i; /* Iterator variable */
112110 int iCons = -1; /* Index of constraint to use */
112112 /* By default use a full table scan. This is an expensive option,
112113 ** so search through the constraints to see if a more efficient
112114 ** strategy is possible.
112116 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
112117 pInfo->estimatedCost = 500000;
112118 for(i=0; i<pInfo->nConstraint; i++){
112119 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
112120 if( pCons->usable==0 ) continue;
112122 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
112123 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
112124 && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
112126 pInfo->idxNum = FTS3_DOCID_SEARCH;
112127 pInfo->estimatedCost = 1.0;
112128 iCons = i;
112131 /* A MATCH constraint. Use a full-text search.
112133 ** If there is more than one MATCH constraint available, use the first
112134 ** one encountered. If there is both a MATCH constraint and a direct
112135 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
112136 ** though the rowid/docid lookup is faster than a MATCH query, selecting
112137 ** it would lead to an "unable to use function MATCH in the requested
112138 ** context" error.
112140 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
112141 && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
112143 pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
112144 pInfo->estimatedCost = 2.0;
112145 iCons = i;
112146 break;
112150 if( iCons>=0 ){
112151 pInfo->aConstraintUsage[iCons].argvIndex = 1;
112152 pInfo->aConstraintUsage[iCons].omit = 1;
112154 return SQLITE_OK;
112158 ** Implementation of xOpen method.
112160 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
112161 sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
112163 UNUSED_PARAMETER(pVTab);
112165 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
112166 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
112167 ** if the allocation fails, return SQLITE_NOMEM.
112169 *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
112170 if( !pCsr ){
112171 return SQLITE_NOMEM;
112173 memset(pCsr, 0, sizeof(Fts3Cursor));
112174 return SQLITE_OK;
112178 ** Close the cursor. For additional information see the documentation
112179 ** on the xClose method of the virtual table interface.
112181 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
112182 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
112183 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
112184 sqlite3_finalize(pCsr->pStmt);
112185 sqlite3Fts3ExprFree(pCsr->pExpr);
112186 sqlite3Fts3FreeDeferredTokens(pCsr);
112187 sqlite3_free(pCsr->aDoclist);
112188 sqlite3_free(pCsr->aMatchinfo);
112189 sqlite3_free(pCsr);
112190 return SQLITE_OK;
112194 ** Position the pCsr->pStmt statement so that it is on the row
112195 ** of the %_content table that contains the last match. Return
112196 ** SQLITE_OK on success.
112198 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
112199 if( pCsr->isRequireSeek ){
112200 pCsr->isRequireSeek = 0;
112201 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
112202 if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
112203 return SQLITE_OK;
112204 }else{
112205 int rc = sqlite3_reset(pCsr->pStmt);
112206 if( rc==SQLITE_OK ){
112207 /* If no row was found and no error has occured, then the %_content
112208 ** table is missing a row that is present in the full-text index.
112209 ** The data structures are corrupt.
112211 rc = SQLITE_CORRUPT;
112213 pCsr->isEof = 1;
112214 if( pContext ){
112215 sqlite3_result_error_code(pContext, rc);
112217 return rc;
112219 }else{
112220 return SQLITE_OK;
112225 ** This function is used to process a single interior node when searching
112226 ** a b-tree for a term or term prefix. The node data is passed to this
112227 ** function via the zNode/nNode parameters. The term to search for is
112228 ** passed in zTerm/nTerm.
112230 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
112231 ** of the child node that heads the sub-tree that may contain the term.
112233 ** If piLast is not NULL, then *piLast is set to the right-most child node
112234 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
112235 ** a prefix.
112237 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
112239 static int fts3ScanInteriorNode(
112240 const char *zTerm, /* Term to select leaves for */
112241 int nTerm, /* Size of term zTerm in bytes */
112242 const char *zNode, /* Buffer containing segment interior node */
112243 int nNode, /* Size of buffer at zNode */
112244 sqlite3_int64 *piFirst, /* OUT: Selected child node */
112245 sqlite3_int64 *piLast /* OUT: Selected child node */
112247 int rc = SQLITE_OK; /* Return code */
112248 const char *zCsr = zNode; /* Cursor to iterate through node */
112249 const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
112250 char *zBuffer = 0; /* Buffer to load terms into */
112251 int nAlloc = 0; /* Size of allocated buffer */
112252 int isFirstTerm = 1; /* True when processing first term on page */
112253 sqlite3_int64 iChild; /* Block id of child node to descend to */
112255 /* Skip over the 'height' varint that occurs at the start of every
112256 ** interior node. Then load the blockid of the left-child of the b-tree
112257 ** node into variable iChild.
112259 ** Even if the data structure on disk is corrupted, this (reading two
112260 ** varints from the buffer) does not risk an overread. If zNode is a
112261 ** root node, then the buffer comes from a SELECT statement. SQLite does
112262 ** not make this guarantee explicitly, but in practice there are always
112263 ** either more than 20 bytes of allocated space following the nNode bytes of
112264 ** contents, or two zero bytes. Or, if the node is read from the %_segments
112265 ** table, then there are always 20 bytes of zeroed padding following the
112266 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
112268 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
112269 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
112270 if( zCsr>zEnd ){
112271 return SQLITE_CORRUPT;
112274 while( zCsr<zEnd && (piFirst || piLast) ){
112275 int cmp; /* memcmp() result */
112276 int nSuffix; /* Size of term suffix */
112277 int nPrefix = 0; /* Size of term prefix */
112278 int nBuffer; /* Total term size */
112280 /* Load the next term on the node into zBuffer. Use realloc() to expand
112281 ** the size of zBuffer if required. */
112282 if( !isFirstTerm ){
112283 zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
112285 isFirstTerm = 0;
112286 zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
112288 /* NOTE(shess): Previous code checked for negative nPrefix and
112289 ** nSuffix and suffix overrunning zEnd. Additionally corrupt if
112290 ** the prefix is longer than the previous term, or if the suffix
112291 ** causes overflow.
112293 if( nPrefix<0 || nSuffix<0 /* || nPrefix>nBuffer */
112294 || &zCsr[nSuffix]<zCsr || &zCsr[nSuffix]>zEnd ){
112295 rc = SQLITE_CORRUPT;
112296 goto finish_scan;
112298 if( nPrefix+nSuffix>nAlloc ){
112299 char *zNew;
112300 nAlloc = (nPrefix+nSuffix) * 2;
112301 zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
112302 if( !zNew ){
112303 rc = SQLITE_NOMEM;
112304 goto finish_scan;
112306 zBuffer = zNew;
112308 memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
112309 nBuffer = nPrefix + nSuffix;
112310 zCsr += nSuffix;
112312 /* Compare the term we are searching for with the term just loaded from
112313 ** the interior node. If the specified term is greater than or equal
112314 ** to the term from the interior node, then all terms on the sub-tree
112315 ** headed by node iChild are smaller than zTerm. No need to search
112316 ** iChild.
112318 ** If the interior node term is larger than the specified term, then
112319 ** the tree headed by iChild may contain the specified term.
112321 cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
112322 if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
112323 *piFirst = iChild;
112324 piFirst = 0;
112327 if( piLast && cmp<0 ){
112328 *piLast = iChild;
112329 piLast = 0;
112332 iChild++;
112335 if( piFirst ) *piFirst = iChild;
112336 if( piLast ) *piLast = iChild;
112338 finish_scan:
112339 sqlite3_free(zBuffer);
112340 return rc;
112345 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
112346 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
112347 ** contains a term. This function searches the sub-tree headed by the zNode
112348 ** node for the range of leaf nodes that may contain the specified term
112349 ** or terms for which the specified term is a prefix.
112351 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
112352 ** left-most leaf node in the tree that may contain the specified term.
112353 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
112354 ** right-most leaf node that may contain a term for which the specified
112355 ** term is a prefix.
112357 ** It is possible that the range of returned leaf nodes does not contain
112358 ** the specified term or any terms for which it is a prefix. However, if the
112359 ** segment does contain any such terms, they are stored within the identified
112360 ** range. Because this function only inspects interior segment nodes (and
112361 ** never loads leaf nodes into memory), it is not possible to be sure.
112363 ** If an error occurs, an error code other than SQLITE_OK is returned.
112365 static int fts3SelectLeaf(
112366 Fts3Table *p, /* Virtual table handle */
112367 const char *zTerm, /* Term to select leaves for */
112368 int nTerm, /* Size of term zTerm in bytes */
112369 const char *zNode, /* Buffer containing segment interior node */
112370 int nNode, /* Size of buffer at zNode */
112371 sqlite3_int64 *piLeaf, /* Selected leaf node */
112372 sqlite3_int64 *piLeaf2 /* Selected leaf node */
112374 int rc; /* Return code */
112375 int iHeight; /* Height of this node in tree */
112377 assert( piLeaf || piLeaf2 );
112379 sqlite3Fts3GetVarint32(zNode, &iHeight);
112380 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
112381 assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
112383 if( rc==SQLITE_OK && iHeight>1 ){
112384 char *zBlob = 0; /* Blob read from %_segments table */
112385 int nBlob; /* Size of zBlob in bytes */
112387 if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
112388 rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob);
112389 if( rc==SQLITE_OK ){
112390 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
112392 sqlite3_free(zBlob);
112393 piLeaf = 0;
112394 zBlob = 0;
112397 if( rc==SQLITE_OK ){
112398 rc = sqlite3Fts3ReadBlock(p, piLeaf ? *piLeaf : *piLeaf2, &zBlob, &nBlob);
112400 if( rc==SQLITE_OK ){
112401 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
112403 sqlite3_free(zBlob);
112406 return rc;
112410 ** This function is used to create delta-encoded serialized lists of FTS3
112411 ** varints. Each call to this function appends a single varint to a list.
112413 static void fts3PutDeltaVarint(
112414 char **pp, /* IN/OUT: Output pointer */
112415 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
112416 sqlite3_int64 iVal /* Write this value to the list */
112418 assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
112419 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
112420 *piPrev = iVal;
112424 ** When this function is called, *ppPoslist is assumed to point to the
112425 ** start of a position-list. After it returns, *ppPoslist points to the
112426 ** first byte after the position-list.
112428 ** A position list is list of positions (delta encoded) and columns for
112429 ** a single document record of a doclist. So, in other words, this
112430 ** routine advances *ppPoslist so that it points to the next docid in
112431 ** the doclist, or to the first byte past the end of the doclist.
112433 ** If pp is not NULL, then the contents of the position list are copied
112434 ** to *pp. *pp is set to point to the first byte past the last byte copied
112435 ** before this function returns.
112437 static void fts3PoslistCopy(char **pp, char **ppPoslist){
112438 char *pEnd = *ppPoslist;
112439 char c = 0;
112441 /* The end of a position list is marked by a zero encoded as an FTS3
112442 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
112443 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
112444 ** of some other, multi-byte, value.
112446 ** The following while-loop moves pEnd to point to the first byte that is not
112447 ** immediately preceded by a byte with the 0x80 bit set. Then increments
112448 ** pEnd once more so that it points to the byte immediately following the
112449 ** last byte in the position-list.
112451 while( *pEnd | c ){
112452 c = *pEnd++ & 0x80;
112453 testcase( c!=0 && (*pEnd)==0 );
112455 pEnd++; /* Advance past the POS_END terminator byte */
112457 if( pp ){
112458 int n = (int)(pEnd - *ppPoslist);
112459 char *p = *pp;
112460 memcpy(p, *ppPoslist, n);
112461 p += n;
112462 *pp = p;
112464 *ppPoslist = pEnd;
112468 ** When this function is called, *ppPoslist is assumed to point to the
112469 ** start of a column-list. After it returns, *ppPoslist points to the
112470 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
112472 ** A column-list is list of delta-encoded positions for a single column
112473 ** within a single document within a doclist.
112475 ** The column-list is terminated either by a POS_COLUMN varint (1) or
112476 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
112477 ** the POS_COLUMN or POS_END that terminates the column-list.
112479 ** If pp is not NULL, then the contents of the column-list are copied
112480 ** to *pp. *pp is set to point to the first byte past the last byte copied
112481 ** before this function returns. The POS_COLUMN or POS_END terminator
112482 ** is not copied into *pp.
112484 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
112485 char *pEnd = *ppPoslist;
112486 char c = 0;
112488 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
112489 ** not part of a multi-byte varint.
112491 while( 0xFE & (*pEnd | c) ){
112492 c = *pEnd++ & 0x80;
112493 testcase( c!=0 && ((*pEnd)&0xfe)==0 );
112495 if( pp ){
112496 int n = (int)(pEnd - *ppPoslist);
112497 char *p = *pp;
112498 memcpy(p, *ppPoslist, n);
112499 p += n;
112500 *pp = p;
112502 *ppPoslist = pEnd;
112506 ** Value used to signify the end of an position-list. This is safe because
112507 ** it is not possible to have a document with 2^31 terms.
112509 #define POSITION_LIST_END 0x7fffffff
112512 ** This function is used to help parse position-lists. When this function is
112513 ** called, *pp may point to the start of the next varint in the position-list
112514 ** being parsed, or it may point to 1 byte past the end of the position-list
112515 ** (in which case **pp will be a terminator bytes POS_END (0) or
112516 ** (1)).
112518 ** If *pp points past the end of the current position-list, set *pi to
112519 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
112520 ** increment the current value of *pi by the value read, and set *pp to
112521 ** point to the next value before returning.
112523 ** Before calling this routine *pi must be initialized to the value of
112524 ** the previous position, or zero if we are reading the first position
112525 ** in the position-list. Because positions are delta-encoded, the value
112526 ** of the previous position is needed in order to compute the value of
112527 ** the next position.
112529 static void fts3ReadNextPos(
112530 char **pp, /* IN/OUT: Pointer into position-list buffer */
112531 sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
112533 if( (**pp)&0xFE ){
112534 fts3GetDeltaVarint(pp, pi);
112535 *pi -= 2;
112536 }else{
112537 *pi = POSITION_LIST_END;
112542 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
112543 ** the value of iCol encoded as a varint to *pp. This will start a new
112544 ** column list.
112546 ** Set *pp to point to the byte just after the last byte written before
112547 ** returning (do not modify it if iCol==0). Return the total number of bytes
112548 ** written (0 if iCol==0).
112550 static int fts3PutColNumber(char **pp, int iCol){
112551 int n = 0; /* Number of bytes written */
112552 if( iCol ){
112553 char *p = *pp; /* Output pointer */
112554 n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
112555 *p = 0x01;
112556 *pp = &p[n];
112558 return n;
112562 ** Compute the union of two position lists. The output written
112563 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
112564 ** order and with any duplicates removed. All pointers are
112565 ** updated appropriately. The caller is responsible for insuring
112566 ** that there is enough space in *pp to hold the complete output.
112568 static void fts3PoslistMerge(
112569 char **pp, /* Output buffer */
112570 char **pp1, /* Left input list */
112571 char **pp2 /* Right input list */
112573 char *p = *pp;
112574 char *p1 = *pp1;
112575 char *p2 = *pp2;
112577 while( *p1 || *p2 ){
112578 int iCol1; /* The current column index in pp1 */
112579 int iCol2; /* The current column index in pp2 */
112581 if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
112582 else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
112583 else iCol1 = 0;
112585 if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
112586 else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
112587 else iCol2 = 0;
112589 if( iCol1==iCol2 ){
112590 sqlite3_int64 i1 = 0; /* Last position from pp1 */
112591 sqlite3_int64 i2 = 0; /* Last position from pp2 */
112592 sqlite3_int64 iPrev = 0;
112593 int n = fts3PutColNumber(&p, iCol1);
112594 p1 += n;
112595 p2 += n;
112597 /* At this point, both p1 and p2 point to the start of column-lists
112598 ** for the same column (the column with index iCol1 and iCol2).
112599 ** A column-list is a list of non-negative delta-encoded varints, each
112600 ** incremented by 2 before being stored. Each list is terminated by a
112601 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
112602 ** and writes the results to buffer p. p is left pointing to the byte
112603 ** after the list written. No terminator (POS_END or POS_COLUMN) is
112604 ** written to the output.
112606 fts3GetDeltaVarint(&p1, &i1);
112607 fts3GetDeltaVarint(&p2, &i2);
112609 fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
112610 iPrev -= 2;
112611 if( i1==i2 ){
112612 fts3ReadNextPos(&p1, &i1);
112613 fts3ReadNextPos(&p2, &i2);
112614 }else if( i1<i2 ){
112615 fts3ReadNextPos(&p1, &i1);
112616 }else{
112617 fts3ReadNextPos(&p2, &i2);
112619 }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
112620 }else if( iCol1<iCol2 ){
112621 p1 += fts3PutColNumber(&p, iCol1);
112622 fts3ColumnlistCopy(&p, &p1);
112623 }else{
112624 p2 += fts3PutColNumber(&p, iCol2);
112625 fts3ColumnlistCopy(&p, &p2);
112629 *p++ = POS_END;
112630 *pp = p;
112631 *pp1 = p1 + 1;
112632 *pp2 = p2 + 1;
112636 ** nToken==1 searches for adjacent positions.
112638 ** This function is used to merge two position lists into one. When it is
112639 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
112640 ** the part of a doclist that follows each document id. For example, if a row
112641 ** contains:
112643 ** 'a b c'|'x y z'|'a b b a'
112645 ** Then the position list for this row for token 'b' would consist of:
112647 ** 0x02 0x01 0x02 0x03 0x03 0x00
112649 ** When this function returns, both *pp1 and *pp2 are left pointing to the
112650 ** byte following the 0x00 terminator of their respective position lists.
112652 ** If isSaveLeft is 0, an entry is added to the output position list for
112653 ** each position in *pp2 for which there exists one or more positions in
112654 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
112655 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
112656 ** slots before it.
112658 static int fts3PoslistPhraseMerge(
112659 char **pp, /* IN/OUT: Preallocated output buffer */
112660 int nToken, /* Maximum difference in token positions */
112661 int isSaveLeft, /* Save the left position */
112662 int isExact, /* If *pp1 is exactly nTokens before *pp2 */
112663 char **pp1, /* IN/OUT: Left input list */
112664 char **pp2 /* IN/OUT: Right input list */
112666 char *p = (pp ? *pp : 0);
112667 char *p1 = *pp1;
112668 char *p2 = *pp2;
112669 int iCol1 = 0;
112670 int iCol2 = 0;
112672 /* Never set both isSaveLeft and isExact for the same invocation. */
112673 assert( isSaveLeft==0 || isExact==0 );
112675 assert( *p1!=0 && *p2!=0 );
112676 if( *p1==POS_COLUMN ){
112677 p1++;
112678 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
112680 if( *p2==POS_COLUMN ){
112681 p2++;
112682 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
112685 while( 1 ){
112686 if( iCol1==iCol2 ){
112687 char *pSave = p;
112688 sqlite3_int64 iPrev = 0;
112689 sqlite3_int64 iPos1 = 0;
112690 sqlite3_int64 iPos2 = 0;
112692 if( pp && iCol1 ){
112693 *p++ = POS_COLUMN;
112694 p += sqlite3Fts3PutVarint(p, iCol1);
112697 assert( *p1!=POS_END && *p1!=POS_COLUMN );
112698 assert( *p2!=POS_END && *p2!=POS_COLUMN );
112699 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
112700 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
112702 while( 1 ){
112703 if( iPos2==iPos1+nToken
112704 || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
112706 sqlite3_int64 iSave;
112707 if( !pp ){
112708 fts3PoslistCopy(0, &p2);
112709 fts3PoslistCopy(0, &p1);
112710 *pp1 = p1;
112711 *pp2 = p2;
112712 return 1;
112714 iSave = isSaveLeft ? iPos1 : iPos2;
112715 fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
112716 pSave = 0;
112718 if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
112719 if( (*p2&0xFE)==0 ) break;
112720 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
112721 }else{
112722 if( (*p1&0xFE)==0 ) break;
112723 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
112727 if( pSave ){
112728 assert( pp && p );
112729 p = pSave;
112732 fts3ColumnlistCopy(0, &p1);
112733 fts3ColumnlistCopy(0, &p2);
112734 assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
112735 if( 0==*p1 || 0==*p2 ) break;
112737 p1++;
112738 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
112739 p2++;
112740 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
112743 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
112744 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
112745 ** end of the position list, or the 0x01 that precedes the next
112746 ** column-number in the position list.
112748 else if( iCol1<iCol2 ){
112749 fts3ColumnlistCopy(0, &p1);
112750 if( 0==*p1 ) break;
112751 p1++;
112752 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
112753 }else{
112754 fts3ColumnlistCopy(0, &p2);
112755 if( 0==*p2 ) break;
112756 p2++;
112757 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
112761 fts3PoslistCopy(0, &p2);
112762 fts3PoslistCopy(0, &p1);
112763 *pp1 = p1;
112764 *pp2 = p2;
112765 if( !pp || *pp==p ){
112766 return 0;
112768 *p++ = 0x00;
112769 *pp = p;
112770 return 1;
112774 ** Merge two position-lists as required by the NEAR operator.
112776 static int fts3PoslistNearMerge(
112777 char **pp, /* Output buffer */
112778 char *aTmp, /* Temporary buffer space */
112779 int nRight, /* Maximum difference in token positions */
112780 int nLeft, /* Maximum difference in token positions */
112781 char **pp1, /* IN/OUT: Left input list */
112782 char **pp2 /* IN/OUT: Right input list */
112784 char *p1 = *pp1;
112785 char *p2 = *pp2;
112787 if( !pp ){
112788 if( fts3PoslistPhraseMerge(0, nRight, 0, 0, pp1, pp2) ) return 1;
112789 *pp1 = p1;
112790 *pp2 = p2;
112791 return fts3PoslistPhraseMerge(0, nLeft, 0, 0, pp2, pp1);
112792 }else{
112793 char *pTmp1 = aTmp;
112794 char *pTmp2;
112795 char *aTmp2;
112796 int res = 1;
112798 fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
112799 aTmp2 = pTmp2 = pTmp1;
112800 *pp1 = p1;
112801 *pp2 = p2;
112802 fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
112803 if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
112804 fts3PoslistMerge(pp, &aTmp, &aTmp2);
112805 }else if( pTmp1!=aTmp ){
112806 fts3PoslistCopy(pp, &aTmp);
112807 }else if( pTmp2!=aTmp2 ){
112808 fts3PoslistCopy(pp, &aTmp2);
112809 }else{
112810 res = 0;
112813 return res;
112818 ** Values that may be used as the first parameter to fts3DoclistMerge().
112820 #define MERGE_NOT 2 /* D + D -> D */
112821 #define MERGE_AND 3 /* D + D -> D */
112822 #define MERGE_OR 4 /* D + D -> D */
112823 #define MERGE_POS_OR 5 /* P + P -> P */
112824 #define MERGE_PHRASE 6 /* P + P -> D */
112825 #define MERGE_POS_PHRASE 7 /* P + P -> P */
112826 #define MERGE_NEAR 8 /* P + P -> D */
112827 #define MERGE_POS_NEAR 9 /* P + P -> P */
112830 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
112831 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
112832 ** which is guaranteed to be large enough to hold the results. The number
112833 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
112835 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
112836 ** occurs while allocating a temporary buffer as part of the merge operation,
112837 ** SQLITE_NOMEM is returned.
112839 static int fts3DoclistMerge(
112840 int mergetype, /* One of the MERGE_XXX constants */
112841 int nParam1, /* Used by MERGE_NEAR and MERGE_POS_NEAR */
112842 int nParam2, /* Used by MERGE_NEAR and MERGE_POS_NEAR */
112843 char *aBuffer, /* Pre-allocated output buffer */
112844 int *pnBuffer, /* OUT: Bytes written to aBuffer */
112845 char *a1, /* Buffer containing first doclist */
112846 int n1, /* Size of buffer a1 */
112847 char *a2, /* Buffer containing second doclist */
112848 int n2, /* Size of buffer a2 */
112849 int *pnDoc /* OUT: Number of docids in output */
112851 sqlite3_int64 i1 = 0;
112852 sqlite3_int64 i2 = 0;
112853 sqlite3_int64 iPrev = 0;
112855 char *p = aBuffer;
112856 char *p1 = a1;
112857 char *p2 = a2;
112858 char *pEnd1 = &a1[n1];
112859 char *pEnd2 = &a2[n2];
112860 int nDoc = 0;
112862 assert( mergetype==MERGE_OR || mergetype==MERGE_POS_OR
112863 || mergetype==MERGE_AND || mergetype==MERGE_NOT
112864 || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
112865 || mergetype==MERGE_NEAR || mergetype==MERGE_POS_NEAR
112868 if( !aBuffer ){
112869 *pnBuffer = 0;
112870 return SQLITE_NOMEM;
112873 /* Read the first docid from each doclist */
112874 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112875 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112877 switch( mergetype ){
112878 case MERGE_OR:
112879 case MERGE_POS_OR:
112880 while( p1 || p2 ){
112881 if( p2 && p1 && i1==i2 ){
112882 fts3PutDeltaVarint(&p, &iPrev, i1);
112883 if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
112884 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112885 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112886 }else if( !p2 || (p1 && i1<i2) ){
112887 fts3PutDeltaVarint(&p, &iPrev, i1);
112888 if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
112889 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112890 }else{
112891 fts3PutDeltaVarint(&p, &iPrev, i2);
112892 if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
112893 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112896 break;
112898 case MERGE_AND:
112899 while( p1 && p2 ){
112900 if( i1==i2 ){
112901 fts3PutDeltaVarint(&p, &iPrev, i1);
112902 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112903 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112904 nDoc++;
112905 }else if( i1<i2 ){
112906 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112907 }else{
112908 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112911 break;
112913 case MERGE_NOT:
112914 while( p1 ){
112915 if( p2 && i1==i2 ){
112916 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112917 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112918 }else if( !p2 || i1<i2 ){
112919 fts3PutDeltaVarint(&p, &iPrev, i1);
112920 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112921 }else{
112922 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112925 break;
112927 case MERGE_POS_PHRASE:
112928 case MERGE_PHRASE: {
112929 char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
112930 while( p1 && p2 ){
112931 if( i1==i2 ){
112932 char *pSave = p;
112933 sqlite3_int64 iPrevSave = iPrev;
112934 fts3PutDeltaVarint(&p, &iPrev, i1);
112935 if( 0==fts3PoslistPhraseMerge(ppPos, nParam1, 0, 1, &p1, &p2) ){
112936 p = pSave;
112937 iPrev = iPrevSave;
112938 }else{
112939 nDoc++;
112941 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112942 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112943 }else if( i1<i2 ){
112944 fts3PoslistCopy(0, &p1);
112945 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112946 }else{
112947 fts3PoslistCopy(0, &p2);
112948 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112951 break;
112954 default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
112955 char *aTmp = 0;
112956 char **ppPos = 0;
112958 if( mergetype==MERGE_POS_NEAR ){
112959 ppPos = &p;
112960 aTmp = sqlite3_malloc(2*(n1+n2+1));
112961 if( !aTmp ){
112962 return SQLITE_NOMEM;
112966 while( p1 && p2 ){
112967 if( i1==i2 ){
112968 char *pSave = p;
112969 sqlite3_int64 iPrevSave = iPrev;
112970 fts3PutDeltaVarint(&p, &iPrev, i1);
112972 if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
112973 iPrev = iPrevSave;
112974 p = pSave;
112977 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112978 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112979 }else if( i1<i2 ){
112980 fts3PoslistCopy(0, &p1);
112981 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112982 }else{
112983 fts3PoslistCopy(0, &p2);
112984 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112987 sqlite3_free(aTmp);
112988 break;
112992 if( pnDoc ) *pnDoc = nDoc;
112993 *pnBuffer = (int)(p-aBuffer);
112994 return SQLITE_OK;
112998 ** A pointer to an instance of this structure is used as the context
112999 ** argument to sqlite3Fts3SegReaderIterate()
113001 typedef struct TermSelect TermSelect;
113002 struct TermSelect {
113003 int isReqPos;
113004 char *aaOutput[16]; /* Malloc'd output buffer */
113005 int anOutput[16]; /* Size of output in bytes */
113009 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
113010 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
113011 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
113013 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
113014 ** the responsibility of the caller to free any doclists left in the
113015 ** TermSelect.aaOutput[] array.
113017 static int fts3TermSelectMerge(TermSelect *pTS){
113018 int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
113019 char *aOut = 0;
113020 int nOut = 0;
113021 int i;
113023 /* Loop through the doclists in the aaOutput[] array. Merge them all
113024 ** into a single doclist.
113026 for(i=0; i<SizeofArray(pTS->aaOutput); i++){
113027 if( pTS->aaOutput[i] ){
113028 if( !aOut ){
113029 aOut = pTS->aaOutput[i];
113030 nOut = pTS->anOutput[i];
113031 pTS->aaOutput[i] = 0;
113032 }else{
113033 int nNew = nOut + pTS->anOutput[i];
113034 char *aNew = sqlite3_malloc(nNew);
113035 if( !aNew ){
113036 sqlite3_free(aOut);
113037 return SQLITE_NOMEM;
113039 fts3DoclistMerge(mergetype, 0, 0,
113040 aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, 0
113042 sqlite3_free(pTS->aaOutput[i]);
113043 sqlite3_free(aOut);
113044 pTS->aaOutput[i] = 0;
113045 aOut = aNew;
113046 nOut = nNew;
113051 pTS->aaOutput[0] = aOut;
113052 pTS->anOutput[0] = nOut;
113053 return SQLITE_OK;
113057 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
113058 ** querying the full-text index for a doclist associated with a term or
113059 ** term-prefix.
113061 static int fts3TermSelectCb(
113062 Fts3Table *p, /* Virtual table object */
113063 void *pContext, /* Pointer to TermSelect structure */
113064 char *zTerm,
113065 int nTerm,
113066 char *aDoclist,
113067 int nDoclist
113069 TermSelect *pTS = (TermSelect *)pContext;
113071 UNUSED_PARAMETER(p);
113072 UNUSED_PARAMETER(zTerm);
113073 UNUSED_PARAMETER(nTerm);
113075 if( pTS->aaOutput[0]==0 ){
113076 /* If this is the first term selected, copy the doclist to the output
113077 ** buffer using memcpy(). TODO: Add a way to transfer control of the
113078 ** aDoclist buffer from the caller so as to avoid the memcpy().
113080 pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
113081 pTS->anOutput[0] = nDoclist;
113082 if( pTS->aaOutput[0] ){
113083 memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
113084 }else{
113085 return SQLITE_NOMEM;
113087 }else{
113088 int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
113089 char *aMerge = aDoclist;
113090 int nMerge = nDoclist;
113091 int iOut;
113093 for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
113094 char *aNew;
113095 int nNew;
113096 if( pTS->aaOutput[iOut]==0 ){
113097 assert( iOut>0 );
113098 pTS->aaOutput[iOut] = aMerge;
113099 pTS->anOutput[iOut] = nMerge;
113100 break;
113103 nNew = nMerge + pTS->anOutput[iOut];
113104 aNew = sqlite3_malloc(nNew);
113105 if( !aNew ){
113106 if( aMerge!=aDoclist ){
113107 sqlite3_free(aMerge);
113109 return SQLITE_NOMEM;
113111 fts3DoclistMerge(mergetype, 0, 0, aNew, &nNew,
113112 pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge, 0
113115 if( iOut>0 ) sqlite3_free(aMerge);
113116 sqlite3_free(pTS->aaOutput[iOut]);
113117 pTS->aaOutput[iOut] = 0;
113119 aMerge = aNew;
113120 nMerge = nNew;
113121 if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
113122 pTS->aaOutput[iOut] = aMerge;
113123 pTS->anOutput[iOut] = nMerge;
113127 return SQLITE_OK;
113130 static int fts3DeferredTermSelect(
113131 Fts3DeferredToken *pToken, /* Phrase token */
113132 int isTermPos, /* True to include positions */
113133 int *pnOut, /* OUT: Size of list */
113134 char **ppOut /* OUT: Body of list */
113136 char *aSource;
113137 int nSource;
113139 aSource = sqlite3Fts3DeferredDoclist(pToken, &nSource);
113140 if( !aSource ){
113141 *pnOut = 0;
113142 *ppOut = 0;
113143 }else if( isTermPos ){
113144 *ppOut = sqlite3_malloc(nSource);
113145 if( !*ppOut ) return SQLITE_NOMEM;
113146 memcpy(*ppOut, aSource, nSource);
113147 *pnOut = nSource;
113148 }else{
113149 sqlite3_int64 docid;
113150 *pnOut = sqlite3Fts3GetVarint(aSource, &docid);
113151 *ppOut = sqlite3_malloc(*pnOut);
113152 if( !*ppOut ) return SQLITE_NOMEM;
113153 sqlite3Fts3PutVarint(*ppOut, docid);
113156 return SQLITE_OK;
113159 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
113160 Fts3Table *p, /* FTS3 table handle */
113161 int iLevel, /* Level of segments to scan */
113162 const char *zTerm, /* Term to query for */
113163 int nTerm, /* Size of zTerm in bytes */
113164 int isPrefix, /* True for a prefix search */
113165 int isScan, /* True to scan from zTerm to EOF */
113166 Fts3SegReaderCursor *pCsr /* Cursor object to populate */
113168 int rc = SQLITE_OK;
113169 int rc2;
113170 int iAge = 0;
113171 sqlite3_stmt *pStmt = 0;
113172 Fts3SegReader *pPending = 0;
113174 assert( iLevel==FTS3_SEGCURSOR_ALL
113175 || iLevel==FTS3_SEGCURSOR_PENDING
113176 || iLevel>=0
113178 assert( FTS3_SEGCURSOR_PENDING<0 );
113179 assert( FTS3_SEGCURSOR_ALL<0 );
113180 assert( iLevel==FTS3_SEGCURSOR_ALL || (zTerm==0 && isPrefix==1) );
113181 assert( isPrefix==0 || isScan==0 );
113184 memset(pCsr, 0, sizeof(Fts3SegReaderCursor));
113186 /* If iLevel is less than 0, include a seg-reader for the pending-terms. */
113187 assert( isScan==0 || fts3HashCount(&p->pendingTerms)==0 );
113188 if( iLevel<0 && isScan==0 ){
113189 rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &pPending);
113190 if( rc==SQLITE_OK && pPending ){
113191 int nByte = (sizeof(Fts3SegReader *) * 16);
113192 pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
113193 if( pCsr->apSegment==0 ){
113194 rc = SQLITE_NOMEM;
113195 }else{
113196 pCsr->apSegment[0] = pPending;
113197 pCsr->nSegment = 1;
113198 pPending = 0;
113203 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
113204 if( rc==SQLITE_OK ){
113205 rc = sqlite3Fts3AllSegdirs(p, iLevel, &pStmt);
113207 while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
113209 /* Read the values returned by the SELECT into local variables. */
113210 sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
113211 sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
113212 sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
113213 int nRoot = sqlite3_column_bytes(pStmt, 4);
113214 char const *zRoot = sqlite3_column_blob(pStmt, 4);
113216 /* If nSegment is a multiple of 16 the array needs to be extended. */
113217 if( (pCsr->nSegment%16)==0 ){
113218 Fts3SegReader **apNew;
113219 int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
113220 apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
113221 if( !apNew ){
113222 rc = SQLITE_NOMEM;
113223 goto finished;
113225 pCsr->apSegment = apNew;
113228 /* If zTerm is not NULL, and this segment is not stored entirely on its
113229 ** root node, the range of leaves scanned can be reduced. Do this. */
113230 if( iStartBlock && zTerm ){
113231 sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
113232 rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
113233 if( rc!=SQLITE_OK ) goto finished;
113234 if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
113237 rc = sqlite3Fts3SegReaderNew(iAge, iStartBlock, iLeavesEndBlock,
113238 iEndBlock, zRoot, nRoot, &pCsr->apSegment[pCsr->nSegment]
113240 if( rc!=SQLITE_OK ) goto finished;
113241 pCsr->nSegment++;
113242 iAge++;
113246 finished:
113247 rc2 = sqlite3_reset(pStmt);
113248 if( rc==SQLITE_DONE ) rc = rc2;
113249 sqlite3Fts3SegReaderFree(pPending);
113251 return rc;
113255 static int fts3TermSegReaderCursor(
113256 Fts3Cursor *pCsr, /* Virtual table cursor handle */
113257 const char *zTerm, /* Term to query for */
113258 int nTerm, /* Size of zTerm in bytes */
113259 int isPrefix, /* True for a prefix search */
113260 Fts3SegReaderCursor **ppSegcsr /* OUT: Allocated seg-reader cursor */
113262 Fts3SegReaderCursor *pSegcsr; /* Object to allocate and return */
113263 int rc = SQLITE_NOMEM; /* Return code */
113265 pSegcsr = sqlite3_malloc(sizeof(Fts3SegReaderCursor));
113266 if( pSegcsr ){
113267 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
113268 int i;
113269 int nCost = 0;
113270 rc = sqlite3Fts3SegReaderCursor(
113271 p, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr);
113273 for(i=0; rc==SQLITE_OK && i<pSegcsr->nSegment; i++){
113274 rc = sqlite3Fts3SegReaderCost(pCsr, pSegcsr->apSegment[i], &nCost);
113276 pSegcsr->nCost = nCost;
113279 *ppSegcsr = pSegcsr;
113280 return rc;
113283 static void fts3SegReaderCursorFree(Fts3SegReaderCursor *pSegcsr){
113284 sqlite3Fts3SegReaderFinish(pSegcsr);
113285 sqlite3_free(pSegcsr);
113289 ** This function retreives the doclist for the specified term (or term
113290 ** prefix) from the database.
113292 ** The returned doclist may be in one of two formats, depending on the
113293 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
113294 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
113295 ** is non-zero, then the returned list is in the same format as is stored
113296 ** in the database without the found length specifier at the start of on-disk
113297 ** doclists.
113299 static int fts3TermSelect(
113300 Fts3Table *p, /* Virtual table handle */
113301 Fts3PhraseToken *pTok, /* Token to query for */
113302 int iColumn, /* Column to query (or -ve for all columns) */
113303 int isReqPos, /* True to include position lists in output */
113304 int *pnOut, /* OUT: Size of buffer at *ppOut */
113305 char **ppOut /* OUT: Malloced result buffer */
113307 int rc; /* Return code */
113308 Fts3SegReaderCursor *pSegcsr; /* Seg-reader cursor for this term */
113309 TermSelect tsc; /* Context object for fts3TermSelectCb() */
113310 Fts3SegFilter filter; /* Segment term filter configuration */
113312 pSegcsr = pTok->pSegcsr;
113313 memset(&tsc, 0, sizeof(TermSelect));
113314 tsc.isReqPos = isReqPos;
113316 filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
113317 | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
113318 | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
113319 | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
113320 filter.iCol = iColumn;
113321 filter.zTerm = pTok->z;
113322 filter.nTerm = pTok->n;
113324 rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
113325 while( SQLITE_OK==rc
113326 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
113328 rc = fts3TermSelectCb(p, (void *)&tsc,
113329 pSegcsr->zTerm, pSegcsr->nTerm, pSegcsr->aDoclist, pSegcsr->nDoclist
113333 if( rc==SQLITE_OK ){
113334 rc = fts3TermSelectMerge(&tsc);
113336 if( rc==SQLITE_OK ){
113337 *ppOut = tsc.aaOutput[0];
113338 *pnOut = tsc.anOutput[0];
113339 }else{
113340 int i;
113341 for(i=0; i<SizeofArray(tsc.aaOutput); i++){
113342 sqlite3_free(tsc.aaOutput[i]);
113346 fts3SegReaderCursorFree(pSegcsr);
113347 pTok->pSegcsr = 0;
113348 return rc;
113352 ** This function counts the total number of docids in the doclist stored
113353 ** in buffer aList[], size nList bytes.
113355 ** If the isPoslist argument is true, then it is assumed that the doclist
113356 ** contains a position-list following each docid. Otherwise, it is assumed
113357 ** that the doclist is simply a list of docids stored as delta encoded
113358 ** varints.
113360 static int fts3DoclistCountDocids(int isPoslist, char *aList, int nList){
113361 int nDoc = 0; /* Return value */
113362 if( aList ){
113363 char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
113364 char *p = aList; /* Cursor */
113365 if( !isPoslist ){
113366 /* The number of docids in the list is the same as the number of
113367 ** varints. In FTS3 a varint consists of a single byte with the 0x80
113368 ** bit cleared and zero or more bytes with the 0x80 bit set. So to
113369 ** count the varints in the buffer, just count the number of bytes
113370 ** with the 0x80 bit clear. */
113371 while( p<aEnd ) nDoc += (((*p++)&0x80)==0);
113372 }else{
113373 while( p<aEnd ){
113374 nDoc++;
113375 while( (*p++)&0x80 ); /* Skip docid varint */
113376 fts3PoslistCopy(0, &p); /* Skip over position list */
113381 return nDoc;
113385 ** Call sqlite3Fts3DeferToken() for each token in the expression pExpr.
113387 static int fts3DeferExpression(Fts3Cursor *pCsr, Fts3Expr *pExpr){
113388 int rc = SQLITE_OK;
113389 if( pExpr ){
113390 rc = fts3DeferExpression(pCsr, pExpr->pLeft);
113391 if( rc==SQLITE_OK ){
113392 rc = fts3DeferExpression(pCsr, pExpr->pRight);
113394 if( pExpr->eType==FTSQUERY_PHRASE ){
113395 int iCol = pExpr->pPhrase->iColumn;
113396 int i;
113397 for(i=0; rc==SQLITE_OK && i<pExpr->pPhrase->nToken; i++){
113398 Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
113399 if( pToken->pDeferred==0 ){
113400 rc = sqlite3Fts3DeferToken(pCsr, pToken, iCol);
113405 return rc;
113409 ** This function removes the position information from a doclist. When
113410 ** called, buffer aList (size *pnList bytes) contains a doclist that includes
113411 ** position information. This function removes the position information so
113412 ** that aList contains only docids, and adjusts *pnList to reflect the new
113413 ** (possibly reduced) size of the doclist.
113415 static void fts3DoclistStripPositions(
113416 char *aList, /* IN/OUT: Buffer containing doclist */
113417 int *pnList /* IN/OUT: Size of doclist in bytes */
113419 if( aList ){
113420 char *aEnd = &aList[*pnList]; /* Pointer to one byte after EOF */
113421 char *p = aList; /* Input cursor */
113422 char *pOut = aList; /* Output cursor */
113424 while( p<aEnd ){
113425 sqlite3_int64 delta;
113426 p += sqlite3Fts3GetVarint(p, &delta);
113427 fts3PoslistCopy(0, &p);
113428 pOut += sqlite3Fts3PutVarint(pOut, delta);
113431 *pnList = (int)(pOut - aList);
113436 ** Return a DocList corresponding to the phrase *pPhrase.
113438 ** If this function returns SQLITE_OK, but *pnOut is set to a negative value,
113439 ** then no tokens in the phrase were looked up in the full-text index. This
113440 ** is only possible when this function is called from within xFilter(). The
113441 ** caller should assume that all documents match the phrase. The actual
113442 ** filtering will take place in xNext().
113444 static int fts3PhraseSelect(
113445 Fts3Cursor *pCsr, /* Virtual table cursor handle */
113446 Fts3Phrase *pPhrase, /* Phrase to return a doclist for */
113447 int isReqPos, /* True if output should contain positions */
113448 char **paOut, /* OUT: Pointer to malloc'd result buffer */
113449 int *pnOut /* OUT: Size of buffer at *paOut */
113451 char *pOut = 0;
113452 int nOut = 0;
113453 int rc = SQLITE_OK;
113454 int ii;
113455 int iCol = pPhrase->iColumn;
113456 int isTermPos = (pPhrase->nToken>1 || isReqPos);
113457 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
113458 int isFirst = 1;
113460 int iPrevTok = 0;
113461 int nDoc = 0;
113463 /* If this is an xFilter() evaluation, create a segment-reader for each
113464 ** phrase token. Or, if this is an xNext() or snippet/offsets/matchinfo
113465 ** evaluation, only create segment-readers if there are no Fts3DeferredToken
113466 ** objects attached to the phrase-tokens.
113468 for(ii=0; ii<pPhrase->nToken; ii++){
113469 Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
113470 if( pTok->pSegcsr==0 ){
113471 if( (pCsr->eEvalmode==FTS3_EVAL_FILTER)
113472 || (pCsr->eEvalmode==FTS3_EVAL_NEXT && pCsr->pDeferred==0)
113473 || (pCsr->eEvalmode==FTS3_EVAL_MATCHINFO && pTok->bFulltext)
113475 rc = fts3TermSegReaderCursor(
113476 pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
113478 if( rc!=SQLITE_OK ) return rc;
113483 for(ii=0; ii<pPhrase->nToken; ii++){
113484 Fts3PhraseToken *pTok; /* Token to find doclist for */
113485 int iTok = 0; /* The token being queried this iteration */
113486 char *pList = 0; /* Pointer to token doclist */
113487 int nList = 0; /* Size of buffer at pList */
113489 /* Select a token to process. If this is an xFilter() call, then tokens
113490 ** are processed in order from least to most costly. Otherwise, tokens
113491 ** are processed in the order in which they occur in the phrase.
113493 if( pCsr->eEvalmode==FTS3_EVAL_MATCHINFO ){
113494 assert( isReqPos );
113495 iTok = ii;
113496 pTok = &pPhrase->aToken[iTok];
113497 if( pTok->bFulltext==0 ) continue;
113498 }else if( pCsr->eEvalmode==FTS3_EVAL_NEXT || isReqPos ){
113499 iTok = ii;
113500 pTok = &pPhrase->aToken[iTok];
113501 }else{
113502 int nMinCost = 0x7FFFFFFF;
113503 int jj;
113505 /* Find the remaining token with the lowest cost. */
113506 for(jj=0; jj<pPhrase->nToken; jj++){
113507 Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[jj].pSegcsr;
113508 if( pSegcsr && pSegcsr->nCost<nMinCost ){
113509 iTok = jj;
113510 nMinCost = pSegcsr->nCost;
113513 pTok = &pPhrase->aToken[iTok];
113515 /* This branch is taken if it is determined that loading the doclist
113516 ** for the next token would require more IO than loading all documents
113517 ** currently identified by doclist pOut/nOut. No further doclists will
113518 ** be loaded from the full-text index for this phrase.
113520 if( nMinCost>nDoc && ii>0 ){
113521 rc = fts3DeferExpression(pCsr, pCsr->pExpr);
113522 break;
113526 if( pCsr->eEvalmode==FTS3_EVAL_NEXT && pTok->pDeferred ){
113527 rc = fts3DeferredTermSelect(pTok->pDeferred, isTermPos, &nList, &pList);
113528 }else{
113529 if( pTok->pSegcsr ){
113530 rc = fts3TermSelect(p, pTok, iCol, isTermPos, &nList, &pList);
113532 pTok->bFulltext = 1;
113534 assert( rc!=SQLITE_OK || pCsr->eEvalmode || pTok->pSegcsr==0 );
113535 if( rc!=SQLITE_OK ) break;
113537 if( isFirst ){
113538 pOut = pList;
113539 nOut = nList;
113540 if( pCsr->eEvalmode==FTS3_EVAL_FILTER && pPhrase->nToken>1 ){
113541 nDoc = fts3DoclistCountDocids(1, pOut, nOut);
113543 isFirst = 0;
113544 iPrevTok = iTok;
113545 }else{
113546 /* Merge the new term list and the current output. */
113547 char *aLeft, *aRight;
113548 int nLeft, nRight;
113549 int nDist;
113550 int mt;
113552 /* If this is the final token of the phrase, and positions were not
113553 ** requested by the caller, use MERGE_PHRASE instead of POS_PHRASE.
113554 ** This drops the position information from the output list.
113556 mt = MERGE_POS_PHRASE;
113557 if( ii==pPhrase->nToken-1 && !isReqPos ) mt = MERGE_PHRASE;
113559 assert( iPrevTok!=iTok );
113560 if( iPrevTok<iTok ){
113561 aLeft = pOut;
113562 nLeft = nOut;
113563 aRight = pList;
113564 nRight = nList;
113565 nDist = iTok-iPrevTok;
113566 iPrevTok = iTok;
113567 }else{
113568 aRight = pOut;
113569 nRight = nOut;
113570 aLeft = pList;
113571 nLeft = nList;
113572 nDist = iPrevTok-iTok;
113574 pOut = aRight;
113575 fts3DoclistMerge(
113576 mt, nDist, 0, pOut, &nOut, aLeft, nLeft, aRight, nRight, &nDoc
113578 sqlite3_free(aLeft);
113580 assert( nOut==0 || pOut!=0 );
113583 if( rc==SQLITE_OK ){
113584 if( ii!=pPhrase->nToken ){
113585 assert( pCsr->eEvalmode==FTS3_EVAL_FILTER && isReqPos==0 );
113586 fts3DoclistStripPositions(pOut, &nOut);
113588 *paOut = pOut;
113589 *pnOut = nOut;
113590 }else{
113591 sqlite3_free(pOut);
113593 return rc;
113597 ** This function merges two doclists according to the requirements of a
113598 ** NEAR operator.
113600 ** Both input doclists must include position information. The output doclist
113601 ** includes position information if the first argument to this function
113602 ** is MERGE_POS_NEAR, or does not if it is MERGE_NEAR.
113604 static int fts3NearMerge(
113605 int mergetype, /* MERGE_POS_NEAR or MERGE_NEAR */
113606 int nNear, /* Parameter to NEAR operator */
113607 int nTokenLeft, /* Number of tokens in LHS phrase arg */
113608 char *aLeft, /* Doclist for LHS (incl. positions) */
113609 int nLeft, /* Size of LHS doclist in bytes */
113610 int nTokenRight, /* As nTokenLeft */
113611 char *aRight, /* As aLeft */
113612 int nRight, /* As nRight */
113613 char **paOut, /* OUT: Results of merge (malloced) */
113614 int *pnOut /* OUT: Sized of output buffer */
113616 char *aOut; /* Buffer to write output doclist to */
113617 int rc; /* Return code */
113619 assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
113621 aOut = sqlite3_malloc(nLeft+nRight+1);
113622 if( aOut==0 ){
113623 rc = SQLITE_NOMEM;
113624 }else{
113625 rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft,
113626 aOut, pnOut, aLeft, nLeft, aRight, nRight, 0
113628 if( rc!=SQLITE_OK ){
113629 sqlite3_free(aOut);
113630 aOut = 0;
113634 *paOut = aOut;
113635 return rc;
113639 ** This function is used as part of the processing for the snippet() and
113640 ** offsets() functions.
113642 ** Both pLeft and pRight are expression nodes of type FTSQUERY_PHRASE. Both
113643 ** have their respective doclists (including position information) loaded
113644 ** in Fts3Expr.aDoclist/nDoclist. This function removes all entries from
113645 ** each doclist that are not within nNear tokens of a corresponding entry
113646 ** in the other doclist.
113648 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
113649 int rc; /* Return code */
113651 assert( pLeft->eType==FTSQUERY_PHRASE );
113652 assert( pRight->eType==FTSQUERY_PHRASE );
113653 assert( pLeft->isLoaded && pRight->isLoaded );
113655 if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
113656 sqlite3_free(pLeft->aDoclist);
113657 sqlite3_free(pRight->aDoclist);
113658 pRight->aDoclist = 0;
113659 pLeft->aDoclist = 0;
113660 rc = SQLITE_OK;
113661 }else{
113662 char *aOut; /* Buffer in which to assemble new doclist */
113663 int nOut; /* Size of buffer aOut in bytes */
113665 rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
113666 pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
113667 pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
113668 &aOut, &nOut
113670 if( rc!=SQLITE_OK ) return rc;
113671 sqlite3_free(pRight->aDoclist);
113672 pRight->aDoclist = aOut;
113673 pRight->nDoclist = nOut;
113675 rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
113676 pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
113677 pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
113678 &aOut, &nOut
113680 sqlite3_free(pLeft->aDoclist);
113681 pLeft->aDoclist = aOut;
113682 pLeft->nDoclist = nOut;
113684 return rc;
113689 ** Allocate an Fts3SegReaderArray for each token in the expression pExpr.
113690 ** The allocated objects are stored in the Fts3PhraseToken.pArray member
113691 ** variables of each token structure.
113693 static int fts3ExprAllocateSegReaders(
113694 Fts3Cursor *pCsr, /* FTS3 table */
113695 Fts3Expr *pExpr, /* Expression to create seg-readers for */
113696 int *pnExpr /* OUT: Number of AND'd expressions */
113698 int rc = SQLITE_OK; /* Return code */
113700 assert( pCsr->eEvalmode==FTS3_EVAL_FILTER );
113701 if( pnExpr && pExpr->eType!=FTSQUERY_AND ){
113702 (*pnExpr)++;
113703 pnExpr = 0;
113706 if( pExpr->eType==FTSQUERY_PHRASE ){
113707 Fts3Phrase *pPhrase = pExpr->pPhrase;
113708 int ii;
113710 for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
113711 Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
113712 if( pTok->pSegcsr==0 ){
113713 rc = fts3TermSegReaderCursor(
113714 pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
113718 }else{
113719 rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pLeft, pnExpr);
113720 if( rc==SQLITE_OK ){
113721 rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pRight, pnExpr);
113724 return rc;
113728 ** Free the Fts3SegReaderArray objects associated with each token in the
113729 ** expression pExpr. In other words, this function frees the resources
113730 ** allocated by fts3ExprAllocateSegReaders().
113732 static void fts3ExprFreeSegReaders(Fts3Expr *pExpr){
113733 if( pExpr ){
113734 Fts3Phrase *pPhrase = pExpr->pPhrase;
113735 if( pPhrase ){
113736 int kk;
113737 for(kk=0; kk<pPhrase->nToken; kk++){
113738 fts3SegReaderCursorFree(pPhrase->aToken[kk].pSegcsr);
113739 pPhrase->aToken[kk].pSegcsr = 0;
113742 fts3ExprFreeSegReaders(pExpr->pLeft);
113743 fts3ExprFreeSegReaders(pExpr->pRight);
113748 ** Return the sum of the costs of all tokens in the expression pExpr. This
113749 ** function must be called after Fts3SegReaderArrays have been allocated
113750 ** for all tokens using fts3ExprAllocateSegReaders().
113752 static int fts3ExprCost(Fts3Expr *pExpr){
113753 int nCost; /* Return value */
113754 if( pExpr->eType==FTSQUERY_PHRASE ){
113755 Fts3Phrase *pPhrase = pExpr->pPhrase;
113756 int ii;
113757 nCost = 0;
113758 for(ii=0; ii<pPhrase->nToken; ii++){
113759 Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[ii].pSegcsr;
113760 if( pSegcsr ) nCost += pSegcsr->nCost;
113762 }else{
113763 nCost = fts3ExprCost(pExpr->pLeft) + fts3ExprCost(pExpr->pRight);
113765 return nCost;
113769 ** The following is a helper function (and type) for fts3EvalExpr(). It
113770 ** must be called after Fts3SegReaders have been allocated for every token
113771 ** in the expression. See the context it is called from in fts3EvalExpr()
113772 ** for further explanation.
113774 typedef struct ExprAndCost ExprAndCost;
113775 struct ExprAndCost {
113776 Fts3Expr *pExpr;
113777 int nCost;
113779 static void fts3ExprAssignCosts(
113780 Fts3Expr *pExpr, /* Expression to create seg-readers for */
113781 ExprAndCost **ppExprCost /* OUT: Write to *ppExprCost */
113783 if( pExpr->eType==FTSQUERY_AND ){
113784 fts3ExprAssignCosts(pExpr->pLeft, ppExprCost);
113785 fts3ExprAssignCosts(pExpr->pRight, ppExprCost);
113786 }else{
113787 (*ppExprCost)->pExpr = pExpr;
113788 (*ppExprCost)->nCost = fts3ExprCost(pExpr);
113789 (*ppExprCost)++;
113794 ** Evaluate the full-text expression pExpr against FTS3 table pTab. Store
113795 ** the resulting doclist in *paOut and *pnOut. This routine mallocs for
113796 ** the space needed to store the output. The caller is responsible for
113797 ** freeing the space when it has finished.
113799 ** This function is called in two distinct contexts:
113801 ** * From within the virtual table xFilter() method. In this case, the
113802 ** output doclist contains entries for all rows in the table, based on
113803 ** data read from the full-text index.
113805 ** In this case, if the query expression contains one or more tokens that
113806 ** are very common, then the returned doclist may contain a superset of
113807 ** the documents that actually match the expression.
113809 ** * From within the virtual table xNext() method. This call is only made
113810 ** if the call from within xFilter() found that there were very common
113811 ** tokens in the query expression and did return a superset of the
113812 ** matching documents. In this case the returned doclist contains only
113813 ** entries that correspond to the current row of the table. Instead of
113814 ** reading the data for each token from the full-text index, the data is
113815 ** already available in-memory in the Fts3PhraseToken.pDeferred structures.
113816 ** See fts3EvalDeferred() for how it gets there.
113818 ** In the first case above, Fts3Cursor.doDeferred==0. In the second (if it is
113819 ** required) Fts3Cursor.doDeferred==1.
113821 ** If the SQLite invokes the snippet(), offsets() or matchinfo() function
113822 ** as part of a SELECT on an FTS3 table, this function is called on each
113823 ** individual phrase expression in the query. If there were very common tokens
113824 ** found in the xFilter() call, then this function is called once for phrase
113825 ** for each row visited, and the returned doclist contains entries for the
113826 ** current row only. Otherwise, if there were no very common tokens, then this
113827 ** function is called once only for each phrase in the query and the returned
113828 ** doclist contains entries for all rows of the table.
113830 ** Fts3Cursor.doDeferred==1 when this function is called on phrases as a
113831 ** result of a snippet(), offsets() or matchinfo() invocation.
113833 static int fts3EvalExpr(
113834 Fts3Cursor *p, /* Virtual table cursor handle */
113835 Fts3Expr *pExpr, /* Parsed fts3 expression */
113836 char **paOut, /* OUT: Pointer to malloc'd result buffer */
113837 int *pnOut, /* OUT: Size of buffer at *paOut */
113838 int isReqPos /* Require positions in output buffer */
113840 int rc = SQLITE_OK; /* Return code */
113842 /* Zero the output parameters. */
113843 *paOut = 0;
113844 *pnOut = 0;
113846 if( pExpr ){
113847 assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR
113848 || pExpr->eType==FTSQUERY_AND || pExpr->eType==FTSQUERY_NOT
113849 || pExpr->eType==FTSQUERY_PHRASE
113851 assert( pExpr->eType==FTSQUERY_PHRASE || isReqPos==0 );
113853 if( pExpr->eType==FTSQUERY_PHRASE ){
113854 rc = fts3PhraseSelect(p, pExpr->pPhrase,
113855 isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
113856 paOut, pnOut
113858 fts3ExprFreeSegReaders(pExpr);
113859 }else if( p->eEvalmode==FTS3_EVAL_FILTER && pExpr->eType==FTSQUERY_AND ){
113860 ExprAndCost *aExpr = 0; /* Array of AND'd expressions and costs */
113861 int nExpr = 0; /* Size of aExpr[] */
113862 char *aRet = 0; /* Doclist to return to caller */
113863 int nRet = 0; /* Length of aRet[] in bytes */
113864 int nDoc = 0x7FFFFFFF;
113866 assert( !isReqPos );
113868 rc = fts3ExprAllocateSegReaders(p, pExpr, &nExpr);
113869 if( rc==SQLITE_OK ){
113870 assert( nExpr>1 );
113871 aExpr = sqlite3_malloc(sizeof(ExprAndCost) * nExpr);
113872 if( !aExpr ) rc = SQLITE_NOMEM;
113874 if( rc==SQLITE_OK ){
113875 int ii; /* Used to iterate through expressions */
113877 fts3ExprAssignCosts(pExpr, &aExpr);
113878 aExpr -= nExpr;
113879 for(ii=0; ii<nExpr; ii++){
113880 char *aNew;
113881 int nNew;
113882 int jj;
113883 ExprAndCost *pBest = 0;
113885 for(jj=0; jj<nExpr; jj++){
113886 ExprAndCost *pCand = &aExpr[jj];
113887 if( pCand->pExpr && (pBest==0 || pCand->nCost<pBest->nCost) ){
113888 pBest = pCand;
113892 if( pBest->nCost>nDoc ){
113893 rc = fts3DeferExpression(p, p->pExpr);
113894 break;
113895 }else{
113896 rc = fts3EvalExpr(p, pBest->pExpr, &aNew, &nNew, 0);
113897 if( rc!=SQLITE_OK ) break;
113898 pBest->pExpr = 0;
113899 if( ii==0 ){
113900 aRet = aNew;
113901 nRet = nNew;
113902 nDoc = fts3DoclistCountDocids(0, aRet, nRet);
113903 }else{
113904 fts3DoclistMerge(
113905 MERGE_AND, 0, 0, aRet, &nRet, aRet, nRet, aNew, nNew, &nDoc
113907 sqlite3_free(aNew);
113913 if( rc==SQLITE_OK ){
113914 *paOut = aRet;
113915 *pnOut = nRet;
113916 }else{
113917 assert( *paOut==0 );
113918 sqlite3_free(aRet);
113920 sqlite3_free(aExpr);
113921 fts3ExprFreeSegReaders(pExpr);
113923 }else{
113924 char *aLeft;
113925 char *aRight;
113926 int nLeft;
113927 int nRight;
113929 assert( pExpr->eType==FTSQUERY_NEAR
113930 || pExpr->eType==FTSQUERY_OR
113931 || pExpr->eType==FTSQUERY_NOT
113932 || (pExpr->eType==FTSQUERY_AND && p->eEvalmode==FTS3_EVAL_NEXT)
113935 if( 0==(rc = fts3EvalExpr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
113936 && 0==(rc = fts3EvalExpr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
113938 switch( pExpr->eType ){
113939 case FTSQUERY_NEAR: {
113940 Fts3Expr *pLeft;
113941 Fts3Expr *pRight;
113942 int mergetype = MERGE_NEAR;
113943 if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
113944 mergetype = MERGE_POS_NEAR;
113946 pLeft = pExpr->pLeft;
113947 while( pLeft->eType==FTSQUERY_NEAR ){
113948 pLeft=pLeft->pRight;
113950 pRight = pExpr->pRight;
113951 assert( pRight->eType==FTSQUERY_PHRASE );
113952 assert( pLeft->eType==FTSQUERY_PHRASE );
113954 rc = fts3NearMerge(mergetype, pExpr->nNear,
113955 pLeft->pPhrase->nToken, aLeft, nLeft,
113956 pRight->pPhrase->nToken, aRight, nRight,
113957 paOut, pnOut
113959 sqlite3_free(aLeft);
113960 break;
113963 case FTSQUERY_OR: {
113964 /* Allocate a buffer for the output. The maximum size is the
113965 ** sum of the sizes of the two input buffers. The +1 term is
113966 ** so that a buffer of zero bytes is never allocated - this can
113967 ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
113969 char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
113970 rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
113971 aLeft, nLeft, aRight, nRight, 0
113973 *paOut = aBuffer;
113974 sqlite3_free(aLeft);
113975 break;
113978 default: {
113979 assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
113980 fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
113981 aLeft, nLeft, aRight, nRight, 0
113983 *paOut = aLeft;
113984 break;
113988 sqlite3_free(aRight);
113992 assert( rc==SQLITE_OK || *paOut==0 );
113993 return rc;
113997 ** This function is called from within xNext() for each row visited by
113998 ** an FTS3 query. If evaluating the FTS3 query expression within xFilter()
113999 ** was able to determine the exact set of matching rows, this function sets
114000 ** *pbRes to true and returns SQLITE_IO immediately.
114002 ** Otherwise, if evaluating the query expression within xFilter() returned a
114003 ** superset of the matching documents instead of an exact set (this happens
114004 ** when the query includes very common tokens and it is deemed too expensive to
114005 ** load their doclists from disk), this function tests if the current row
114006 ** really does match the FTS3 query.
114008 ** If an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK
114009 ** is returned and *pbRes is set to true if the current row matches the
114010 ** FTS3 query (and should be included in the results returned to SQLite), or
114011 ** false otherwise.
114013 static int fts3EvalDeferred(
114014 Fts3Cursor *pCsr, /* FTS3 cursor pointing at row to test */
114015 int *pbRes /* OUT: Set to true if row is a match */
114017 int rc = SQLITE_OK;
114018 if( pCsr->pDeferred==0 ){
114019 *pbRes = 1;
114020 }else{
114021 rc = fts3CursorSeek(0, pCsr);
114022 if( rc==SQLITE_OK ){
114023 sqlite3Fts3FreeDeferredDoclists(pCsr);
114024 rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
114026 if( rc==SQLITE_OK ){
114027 char *a = 0;
114028 int n = 0;
114029 rc = fts3EvalExpr(pCsr, pCsr->pExpr, &a, &n, 0);
114030 assert( n>=0 );
114031 *pbRes = (n>0);
114032 sqlite3_free(a);
114035 return rc;
114039 ** Advance the cursor to the next row in the %_content table that
114040 ** matches the search criteria. For a MATCH search, this will be
114041 ** the next row that matches. For a full-table scan, this will be
114042 ** simply the next row in the %_content table. For a docid lookup,
114043 ** this routine simply sets the EOF flag.
114045 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
114046 ** even if we reach end-of-file. The fts3EofMethod() will be called
114047 ** subsequently to determine whether or not an EOF was hit.
114049 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
114050 int res;
114051 int rc = SQLITE_OK; /* Return code */
114052 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
114054 pCsr->eEvalmode = FTS3_EVAL_NEXT;
114056 if( pCsr->aDoclist==0 ){
114057 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
114058 pCsr->isEof = 1;
114059 rc = sqlite3_reset(pCsr->pStmt);
114060 break;
114062 pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
114063 }else{
114064 if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
114065 pCsr->isEof = 1;
114066 break;
114068 sqlite3_reset(pCsr->pStmt);
114069 fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
114070 pCsr->isRequireSeek = 1;
114071 pCsr->isMatchinfoNeeded = 1;
114073 }while( SQLITE_OK==(rc = fts3EvalDeferred(pCsr, &res)) && res==0 );
114075 return rc;
114079 ** This is the xFilter interface for the virtual table. See
114080 ** the virtual table xFilter method documentation for additional
114081 ** information.
114083 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
114084 ** the %_content table.
114086 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
114087 ** in the %_content table.
114089 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
114090 ** column on the left-hand side of the MATCH operator is column
114091 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
114092 ** side of the MATCH operator.
114094 static int fts3FilterMethod(
114095 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
114096 int idxNum, /* Strategy index */
114097 const char *idxStr, /* Unused */
114098 int nVal, /* Number of elements in apVal */
114099 sqlite3_value **apVal /* Arguments for the indexing scheme */
114101 const char *azSql[] = {
114102 "SELECT %s FROM %Q.'%q_content' AS x WHERE docid = ?", /* non-full-scan */
114103 "SELECT %s FROM %Q.'%q_content' AS x ", /* full-scan */
114105 int rc; /* Return code */
114106 char *zSql; /* SQL statement used to access %_content */
114107 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
114108 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
114110 UNUSED_PARAMETER(idxStr);
114111 UNUSED_PARAMETER(nVal);
114113 assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
114114 assert( nVal==0 || nVal==1 );
114115 assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
114116 assert( p->pSegments==0 );
114118 /* In case the cursor has been used before, clear it now. */
114119 sqlite3_finalize(pCsr->pStmt);
114120 sqlite3_free(pCsr->aDoclist);
114121 sqlite3Fts3ExprFree(pCsr->pExpr);
114122 memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
114124 if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
114125 int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
114126 const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
114128 if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
114129 return SQLITE_NOMEM;
114132 rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
114133 iCol, zQuery, -1, &pCsr->pExpr
114135 if( rc!=SQLITE_OK ){
114136 if( rc==SQLITE_ERROR ){
114137 p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
114138 zQuery);
114140 return rc;
114143 rc = sqlite3Fts3ReadLock(p);
114144 if( rc!=SQLITE_OK ) return rc;
114146 rc = fts3EvalExpr(pCsr, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
114147 sqlite3Fts3SegmentsClose(p);
114148 if( rc!=SQLITE_OK ) return rc;
114149 pCsr->pNextId = pCsr->aDoclist;
114150 pCsr->iPrevId = 0;
114153 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
114154 ** statement loops through all rows of the %_content table. For a
114155 ** full-text query or docid lookup, the statement retrieves a single
114156 ** row by docid.
114158 zSql = (char *)azSql[idxNum==FTS3_FULLSCAN_SEARCH];
114159 zSql = sqlite3_mprintf(zSql, p->zReadExprlist, p->zDb, p->zName);
114160 if( !zSql ){
114161 rc = SQLITE_NOMEM;
114162 }else{
114163 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
114164 sqlite3_free(zSql);
114166 if( rc==SQLITE_OK && idxNum==FTS3_DOCID_SEARCH ){
114167 rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
114169 pCsr->eSearch = (i16)idxNum;
114171 if( rc!=SQLITE_OK ) return rc;
114172 return fts3NextMethod(pCursor);
114176 ** This is the xEof method of the virtual table. SQLite calls this
114177 ** routine to find out if it has reached the end of a result set.
114179 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
114180 return ((Fts3Cursor *)pCursor)->isEof;
114184 ** This is the xRowid method. The SQLite core calls this routine to
114185 ** retrieve the rowid for the current row of the result set. fts3
114186 ** exposes %_content.docid as the rowid for the virtual table. The
114187 ** rowid should be written to *pRowid.
114189 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
114190 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
114191 if( pCsr->aDoclist ){
114192 *pRowid = pCsr->iPrevId;
114193 }else{
114194 /* This branch runs if the query is implemented using a full-table scan
114195 ** (not using the full-text index). In this case grab the rowid from the
114196 ** SELECT statement.
114198 assert( pCsr->isRequireSeek==0 );
114199 *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
114201 return SQLITE_OK;
114205 ** This is the xColumn method, called by SQLite to request a value from
114206 ** the row that the supplied cursor currently points to.
114208 static int fts3ColumnMethod(
114209 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
114210 sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */
114211 int iCol /* Index of column to read value from */
114213 int rc; /* Return Code */
114214 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
114215 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
114217 /* The column value supplied by SQLite must be in range. */
114218 assert( iCol>=0 && iCol<=p->nColumn+1 );
114220 if( iCol==p->nColumn+1 ){
114221 /* This call is a request for the "docid" column. Since "docid" is an
114222 ** alias for "rowid", use the xRowid() method to obtain the value.
114224 sqlite3_int64 iRowid;
114225 rc = fts3RowidMethod(pCursor, &iRowid);
114226 sqlite3_result_int64(pContext, iRowid);
114227 }else if( iCol==p->nColumn ){
114228 /* The extra column whose name is the same as the table.
114229 ** Return a blob which is a pointer to the cursor.
114231 sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
114232 rc = SQLITE_OK;
114233 }else{
114234 rc = fts3CursorSeek(0, pCsr);
114235 if( rc==SQLITE_OK ){
114236 sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
114239 return rc;
114243 ** This function is the implementation of the xUpdate callback used by
114244 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
114245 ** inserted, updated or deleted.
114247 static int fts3UpdateMethod(
114248 sqlite3_vtab *pVtab, /* Virtual table handle */
114249 int nArg, /* Size of argument array */
114250 sqlite3_value **apVal, /* Array of arguments */
114251 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
114253 return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
114257 ** Implementation of xSync() method. Flush the contents of the pending-terms
114258 ** hash-table to the database.
114260 static int fts3SyncMethod(sqlite3_vtab *pVtab){
114261 int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
114262 sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
114263 return rc;
114267 ** Implementation of xBegin() method. This is a no-op.
114269 static int fts3BeginMethod(sqlite3_vtab *pVtab){
114270 UNUSED_PARAMETER(pVtab);
114271 assert( ((Fts3Table *)pVtab)->nPendingData==0 );
114272 return SQLITE_OK;
114276 ** Implementation of xCommit() method. This is a no-op. The contents of
114277 ** the pending-terms hash-table have already been flushed into the database
114278 ** by fts3SyncMethod().
114280 static int fts3CommitMethod(sqlite3_vtab *pVtab){
114281 UNUSED_PARAMETER(pVtab);
114282 assert( ((Fts3Table *)pVtab)->nPendingData==0 );
114283 return SQLITE_OK;
114287 ** Implementation of xRollback(). Discard the contents of the pending-terms
114288 ** hash-table. Any changes made to the database are reverted by SQLite.
114290 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
114291 sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
114292 return SQLITE_OK;
114296 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
114297 ** The loaded doclist contains positions as well as the document ids.
114298 ** This is used by the matchinfo(), snippet() and offsets() auxillary
114299 ** functions.
114301 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *pCsr, Fts3Expr *pExpr){
114302 int rc;
114303 assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
114304 assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
114305 rc = fts3EvalExpr(pCsr, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
114306 return rc;
114309 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(
114310 Fts3Cursor *pCsr,
114311 Fts3Expr *pExpr,
114312 char **paDoclist,
114313 int *pnDoclist
114315 int rc;
114316 assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
114317 assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
114318 pCsr->eEvalmode = FTS3_EVAL_MATCHINFO;
114319 rc = fts3EvalExpr(pCsr, pExpr, paDoclist, pnDoclist, 1);
114320 pCsr->eEvalmode = FTS3_EVAL_NEXT;
114321 return rc;
114325 ** After ExprLoadDoclist() (see above) has been called, this function is
114326 ** used to iterate/search through the position lists that make up the doclist
114327 ** stored in pExpr->aDoclist.
114329 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
114330 Fts3Expr *pExpr, /* Access this expressions doclist */
114331 sqlite3_int64 iDocid, /* Docid associated with requested pos-list */
114332 int iCol /* Column of requested pos-list */
114334 assert( pExpr->isLoaded );
114335 if( pExpr->aDoclist ){
114336 char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
114337 char *pCsr;
114339 if( pExpr->pCurrent==0 ){
114340 pExpr->pCurrent = pExpr->aDoclist;
114341 pExpr->iCurrent = 0;
114342 pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
114344 pCsr = pExpr->pCurrent;
114345 assert( pCsr );
114347 while( pCsr<pEnd ){
114348 if( pExpr->iCurrent<iDocid ){
114349 fts3PoslistCopy(0, &pCsr);
114350 if( pCsr<pEnd ){
114351 fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
114353 pExpr->pCurrent = pCsr;
114354 }else{
114355 if( pExpr->iCurrent==iDocid ){
114356 int iThis = 0;
114357 if( iCol<0 ){
114358 /* If iCol is negative, return a pointer to the start of the
114359 ** position-list (instead of a pointer to the start of a list
114360 ** of offsets associated with a specific column).
114362 return pCsr;
114364 while( iThis<iCol ){
114365 fts3ColumnlistCopy(0, &pCsr);
114366 if( *pCsr==0x00 ) return 0;
114367 pCsr++;
114368 pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
114370 if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
114372 return 0;
114377 return 0;
114381 ** Helper function used by the implementation of the overloaded snippet(),
114382 ** offsets() and optimize() SQL functions.
114384 ** If the value passed as the third argument is a blob of size
114385 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
114386 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
114387 ** message is written to context pContext and SQLITE_ERROR returned. The
114388 ** string passed via zFunc is used as part of the error message.
114390 static int fts3FunctionArg(
114391 sqlite3_context *pContext, /* SQL function call context */
114392 const char *zFunc, /* Function name */
114393 sqlite3_value *pVal, /* argv[0] passed to function */
114394 Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
114396 Fts3Cursor *pRet;
114397 if( sqlite3_value_type(pVal)!=SQLITE_BLOB
114398 || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
114400 char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
114401 sqlite3_result_error(pContext, zErr, -1);
114402 sqlite3_free(zErr);
114403 return SQLITE_ERROR;
114405 memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
114406 *ppCsr = pRet;
114407 return SQLITE_OK;
114411 ** Implementation of the snippet() function for FTS3
114413 static void fts3SnippetFunc(
114414 sqlite3_context *pContext, /* SQLite function call context */
114415 int nVal, /* Size of apVal[] array */
114416 sqlite3_value **apVal /* Array of arguments */
114418 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
114419 const char *zStart = "<b>";
114420 const char *zEnd = "</b>";
114421 const char *zEllipsis = "<b>...</b>";
114422 int iCol = -1;
114423 int nToken = 15; /* Default number of tokens in snippet */
114425 /* There must be at least one argument passed to this function (otherwise
114426 ** the non-overloaded version would have been called instead of this one).
114428 assert( nVal>=1 );
114430 if( nVal>6 ){
114431 sqlite3_result_error(pContext,
114432 "wrong number of arguments to function snippet()", -1);
114433 return;
114435 if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
114437 switch( nVal ){
114438 case 6: nToken = sqlite3_value_int(apVal[5]);
114439 case 5: iCol = sqlite3_value_int(apVal[4]);
114440 case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
114441 case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
114442 case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
114444 if( !zEllipsis || !zEnd || !zStart ){
114445 sqlite3_result_error_nomem(pContext);
114446 }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
114447 sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
114452 ** Implementation of the offsets() function for FTS3
114454 static void fts3OffsetsFunc(
114455 sqlite3_context *pContext, /* SQLite function call context */
114456 int nVal, /* Size of argument array */
114457 sqlite3_value **apVal /* Array of arguments */
114459 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
114461 UNUSED_PARAMETER(nVal);
114463 assert( nVal==1 );
114464 if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
114465 assert( pCsr );
114466 if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
114467 sqlite3Fts3Offsets(pContext, pCsr);
114472 ** Implementation of the special optimize() function for FTS3. This
114473 ** function merges all segments in the database to a single segment.
114474 ** Example usage is:
114476 ** SELECT optimize(t) FROM t LIMIT 1;
114478 ** where 't' is the name of an FTS3 table.
114480 static void fts3OptimizeFunc(
114481 sqlite3_context *pContext, /* SQLite function call context */
114482 int nVal, /* Size of argument array */
114483 sqlite3_value **apVal /* Array of arguments */
114485 int rc; /* Return code */
114486 Fts3Table *p; /* Virtual table handle */
114487 Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
114489 UNUSED_PARAMETER(nVal);
114491 assert( nVal==1 );
114492 if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
114493 p = (Fts3Table *)pCursor->base.pVtab;
114494 assert( p );
114496 rc = sqlite3Fts3Optimize(p);
114498 switch( rc ){
114499 case SQLITE_OK:
114500 sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
114501 break;
114502 case SQLITE_DONE:
114503 sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
114504 break;
114505 default:
114506 sqlite3_result_error_code(pContext, rc);
114507 break;
114512 ** Implementation of the matchinfo() function for FTS3
114514 static void fts3MatchinfoFunc(
114515 sqlite3_context *pContext, /* SQLite function call context */
114516 int nVal, /* Size of argument array */
114517 sqlite3_value **apVal /* Array of arguments */
114519 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
114520 assert( nVal==1 || nVal==2 );
114521 if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
114522 const char *zArg = 0;
114523 if( nVal>1 ){
114524 zArg = (const char *)sqlite3_value_text(apVal[1]);
114526 sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
114531 ** This routine implements the xFindFunction method for the FTS3
114532 ** virtual table.
114534 static int fts3FindFunctionMethod(
114535 sqlite3_vtab *pVtab, /* Virtual table handle */
114536 int nArg, /* Number of SQL function arguments */
114537 const char *zName, /* Name of SQL function */
114538 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
114539 void **ppArg /* Unused */
114541 struct Overloaded {
114542 const char *zName;
114543 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
114544 } aOverload[] = {
114545 { "snippet", fts3SnippetFunc },
114546 { "offsets", fts3OffsetsFunc },
114547 { "optimize", fts3OptimizeFunc },
114548 { "matchinfo", fts3MatchinfoFunc },
114550 int i; /* Iterator variable */
114552 UNUSED_PARAMETER(pVtab);
114553 UNUSED_PARAMETER(nArg);
114554 UNUSED_PARAMETER(ppArg);
114556 for(i=0; i<SizeofArray(aOverload); i++){
114557 if( strcmp(zName, aOverload[i].zName)==0 ){
114558 *pxFunc = aOverload[i].xFunc;
114559 return 1;
114563 /* No function of the specified name was found. Return 0. */
114564 return 0;
114568 ** Implementation of FTS3 xRename method. Rename an fts3 table.
114570 static int fts3RenameMethod(
114571 sqlite3_vtab *pVtab, /* Virtual table handle */
114572 const char *zName /* New name of table */
114574 Fts3Table *p = (Fts3Table *)pVtab;
114575 sqlite3 *db = p->db; /* Database connection */
114576 int rc; /* Return Code */
114578 rc = sqlite3Fts3PendingTermsFlush(p);
114579 if( rc!=SQLITE_OK ){
114580 return rc;
114583 fts3DbExec(&rc, db,
114584 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
114585 p->zDb, p->zName, zName
114587 if( p->bHasDocsize ){
114588 fts3DbExec(&rc, db,
114589 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
114590 p->zDb, p->zName, zName
114593 if( p->bHasStat ){
114594 fts3DbExec(&rc, db,
114595 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
114596 p->zDb, p->zName, zName
114599 fts3DbExec(&rc, db,
114600 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
114601 p->zDb, p->zName, zName
114603 fts3DbExec(&rc, db,
114604 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
114605 p->zDb, p->zName, zName
114607 return rc;
114610 static const sqlite3_module fts3Module = {
114611 /* iVersion */ 0,
114612 /* xCreate */ fts3CreateMethod,
114613 /* xConnect */ fts3ConnectMethod,
114614 /* xBestIndex */ fts3BestIndexMethod,
114615 /* xDisconnect */ fts3DisconnectMethod,
114616 /* xDestroy */ fts3DestroyMethod,
114617 /* xOpen */ fts3OpenMethod,
114618 /* xClose */ fts3CloseMethod,
114619 /* xFilter */ fts3FilterMethod,
114620 /* xNext */ fts3NextMethod,
114621 /* xEof */ fts3EofMethod,
114622 /* xColumn */ fts3ColumnMethod,
114623 /* xRowid */ fts3RowidMethod,
114624 /* xUpdate */ fts3UpdateMethod,
114625 /* xBegin */ fts3BeginMethod,
114626 /* xSync */ fts3SyncMethod,
114627 /* xCommit */ fts3CommitMethod,
114628 /* xRollback */ fts3RollbackMethod,
114629 /* xFindFunction */ fts3FindFunctionMethod,
114630 /* xRename */ fts3RenameMethod,
114634 ** This function is registered as the module destructor (called when an
114635 ** FTS3 enabled database connection is closed). It frees the memory
114636 ** allocated for the tokenizer hash table.
114638 static void hashDestroy(void *p){
114639 Fts3Hash *pHash = (Fts3Hash *)p;
114640 sqlite3Fts3HashClear(pHash);
114641 sqlite3_free(pHash);
114645 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
114646 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
114647 ** respectively. The following three forward declarations are for functions
114648 ** declared in these files used to retrieve the respective implementations.
114650 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
114651 ** to by the argument to point to the "simple" tokenizer implementation.
114652 ** And so on.
114654 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
114655 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
114656 #ifdef SQLITE_ENABLE_ICU
114657 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
114658 #endif
114661 ** Initialise the fts3 extension. If this extension is built as part
114662 ** of the sqlite library, then this function is called directly by
114663 ** SQLite. If fts3 is built as a dynamically loadable extension, this
114664 ** function is called by the sqlite3_extension_init() entry point.
114666 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
114667 int rc = SQLITE_OK;
114668 Fts3Hash *pHash = 0;
114669 const sqlite3_tokenizer_module *pSimple = 0;
114670 const sqlite3_tokenizer_module *pPorter = 0;
114672 #ifdef SQLITE_ENABLE_ICU
114673 const sqlite3_tokenizer_module *pIcu = 0;
114674 sqlite3Fts3IcuTokenizerModule(&pIcu);
114675 #endif
114677 rc = sqlite3Fts3InitAux(db);
114678 if( rc!=SQLITE_OK ) return rc;
114680 sqlite3Fts3SimpleTokenizerModule(&pSimple);
114681 sqlite3Fts3PorterTokenizerModule(&pPorter);
114683 /* Allocate and initialise the hash-table used to store tokenizers. */
114684 pHash = sqlite3_malloc(sizeof(Fts3Hash));
114685 if( !pHash ){
114686 rc = SQLITE_NOMEM;
114687 }else{
114688 sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
114691 /* Load the built-in tokenizers into the hash table */
114692 if( rc==SQLITE_OK ){
114693 if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
114694 || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
114695 #ifdef SQLITE_ENABLE_ICU
114696 || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
114697 #endif
114699 rc = SQLITE_NOMEM;
114703 #ifdef SQLITE_TEST
114704 if( rc==SQLITE_OK ){
114705 rc = sqlite3Fts3ExprInitTestInterface(db);
114707 #endif
114709 /* Create the virtual table wrapper around the hash-table and overload
114710 ** the two scalar functions. If this is successful, register the
114711 ** module with sqlite.
114713 if( SQLITE_OK==rc
114714 #if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
114715 /* fts3_tokenizer() disabled for security reasons. */
114716 #else
114717 && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
114718 #endif
114719 && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
114720 && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
114721 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
114722 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
114723 && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
114725 rc = sqlite3_create_module_v2(
114726 db, "fts3", &fts3Module, (void *)pHash, hashDestroy
114728 #if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
114729 /* Disable fts4 pending review. */
114730 #else
114731 if( rc==SQLITE_OK ){
114732 rc = sqlite3_create_module_v2(
114733 db, "fts4", &fts3Module, (void *)pHash, 0
114736 #endif
114737 return rc;
114740 /* An error has occurred. Delete the hash table and return the error code. */
114741 assert( rc!=SQLITE_OK );
114742 if( pHash ){
114743 sqlite3Fts3HashClear(pHash);
114744 sqlite3_free(pHash);
114746 return rc;
114749 #if !SQLITE_CORE
114750 SQLITE_API int sqlite3_extension_init(
114751 sqlite3 *db,
114752 char **pzErrMsg,
114753 const sqlite3_api_routines *pApi
114755 SQLITE_EXTENSION_INIT2(pApi)
114756 return sqlite3Fts3Init(db);
114758 #endif
114760 #endif
114762 /************** End of fts3.c ************************************************/
114763 /************** Begin file fts3_aux.c ****************************************/
114765 ** 2011 Jan 27
114767 ** The author disclaims copyright to this source code. In place of
114768 ** a legal notice, here is a blessing:
114770 ** May you do good and not evil.
114771 ** May you find forgiveness for yourself and forgive others.
114772 ** May you share freely, never taking more than you give.
114774 ******************************************************************************
114778 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114781 typedef struct Fts3auxTable Fts3auxTable;
114782 typedef struct Fts3auxCursor Fts3auxCursor;
114784 struct Fts3auxTable {
114785 sqlite3_vtab base; /* Base class used by SQLite core */
114786 Fts3Table *pFts3Tab;
114789 struct Fts3auxCursor {
114790 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
114791 Fts3SegReaderCursor csr; /* Must be right after "base" */
114792 Fts3SegFilter filter;
114793 char *zStop;
114794 int nStop; /* Byte-length of string zStop */
114795 int isEof; /* True if cursor is at EOF */
114796 sqlite3_int64 iRowid; /* Current rowid */
114798 int iCol; /* Current value of 'col' column */
114799 int nStat; /* Size of aStat[] array */
114800 struct Fts3auxColstats {
114801 sqlite3_int64 nDoc; /* 'documents' values for current csr row */
114802 sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
114803 } *aStat;
114807 ** Schema of the terms table.
114809 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
114812 ** This function does all the work for both the xConnect and xCreate methods.
114813 ** These tables have no persistent representation of their own, so xConnect
114814 ** and xCreate are identical operations.
114816 static int fts3auxConnectMethod(
114817 sqlite3 *db, /* Database connection */
114818 void *pUnused, /* Unused */
114819 int argc, /* Number of elements in argv array */
114820 const char * const *argv, /* xCreate/xConnect argument array */
114821 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
114822 char **pzErr /* OUT: sqlite3_malloc'd error message */
114824 char const *zDb; /* Name of database (e.g. "main") */
114825 char const *zFts3; /* Name of fts3 table */
114826 int nDb; /* Result of strlen(zDb) */
114827 int nFts3; /* Result of strlen(zFts3) */
114828 int nByte; /* Bytes of space to allocate here */
114829 int rc; /* value returned by declare_vtab() */
114830 Fts3auxTable *p; /* Virtual table object to return */
114832 UNUSED_PARAMETER(pUnused);
114834 /* The user should specify a single argument - the name of an fts3 table. */
114835 if( argc!=4 ){
114836 *pzErr = sqlite3_mprintf(
114837 "wrong number of arguments to fts4aux constructor"
114839 return SQLITE_ERROR;
114842 zDb = argv[1];
114843 nDb = strlen(zDb);
114844 zFts3 = argv[3];
114845 nFts3 = strlen(zFts3);
114847 rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
114848 if( rc!=SQLITE_OK ) return rc;
114850 nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
114851 p = (Fts3auxTable *)sqlite3_malloc(nByte);
114852 if( !p ) return SQLITE_NOMEM;
114853 memset(p, 0, nByte);
114855 p->pFts3Tab = (Fts3Table *)&p[1];
114856 p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
114857 p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
114858 p->pFts3Tab->db = db;
114860 memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
114861 memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
114862 sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
114864 *ppVtab = (sqlite3_vtab *)p;
114865 return SQLITE_OK;
114869 ** This function does the work for both the xDisconnect and xDestroy methods.
114870 ** These tables have no persistent representation of their own, so xDisconnect
114871 ** and xDestroy are identical operations.
114873 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
114874 Fts3auxTable *p = (Fts3auxTable *)pVtab;
114875 Fts3Table *pFts3 = p->pFts3Tab;
114876 int i;
114878 /* Free any prepared statements held */
114879 for(i=0; i<SizeofArray(pFts3->aStmt); i++){
114880 sqlite3_finalize(pFts3->aStmt[i]);
114882 sqlite3_free(pFts3->zSegmentsTbl);
114883 sqlite3_free(p);
114884 return SQLITE_OK;
114887 #define FTS4AUX_EQ_CONSTRAINT 1
114888 #define FTS4AUX_GE_CONSTRAINT 2
114889 #define FTS4AUX_LE_CONSTRAINT 4
114892 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
114894 static int fts3auxBestIndexMethod(
114895 sqlite3_vtab *pVTab,
114896 sqlite3_index_info *pInfo
114898 int i;
114899 int iEq = -1;
114900 int iGe = -1;
114901 int iLe = -1;
114903 UNUSED_PARAMETER(pVTab);
114905 /* This vtab delivers always results in "ORDER BY term ASC" order. */
114906 if( pInfo->nOrderBy==1
114907 && pInfo->aOrderBy[0].iColumn==0
114908 && pInfo->aOrderBy[0].desc==0
114910 pInfo->orderByConsumed = 1;
114913 /* Search for equality and range constraints on the "term" column. */
114914 for(i=0; i<pInfo->nConstraint; i++){
114915 if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
114916 int op = pInfo->aConstraint[i].op;
114917 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
114918 if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
114919 if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
114920 if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
114921 if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
114925 if( iEq>=0 ){
114926 pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
114927 pInfo->aConstraintUsage[iEq].argvIndex = 1;
114928 pInfo->estimatedCost = 5;
114929 }else{
114930 pInfo->idxNum = 0;
114931 pInfo->estimatedCost = 20000;
114932 if( iGe>=0 ){
114933 pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
114934 pInfo->aConstraintUsage[iGe].argvIndex = 1;
114935 pInfo->estimatedCost /= 2;
114937 if( iLe>=0 ){
114938 pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
114939 pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
114940 pInfo->estimatedCost /= 2;
114944 return SQLITE_OK;
114948 ** xOpen - Open a cursor.
114950 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
114951 Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
114953 UNUSED_PARAMETER(pVTab);
114955 pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
114956 if( !pCsr ) return SQLITE_NOMEM;
114957 memset(pCsr, 0, sizeof(Fts3auxCursor));
114959 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
114960 return SQLITE_OK;
114964 ** xClose - Close a cursor.
114966 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
114967 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
114968 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
114970 sqlite3Fts3SegmentsClose(pFts3);
114971 sqlite3Fts3SegReaderFinish(&pCsr->csr);
114972 sqlite3_free((void *)pCsr->filter.zTerm);
114973 sqlite3_free(pCsr->zStop);
114974 sqlite3_free(pCsr->aStat);
114975 sqlite3_free(pCsr);
114976 return SQLITE_OK;
114979 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
114980 if( nSize>pCsr->nStat ){
114981 struct Fts3auxColstats *aNew;
114982 aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
114983 sizeof(struct Fts3auxColstats) * nSize
114985 if( aNew==0 ) return SQLITE_NOMEM;
114986 memset(&aNew[pCsr->nStat], 0,
114987 sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
114989 pCsr->aStat = aNew;
114990 pCsr->nStat = nSize;
114992 return SQLITE_OK;
114996 ** xNext - Advance the cursor to the next row, if any.
114998 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
114999 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
115000 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
115001 int rc;
115003 /* Increment our pretend rowid value. */
115004 pCsr->iRowid++;
115006 for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
115007 if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
115010 rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
115011 if( rc==SQLITE_ROW ){
115012 int i = 0;
115013 int nDoclist = pCsr->csr.nDoclist;
115014 char *aDoclist = pCsr->csr.aDoclist;
115015 int iCol;
115017 int eState = 0;
115019 if( pCsr->zStop ){
115020 int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
115021 int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
115022 if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
115023 pCsr->isEof = 1;
115024 return SQLITE_OK;
115028 if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
115029 memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
115030 iCol = 0;
115032 while( i<nDoclist ){
115033 sqlite3_int64 v = 0;
115035 i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
115036 switch( eState ){
115037 /* State 0. In this state the integer just read was a docid. */
115038 case 0:
115039 pCsr->aStat[0].nDoc++;
115040 eState = 1;
115041 iCol = 0;
115042 break;
115044 /* State 1. In this state we are expecting either a 1, indicating
115045 ** that the following integer will be a column number, or the
115046 ** start of a position list for column 0.
115048 ** The only difference between state 1 and state 2 is that if the
115049 ** integer encountered in state 1 is not 0 or 1, then we need to
115050 ** increment the column 0 "nDoc" count for this term.
115052 case 1:
115053 assert( iCol==0 );
115054 if( v>1 ){
115055 pCsr->aStat[1].nDoc++;
115057 eState = 2;
115058 /* fall through */
115060 case 2:
115061 if( v==0 ){ /* 0x00. Next integer will be a docid. */
115062 eState = 0;
115063 }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
115064 eState = 3;
115065 }else{ /* 2 or greater. A position. */
115066 pCsr->aStat[iCol+1].nOcc++;
115067 pCsr->aStat[0].nOcc++;
115069 break;
115071 /* State 3. The integer just read is a column number. */
115072 default: assert( eState==3 );
115073 iCol = (int)v;
115074 if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
115075 pCsr->aStat[iCol+1].nDoc++;
115076 eState = 2;
115077 break;
115081 pCsr->iCol = 0;
115082 rc = SQLITE_OK;
115083 }else{
115084 pCsr->isEof = 1;
115086 return rc;
115090 ** xFilter - Initialize a cursor to point at the start of its data.
115092 static int fts3auxFilterMethod(
115093 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
115094 int idxNum, /* Strategy index */
115095 const char *idxStr, /* Unused */
115096 int nVal, /* Number of elements in apVal */
115097 sqlite3_value **apVal /* Arguments for the indexing scheme */
115099 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
115100 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
115101 int rc;
115102 int isScan;
115104 UNUSED_PARAMETER(nVal);
115106 assert( idxStr==0 );
115107 assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
115108 || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
115109 || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
115111 isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
115113 /* In case this cursor is being reused, close and zero it. */
115114 testcase(pCsr->filter.zTerm);
115115 sqlite3Fts3SegReaderFinish(&pCsr->csr);
115116 sqlite3_free((void *)pCsr->filter.zTerm);
115117 sqlite3_free(pCsr->aStat);
115118 memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
115120 pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
115121 if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
115123 if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
115124 const unsigned char *zStr = sqlite3_value_text(apVal[0]);
115125 if( zStr ){
115126 pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
115127 pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
115128 if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
115131 if( idxNum&FTS4AUX_LE_CONSTRAINT ){
115132 int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
115133 pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
115134 pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
115135 if( pCsr->zStop==0 ) return SQLITE_NOMEM;
115138 rc = sqlite3Fts3SegReaderCursor(pFts3, FTS3_SEGCURSOR_ALL,
115139 pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
115141 if( rc==SQLITE_OK ){
115142 rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
115145 if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
115146 return rc;
115150 ** xEof - Return true if the cursor is at EOF, or false otherwise.
115152 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
115153 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
115154 return pCsr->isEof;
115158 ** xColumn - Return a column value.
115160 static int fts3auxColumnMethod(
115161 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
115162 sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */
115163 int iCol /* Index of column to read value from */
115165 Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
115167 assert( p->isEof==0 );
115168 if( iCol==0 ){ /* Column "term" */
115169 sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
115170 }else if( iCol==1 ){ /* Column "col" */
115171 if( p->iCol ){
115172 sqlite3_result_int(pContext, p->iCol-1);
115173 }else{
115174 sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
115176 }else if( iCol==2 ){ /* Column "documents" */
115177 sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
115178 }else{ /* Column "occurrences" */
115179 sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
115182 return SQLITE_OK;
115186 ** xRowid - Return the current rowid for the cursor.
115188 static int fts3auxRowidMethod(
115189 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
115190 sqlite_int64 *pRowid /* OUT: Rowid value */
115192 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
115193 *pRowid = pCsr->iRowid;
115194 return SQLITE_OK;
115198 ** Register the fts3aux module with database connection db. Return SQLITE_OK
115199 ** if successful or an error code if sqlite3_create_module() fails.
115201 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
115202 static const sqlite3_module fts3aux_module = {
115203 0, /* iVersion */
115204 fts3auxConnectMethod, /* xCreate */
115205 fts3auxConnectMethod, /* xConnect */
115206 fts3auxBestIndexMethod, /* xBestIndex */
115207 fts3auxDisconnectMethod, /* xDisconnect */
115208 fts3auxDisconnectMethod, /* xDestroy */
115209 fts3auxOpenMethod, /* xOpen */
115210 fts3auxCloseMethod, /* xClose */
115211 fts3auxFilterMethod, /* xFilter */
115212 fts3auxNextMethod, /* xNext */
115213 fts3auxEofMethod, /* xEof */
115214 fts3auxColumnMethod, /* xColumn */
115215 fts3auxRowidMethod, /* xRowid */
115216 0, /* xUpdate */
115217 0, /* xBegin */
115218 0, /* xSync */
115219 0, /* xCommit */
115220 0, /* xRollback */
115221 0, /* xFindFunction */
115222 0 /* xRename */
115224 int rc; /* Return code */
115226 rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
115227 return rc;
115230 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
115232 /************** End of fts3_aux.c ********************************************/
115233 /************** Begin file fts3_expr.c ***************************************/
115235 ** 2008 Nov 28
115237 ** The author disclaims copyright to this source code. In place of
115238 ** a legal notice, here is a blessing:
115240 ** May you do good and not evil.
115241 ** May you find forgiveness for yourself and forgive others.
115242 ** May you share freely, never taking more than you give.
115244 ******************************************************************************
115246 ** This module contains code that implements a parser for fts3 query strings
115247 ** (the right-hand argument to the MATCH operator). Because the supported
115248 ** syntax is relatively simple, the whole tokenizer/parser system is
115249 ** hand-coded.
115251 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
115254 ** By default, this module parses the legacy syntax that has been
115255 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
115256 ** is defined, then it uses the new syntax. The differences between
115257 ** the new and the old syntaxes are:
115259 ** a) The new syntax supports parenthesis. The old does not.
115261 ** b) The new syntax supports the AND and NOT operators. The old does not.
115263 ** c) The old syntax supports the "-" token qualifier. This is not
115264 ** supported by the new syntax (it is replaced by the NOT operator).
115266 ** d) When using the old syntax, the OR operator has a greater precedence
115267 ** than an implicit AND. When using the new, both implicity and explicit
115268 ** AND operators have a higher precedence than OR.
115270 ** If compiled with SQLITE_TEST defined, then this module exports the
115271 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
115272 ** to zero causes the module to use the old syntax. If it is set to
115273 ** non-zero the new syntax is activated. This is so both syntaxes can
115274 ** be tested using a single build of testfixture.
115276 ** The following describes the syntax supported by the fts3 MATCH
115277 ** operator in a similar format to that used by the lemon parser
115278 ** generator. This module does not use actually lemon, it uses a
115279 ** custom parser.
115281 ** query ::= andexpr (OR andexpr)*.
115283 ** andexpr ::= notexpr (AND? notexpr)*.
115285 ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
115286 ** notexpr ::= LP query RP.
115288 ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
115290 ** distance_opt ::= .
115291 ** distance_opt ::= / INTEGER.
115293 ** phrase ::= TOKEN.
115294 ** phrase ::= COLUMN:TOKEN.
115295 ** phrase ::= "TOKEN TOKEN TOKEN...".
115298 #ifdef SQLITE_TEST
115299 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
115300 #else
115301 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
115302 # define sqlite3_fts3_enable_parentheses 1
115303 # else
115304 # define sqlite3_fts3_enable_parentheses 0
115305 # endif
115306 #endif
115309 ** Default span for NEAR operators.
115311 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
115314 typedef struct ParseContext ParseContext;
115315 struct ParseContext {
115316 sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
115317 const char **azCol; /* Array of column names for fts3 table */
115318 int nCol; /* Number of entries in azCol[] */
115319 int iDefaultCol; /* Default column to query */
115320 sqlite3_context *pCtx; /* Write error message here */
115321 int nNest; /* Number of nested brackets */
115325 ** This function is equivalent to the standard isspace() function.
115327 ** The standard isspace() can be awkward to use safely, because although it
115328 ** is defined to accept an argument of type int, its behaviour when passed
115329 ** an integer that falls outside of the range of the unsigned char type
115330 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
115331 ** is defined to accept an argument of type char, and always returns 0 for
115332 ** any values that fall outside of the range of the unsigned char type (i.e.
115333 ** negative values).
115335 static int fts3isspace(char c){
115336 return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
115340 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
115341 ** zero the memory before returning a pointer to it. If unsuccessful,
115342 ** return NULL.
115344 static void *fts3MallocZero(int nByte){
115345 void *pRet = sqlite3_malloc(nByte);
115346 if( pRet ) memset(pRet, 0, nByte);
115347 return pRet;
115352 ** Extract the next token from buffer z (length n) using the tokenizer
115353 ** and other information (column names etc.) in pParse. Create an Fts3Expr
115354 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
115355 ** single token and set *ppExpr to point to it. If the end of the buffer is
115356 ** reached before a token is found, set *ppExpr to zero. It is the
115357 ** responsibility of the caller to eventually deallocate the allocated
115358 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
115360 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
115361 ** fails.
115363 static int getNextToken(
115364 ParseContext *pParse, /* fts3 query parse context */
115365 int iCol, /* Value for Fts3Phrase.iColumn */
115366 const char *z, int n, /* Input string */
115367 Fts3Expr **ppExpr, /* OUT: expression */
115368 int *pnConsumed /* OUT: Number of bytes consumed */
115370 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
115371 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
115372 int rc;
115373 sqlite3_tokenizer_cursor *pCursor;
115374 Fts3Expr *pRet = 0;
115375 int nConsumed = 0;
115377 rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
115378 if( rc==SQLITE_OK ){
115379 const char *zToken;
115380 int nToken, iStart, iEnd, iPosition;
115381 int nByte; /* total space to allocate */
115383 pCursor->pTokenizer = pTokenizer;
115384 rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
115386 if( rc==SQLITE_OK ){
115387 nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
115388 pRet = (Fts3Expr *)fts3MallocZero(nByte);
115389 if( !pRet ){
115390 rc = SQLITE_NOMEM;
115391 }else{
115392 pRet->eType = FTSQUERY_PHRASE;
115393 pRet->pPhrase = (Fts3Phrase *)&pRet[1];
115394 pRet->pPhrase->nToken = 1;
115395 pRet->pPhrase->iColumn = iCol;
115396 pRet->pPhrase->aToken[0].n = nToken;
115397 pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
115398 memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
115400 if( iEnd<n && z[iEnd]=='*' ){
115401 pRet->pPhrase->aToken[0].isPrefix = 1;
115402 iEnd++;
115404 if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
115405 pRet->pPhrase->isNot = 1;
115408 nConsumed = iEnd;
115411 pModule->xClose(pCursor);
115414 *pnConsumed = nConsumed;
115415 *ppExpr = pRet;
115416 return rc;
115421 ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
115422 ** then free the old allocation.
115424 static void *fts3ReallocOrFree(void *pOrig, int nNew){
115425 void *pRet = sqlite3_realloc(pOrig, nNew);
115426 if( !pRet ){
115427 sqlite3_free(pOrig);
115429 return pRet;
115433 ** Buffer zInput, length nInput, contains the contents of a quoted string
115434 ** that appeared as part of an fts3 query expression. Neither quote character
115435 ** is included in the buffer. This function attempts to tokenize the entire
115436 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
115437 ** containing the results.
115439 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
115440 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
115441 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
115442 ** to 0.
115444 static int getNextString(
115445 ParseContext *pParse, /* fts3 query parse context */
115446 const char *zInput, int nInput, /* Input string */
115447 Fts3Expr **ppExpr /* OUT: expression */
115449 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
115450 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
115451 int rc;
115452 Fts3Expr *p = 0;
115453 sqlite3_tokenizer_cursor *pCursor = 0;
115454 char *zTemp = 0;
115455 int nTemp = 0;
115457 rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
115458 if( rc==SQLITE_OK ){
115459 int ii;
115460 pCursor->pTokenizer = pTokenizer;
115461 for(ii=0; rc==SQLITE_OK; ii++){
115462 const char *zToken;
115463 int nToken, iBegin, iEnd, iPos;
115464 rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
115465 if( rc==SQLITE_OK ){
115466 int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
115467 p = fts3ReallocOrFree(p, nByte+ii*sizeof(Fts3PhraseToken));
115468 zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
115469 if( !p || !zTemp ){
115470 goto no_mem;
115472 if( ii==0 ){
115473 memset(p, 0, nByte);
115474 p->pPhrase = (Fts3Phrase *)&p[1];
115476 p->pPhrase = (Fts3Phrase *)&p[1];
115477 memset(&p->pPhrase->aToken[ii], 0, sizeof(Fts3PhraseToken));
115478 p->pPhrase->nToken = ii+1;
115479 p->pPhrase->aToken[ii].n = nToken;
115480 memcpy(&zTemp[nTemp], zToken, nToken);
115481 nTemp += nToken;
115482 if( iEnd<nInput && zInput[iEnd]=='*' ){
115483 p->pPhrase->aToken[ii].isPrefix = 1;
115484 }else{
115485 p->pPhrase->aToken[ii].isPrefix = 0;
115490 pModule->xClose(pCursor);
115491 pCursor = 0;
115494 if( rc==SQLITE_DONE ){
115495 int jj;
115496 char *zNew = NULL;
115497 int nNew = 0;
115498 int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
115499 nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(Fts3PhraseToken);
115500 p = fts3ReallocOrFree(p, nByte + nTemp);
115501 if( !p ){
115502 goto no_mem;
115504 if( zTemp ){
115505 zNew = &(((char *)p)[nByte]);
115506 memcpy(zNew, zTemp, nTemp);
115507 }else{
115508 memset(p, 0, nByte+nTemp);
115510 p->pPhrase = (Fts3Phrase *)&p[1];
115511 for(jj=0; jj<p->pPhrase->nToken; jj++){
115512 p->pPhrase->aToken[jj].z = &zNew[nNew];
115513 nNew += p->pPhrase->aToken[jj].n;
115515 sqlite3_free(zTemp);
115516 p->eType = FTSQUERY_PHRASE;
115517 p->pPhrase->iColumn = pParse->iDefaultCol;
115518 rc = SQLITE_OK;
115521 *ppExpr = p;
115522 return rc;
115523 no_mem:
115525 if( pCursor ){
115526 pModule->xClose(pCursor);
115528 sqlite3_free(zTemp);
115529 sqlite3_free(p);
115530 *ppExpr = 0;
115531 return SQLITE_NOMEM;
115535 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
115536 ** call fts3ExprParse(). So this forward declaration is required.
115538 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
115541 ** The output variable *ppExpr is populated with an allocated Fts3Expr
115542 ** structure, or set to 0 if the end of the input buffer is reached.
115544 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
115545 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
115546 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
115548 static int getNextNode(
115549 ParseContext *pParse, /* fts3 query parse context */
115550 const char *z, int n, /* Input string */
115551 Fts3Expr **ppExpr, /* OUT: expression */
115552 int *pnConsumed /* OUT: Number of bytes consumed */
115554 static const struct Fts3Keyword {
115555 char *z; /* Keyword text */
115556 unsigned char n; /* Length of the keyword */
115557 unsigned char parenOnly; /* Only valid in paren mode */
115558 unsigned char eType; /* Keyword code */
115559 } aKeyword[] = {
115560 { "OR" , 2, 0, FTSQUERY_OR },
115561 { "AND", 3, 1, FTSQUERY_AND },
115562 { "NOT", 3, 1, FTSQUERY_NOT },
115563 { "NEAR", 4, 0, FTSQUERY_NEAR }
115565 int ii;
115566 int iCol;
115567 int iColLen;
115568 int rc;
115569 Fts3Expr *pRet = 0;
115571 const char *zInput = z;
115572 int nInput = n;
115574 /* Skip over any whitespace before checking for a keyword, an open or
115575 ** close bracket, or a quoted string.
115577 while( nInput>0 && fts3isspace(*zInput) ){
115578 nInput--;
115579 zInput++;
115581 if( nInput==0 ){
115582 return SQLITE_DONE;
115585 /* See if we are dealing with a keyword. */
115586 for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
115587 const struct Fts3Keyword *pKey = &aKeyword[ii];
115589 if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
115590 continue;
115593 if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
115594 int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
115595 int nKey = pKey->n;
115596 char cNext;
115598 /* If this is a "NEAR" keyword, check for an explicit nearness. */
115599 if( pKey->eType==FTSQUERY_NEAR ){
115600 assert( nKey==4 );
115601 if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
115602 nNear = 0;
115603 for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
115604 nNear = nNear * 10 + (zInput[nKey] - '0');
115609 /* At this point this is probably a keyword. But for that to be true,
115610 ** the next byte must contain either whitespace, an open or close
115611 ** parenthesis, a quote character, or EOF.
115613 cNext = zInput[nKey];
115614 if( fts3isspace(cNext)
115615 || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
115617 pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
115618 if( !pRet ){
115619 return SQLITE_NOMEM;
115621 pRet->eType = pKey->eType;
115622 pRet->nNear = nNear;
115623 *ppExpr = pRet;
115624 *pnConsumed = (int)((zInput - z) + nKey);
115625 return SQLITE_OK;
115628 /* Turns out that wasn't a keyword after all. This happens if the
115629 ** user has supplied a token such as "ORacle". Continue.
115634 /* Check for an open bracket. */
115635 if( sqlite3_fts3_enable_parentheses ){
115636 if( *zInput=='(' ){
115637 int nConsumed;
115638 pParse->nNest++;
115639 rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
115640 if( rc==SQLITE_OK && !*ppExpr ){
115641 rc = SQLITE_DONE;
115643 *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
115644 return rc;
115647 /* Check for a close bracket. */
115648 if( *zInput==')' ){
115649 pParse->nNest--;
115650 *pnConsumed = (int)((zInput - z) + 1);
115651 return SQLITE_DONE;
115655 /* See if we are dealing with a quoted phrase. If this is the case, then
115656 ** search for the closing quote and pass the whole string to getNextString()
115657 ** for processing. This is easy to do, as fts3 has no syntax for escaping
115658 ** a quote character embedded in a string.
115660 if( *zInput=='"' ){
115661 for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
115662 *pnConsumed = (int)((zInput - z) + ii + 1);
115663 if( ii==nInput ){
115664 return SQLITE_ERROR;
115666 return getNextString(pParse, &zInput[1], ii-1, ppExpr);
115670 /* If control flows to this point, this must be a regular token, or
115671 ** the end of the input. Read a regular token using the sqlite3_tokenizer
115672 ** interface. Before doing so, figure out if there is an explicit
115673 ** column specifier for the token.
115675 ** TODO: Strangely, it is not possible to associate a column specifier
115676 ** with a quoted phrase, only with a single token. Not sure if this was
115677 ** an implementation artifact or an intentional decision when fts3 was
115678 ** first implemented. Whichever it was, this module duplicates the
115679 ** limitation.
115681 iCol = pParse->iDefaultCol;
115682 iColLen = 0;
115683 for(ii=0; ii<pParse->nCol; ii++){
115684 const char *zStr = pParse->azCol[ii];
115685 int nStr = (int)strlen(zStr);
115686 if( nInput>nStr && zInput[nStr]==':'
115687 && sqlite3_strnicmp(zStr, zInput, nStr)==0
115689 iCol = ii;
115690 iColLen = (int)((zInput - z) + nStr + 1);
115691 break;
115694 rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
115695 *pnConsumed += iColLen;
115696 return rc;
115700 ** The argument is an Fts3Expr structure for a binary operator (any type
115701 ** except an FTSQUERY_PHRASE). Return an integer value representing the
115702 ** precedence of the operator. Lower values have a higher precedence (i.e.
115703 ** group more tightly). For example, in the C language, the == operator
115704 ** groups more tightly than ||, and would therefore have a higher precedence.
115706 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
115707 ** is defined), the order of the operators in precedence from highest to
115708 ** lowest is:
115710 ** NEAR
115711 ** NOT
115712 ** AND (including implicit ANDs)
115713 ** OR
115715 ** Note that when using the old query syntax, the OR operator has a higher
115716 ** precedence than the AND operator.
115718 static int opPrecedence(Fts3Expr *p){
115719 assert( p->eType!=FTSQUERY_PHRASE );
115720 if( sqlite3_fts3_enable_parentheses ){
115721 return p->eType;
115722 }else if( p->eType==FTSQUERY_NEAR ){
115723 return 1;
115724 }else if( p->eType==FTSQUERY_OR ){
115725 return 2;
115727 assert( p->eType==FTSQUERY_AND );
115728 return 3;
115732 ** Argument ppHead contains a pointer to the current head of a query
115733 ** expression tree being parsed. pPrev is the expression node most recently
115734 ** inserted into the tree. This function adds pNew, which is always a binary
115735 ** operator node, into the expression tree based on the relative precedence
115736 ** of pNew and the existing nodes of the tree. This may result in the head
115737 ** of the tree changing, in which case *ppHead is set to the new root node.
115739 static void insertBinaryOperator(
115740 Fts3Expr **ppHead, /* Pointer to the root node of a tree */
115741 Fts3Expr *pPrev, /* Node most recently inserted into the tree */
115742 Fts3Expr *pNew /* New binary node to insert into expression tree */
115744 Fts3Expr *pSplit = pPrev;
115745 while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
115746 pSplit = pSplit->pParent;
115749 if( pSplit->pParent ){
115750 assert( pSplit->pParent->pRight==pSplit );
115751 pSplit->pParent->pRight = pNew;
115752 pNew->pParent = pSplit->pParent;
115753 }else{
115754 *ppHead = pNew;
115756 pNew->pLeft = pSplit;
115757 pSplit->pParent = pNew;
115761 ** Parse the fts3 query expression found in buffer z, length n. This function
115762 ** returns either when the end of the buffer is reached or an unmatched
115763 ** closing bracket - ')' - is encountered.
115765 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
115766 ** parsed form of the expression and *pnConsumed is set to the number of
115767 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
115768 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
115770 static int fts3ExprParse(
115771 ParseContext *pParse, /* fts3 query parse context */
115772 const char *z, int n, /* Text of MATCH query */
115773 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
115774 int *pnConsumed /* OUT: Number of bytes consumed */
115776 Fts3Expr *pRet = 0;
115777 Fts3Expr *pPrev = 0;
115778 Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
115779 int nIn = n;
115780 const char *zIn = z;
115781 int rc = SQLITE_OK;
115782 int isRequirePhrase = 1;
115784 while( rc==SQLITE_OK ){
115785 Fts3Expr *p = 0;
115786 int nByte = 0;
115787 rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
115788 if( rc==SQLITE_OK ){
115789 int isPhrase;
115791 if( !sqlite3_fts3_enable_parentheses
115792 && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
115794 /* Create an implicit NOT operator. */
115795 Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
115796 if( !pNot ){
115797 sqlite3Fts3ExprFree(p);
115798 rc = SQLITE_NOMEM;
115799 goto exprparse_out;
115801 pNot->eType = FTSQUERY_NOT;
115802 pNot->pRight = p;
115803 if( pNotBranch ){
115804 pNot->pLeft = pNotBranch;
115806 pNotBranch = pNot;
115807 p = pPrev;
115808 }else{
115809 int eType = p->eType;
115810 assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
115811 isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
115813 /* The isRequirePhrase variable is set to true if a phrase or
115814 ** an expression contained in parenthesis is required. If a
115815 ** binary operator (AND, OR, NOT or NEAR) is encounted when
115816 ** isRequirePhrase is set, this is a syntax error.
115818 if( !isPhrase && isRequirePhrase ){
115819 sqlite3Fts3ExprFree(p);
115820 rc = SQLITE_ERROR;
115821 goto exprparse_out;
115824 if( isPhrase && !isRequirePhrase ){
115825 /* Insert an implicit AND operator. */
115826 Fts3Expr *pAnd;
115827 assert( pRet && pPrev );
115828 pAnd = fts3MallocZero(sizeof(Fts3Expr));
115829 if( !pAnd ){
115830 sqlite3Fts3ExprFree(p);
115831 rc = SQLITE_NOMEM;
115832 goto exprparse_out;
115834 pAnd->eType = FTSQUERY_AND;
115835 insertBinaryOperator(&pRet, pPrev, pAnd);
115836 pPrev = pAnd;
115839 /* This test catches attempts to make either operand of a NEAR
115840 ** operator something other than a phrase. For example, either of
115841 ** the following:
115843 ** (bracketed expression) NEAR phrase
115844 ** phrase NEAR (bracketed expression)
115846 ** Return an error in either case.
115848 if( pPrev && (
115849 (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
115850 || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
115852 sqlite3Fts3ExprFree(p);
115853 rc = SQLITE_ERROR;
115854 goto exprparse_out;
115857 if( isPhrase ){
115858 if( pRet ){
115859 assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
115860 pPrev->pRight = p;
115861 p->pParent = pPrev;
115862 }else{
115863 pRet = p;
115865 }else{
115866 insertBinaryOperator(&pRet, pPrev, p);
115868 isRequirePhrase = !isPhrase;
115870 assert( nByte>0 );
115872 assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
115873 nIn -= nByte;
115874 zIn += nByte;
115875 pPrev = p;
115878 if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
115879 rc = SQLITE_ERROR;
115882 if( rc==SQLITE_DONE ){
115883 rc = SQLITE_OK;
115884 if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
115885 if( !pRet ){
115886 rc = SQLITE_ERROR;
115887 }else{
115888 Fts3Expr *pIter = pNotBranch;
115889 while( pIter->pLeft ){
115890 pIter = pIter->pLeft;
115892 pIter->pLeft = pRet;
115893 pRet = pNotBranch;
115897 *pnConsumed = n - nIn;
115899 exprparse_out:
115900 if( rc!=SQLITE_OK ){
115901 sqlite3Fts3ExprFree(pRet);
115902 sqlite3Fts3ExprFree(pNotBranch);
115903 pRet = 0;
115905 *ppExpr = pRet;
115906 return rc;
115910 ** Parameters z and n contain a pointer to and length of a buffer containing
115911 ** an fts3 query expression, respectively. This function attempts to parse the
115912 ** query expression and create a tree of Fts3Expr structures representing the
115913 ** parsed expression. If successful, *ppExpr is set to point to the head
115914 ** of the parsed expression tree and SQLITE_OK is returned. If an error
115915 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
115916 ** error) is returned and *ppExpr is set to 0.
115918 ** If parameter n is a negative number, then z is assumed to point to a
115919 ** nul-terminated string and the length is determined using strlen().
115921 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
115922 ** use to normalize query tokens while parsing the expression. The azCol[]
115923 ** array, which is assumed to contain nCol entries, should contain the names
115924 ** of each column in the target fts3 table, in order from left to right.
115925 ** Column names must be nul-terminated strings.
115927 ** The iDefaultCol parameter should be passed the index of the table column
115928 ** that appears on the left-hand-side of the MATCH operator (the default
115929 ** column to match against for tokens for which a column name is not explicitly
115930 ** specified as part of the query string), or -1 if tokens may by default
115931 ** match any table column.
115933 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
115934 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
115935 char **azCol, /* Array of column names for fts3 table */
115936 int nCol, /* Number of entries in azCol[] */
115937 int iDefaultCol, /* Default column to query */
115938 const char *z, int n, /* Text of MATCH query */
115939 Fts3Expr **ppExpr /* OUT: Parsed query structure */
115941 int nParsed;
115942 int rc;
115943 ParseContext sParse;
115944 sParse.pTokenizer = pTokenizer;
115945 sParse.azCol = (const char **)azCol;
115946 sParse.nCol = nCol;
115947 sParse.iDefaultCol = iDefaultCol;
115948 sParse.nNest = 0;
115949 if( z==0 ){
115950 *ppExpr = 0;
115951 return SQLITE_OK;
115953 if( n<0 ){
115954 n = (int)strlen(z);
115956 rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
115958 /* Check for mismatched parenthesis */
115959 if( rc==SQLITE_OK && sParse.nNest ){
115960 rc = SQLITE_ERROR;
115961 sqlite3Fts3ExprFree(*ppExpr);
115962 *ppExpr = 0;
115965 return rc;
115969 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
115971 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
115972 if( p ){
115973 sqlite3Fts3ExprFree(p->pLeft);
115974 sqlite3Fts3ExprFree(p->pRight);
115975 sqlite3_free(p->aDoclist);
115976 sqlite3_free(p);
115980 /****************************************************************************
115981 *****************************************************************************
115982 ** Everything after this point is just test code.
115985 #ifdef SQLITE_TEST
115989 ** Function to query the hash-table of tokenizers (see README.tokenizers).
115991 static int queryTestTokenizer(
115992 sqlite3 *db,
115993 const char *zName,
115994 const sqlite3_tokenizer_module **pp
115996 int rc;
115997 sqlite3_stmt *pStmt;
115998 const char zSql[] = "SELECT fts3_tokenizer(?)";
116000 *pp = 0;
116001 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
116002 if( rc!=SQLITE_OK ){
116003 return rc;
116006 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
116007 if( SQLITE_ROW==sqlite3_step(pStmt) ){
116008 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
116009 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
116013 return sqlite3_finalize(pStmt);
116017 ** Return a pointer to a buffer containing a text representation of the
116018 ** expression passed as the first argument. The buffer is obtained from
116019 ** sqlite3_malloc(). It is the responsibility of the caller to use
116020 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
116021 ** NULL is returned.
116023 ** If the second argument is not NULL, then its contents are prepended to
116024 ** the returned expression text and then freed using sqlite3_free().
116026 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
116027 switch( pExpr->eType ){
116028 case FTSQUERY_PHRASE: {
116029 Fts3Phrase *pPhrase = pExpr->pPhrase;
116030 int i;
116031 zBuf = sqlite3_mprintf(
116032 "%zPHRASE %d %d", zBuf, pPhrase->iColumn, pPhrase->isNot);
116033 for(i=0; zBuf && i<pPhrase->nToken; i++){
116034 zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
116035 pPhrase->aToken[i].n, pPhrase->aToken[i].z,
116036 (pPhrase->aToken[i].isPrefix?"+":"")
116039 return zBuf;
116042 case FTSQUERY_NEAR:
116043 zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
116044 break;
116045 case FTSQUERY_NOT:
116046 zBuf = sqlite3_mprintf("%zNOT ", zBuf);
116047 break;
116048 case FTSQUERY_AND:
116049 zBuf = sqlite3_mprintf("%zAND ", zBuf);
116050 break;
116051 case FTSQUERY_OR:
116052 zBuf = sqlite3_mprintf("%zOR ", zBuf);
116053 break;
116056 if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
116057 if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
116058 if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
116060 if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
116061 if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
116063 return zBuf;
116067 ** This is the implementation of a scalar SQL function used to test the
116068 ** expression parser. It should be called as follows:
116070 ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
116072 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
116073 ** to parse the query expression (see README.tokenizers). The second argument
116074 ** is the query expression to parse. Each subsequent argument is the name
116075 ** of a column of the fts3 table that the query expression may refer to.
116076 ** For example:
116078 ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
116080 static void fts3ExprTest(
116081 sqlite3_context *context,
116082 int argc,
116083 sqlite3_value **argv
116085 sqlite3_tokenizer_module const *pModule = 0;
116086 sqlite3_tokenizer *pTokenizer = 0;
116087 int rc;
116088 char **azCol = 0;
116089 const char *zExpr;
116090 int nExpr;
116091 int nCol;
116092 int ii;
116093 Fts3Expr *pExpr;
116094 char *zBuf = 0;
116095 sqlite3 *db = sqlite3_context_db_handle(context);
116097 if( argc<3 ){
116098 sqlite3_result_error(context,
116099 "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
116101 return;
116104 rc = queryTestTokenizer(db,
116105 (const char *)sqlite3_value_text(argv[0]), &pModule);
116106 if( rc==SQLITE_NOMEM ){
116107 sqlite3_result_error_nomem(context);
116108 goto exprtest_out;
116109 }else if( !pModule ){
116110 sqlite3_result_error(context, "No such tokenizer module", -1);
116111 goto exprtest_out;
116114 rc = pModule->xCreate(0, 0, &pTokenizer);
116115 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
116116 if( rc==SQLITE_NOMEM ){
116117 sqlite3_result_error_nomem(context);
116118 goto exprtest_out;
116120 pTokenizer->pModule = pModule;
116122 zExpr = (const char *)sqlite3_value_text(argv[1]);
116123 nExpr = sqlite3_value_bytes(argv[1]);
116124 nCol = argc-2;
116125 azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
116126 if( !azCol ){
116127 sqlite3_result_error_nomem(context);
116128 goto exprtest_out;
116130 for(ii=0; ii<nCol; ii++){
116131 azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
116134 rc = sqlite3Fts3ExprParse(
116135 pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
116137 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
116138 sqlite3_result_error(context, "Error parsing expression", -1);
116139 }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
116140 sqlite3_result_error_nomem(context);
116141 }else{
116142 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
116143 sqlite3_free(zBuf);
116146 sqlite3Fts3ExprFree(pExpr);
116148 exprtest_out:
116149 if( pModule && pTokenizer ){
116150 rc = pModule->xDestroy(pTokenizer);
116152 sqlite3_free(azCol);
116156 ** Register the query expression parser test function fts3_exprtest()
116157 ** with database connection db.
116159 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
116160 return sqlite3_create_function(
116161 db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
116165 #endif
116166 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
116168 /************** End of fts3_expr.c *******************************************/
116169 /************** Begin file fts3_hash.c ***************************************/
116171 ** 2001 September 22
116173 ** The author disclaims copyright to this source code. In place of
116174 ** a legal notice, here is a blessing:
116176 ** May you do good and not evil.
116177 ** May you find forgiveness for yourself and forgive others.
116178 ** May you share freely, never taking more than you give.
116180 *************************************************************************
116181 ** This is the implementation of generic hash-tables used in SQLite.
116182 ** We've modified it slightly to serve as a standalone hash table
116183 ** implementation for the full-text indexing module.
116187 ** The code in this file is only compiled if:
116189 ** * The FTS3 module is being built as an extension
116190 ** (in which case SQLITE_CORE is not defined), or
116192 ** * The FTS3 module is being built into the core of
116193 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
116195 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116200 ** Malloc and Free functions
116202 static void *fts3HashMalloc(int n){
116203 void *p = sqlite3_malloc(n);
116204 if( p ){
116205 memset(p, 0, n);
116207 return p;
116209 static void fts3HashFree(void *p){
116210 sqlite3_free(p);
116213 /* Turn bulk memory into a hash table object by initializing the
116214 ** fields of the Hash structure.
116216 ** "pNew" is a pointer to the hash table that is to be initialized.
116217 ** keyClass is one of the constants
116218 ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
116219 ** determines what kind of key the hash table will use. "copyKey" is
116220 ** true if the hash table should make its own private copy of keys and
116221 ** false if it should just use the supplied pointer.
116223 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
116224 assert( pNew!=0 );
116225 assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
116226 pNew->keyClass = keyClass;
116227 pNew->copyKey = copyKey;
116228 pNew->first = 0;
116229 pNew->count = 0;
116230 pNew->htsize = 0;
116231 pNew->ht = 0;
116234 /* Remove all entries from a hash table. Reclaim all memory.
116235 ** Call this routine to delete a hash table or to reset a hash table
116236 ** to the empty state.
116238 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
116239 Fts3HashElem *elem; /* For looping over all elements of the table */
116241 assert( pH!=0 );
116242 elem = pH->first;
116243 pH->first = 0;
116244 fts3HashFree(pH->ht);
116245 pH->ht = 0;
116246 pH->htsize = 0;
116247 while( elem ){
116248 Fts3HashElem *next_elem = elem->next;
116249 if( pH->copyKey && elem->pKey ){
116250 fts3HashFree(elem->pKey);
116252 fts3HashFree(elem);
116253 elem = next_elem;
116255 pH->count = 0;
116259 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
116261 static int fts3StrHash(const void *pKey, int nKey){
116262 const char *z = (const char *)pKey;
116263 int h = 0;
116264 if( nKey<=0 ) nKey = (int) strlen(z);
116265 while( nKey > 0 ){
116266 h = (h<<3) ^ h ^ *z++;
116267 nKey--;
116269 return h & 0x7fffffff;
116271 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
116272 if( n1!=n2 ) return 1;
116273 return strncmp((const char*)pKey1,(const char*)pKey2,n1);
116277 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
116279 static int fts3BinHash(const void *pKey, int nKey){
116280 int h = 0;
116281 const char *z = (const char *)pKey;
116282 while( nKey-- > 0 ){
116283 h = (h<<3) ^ h ^ *(z++);
116285 return h & 0x7fffffff;
116287 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
116288 if( n1!=n2 ) return 1;
116289 return memcmp(pKey1,pKey2,n1);
116293 ** Return a pointer to the appropriate hash function given the key class.
116295 ** The C syntax in this function definition may be unfamilar to some
116296 ** programmers, so we provide the following additional explanation:
116298 ** The name of the function is "ftsHashFunction". The function takes a
116299 ** single parameter "keyClass". The return value of ftsHashFunction()
116300 ** is a pointer to another function. Specifically, the return value
116301 ** of ftsHashFunction() is a pointer to a function that takes two parameters
116302 ** with types "const void*" and "int" and returns an "int".
116304 static int (*ftsHashFunction(int keyClass))(const void*,int){
116305 if( keyClass==FTS3_HASH_STRING ){
116306 return &fts3StrHash;
116307 }else{
116308 assert( keyClass==FTS3_HASH_BINARY );
116309 return &fts3BinHash;
116314 ** Return a pointer to the appropriate hash function given the key class.
116316 ** For help in interpreted the obscure C code in the function definition,
116317 ** see the header comment on the previous function.
116319 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
116320 if( keyClass==FTS3_HASH_STRING ){
116321 return &fts3StrCompare;
116322 }else{
116323 assert( keyClass==FTS3_HASH_BINARY );
116324 return &fts3BinCompare;
116328 /* Link an element into the hash table
116330 static void fts3HashInsertElement(
116331 Fts3Hash *pH, /* The complete hash table */
116332 struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
116333 Fts3HashElem *pNew /* The element to be inserted */
116335 Fts3HashElem *pHead; /* First element already in pEntry */
116336 pHead = pEntry->chain;
116337 if( pHead ){
116338 pNew->next = pHead;
116339 pNew->prev = pHead->prev;
116340 if( pHead->prev ){ pHead->prev->next = pNew; }
116341 else { pH->first = pNew; }
116342 pHead->prev = pNew;
116343 }else{
116344 pNew->next = pH->first;
116345 if( pH->first ){ pH->first->prev = pNew; }
116346 pNew->prev = 0;
116347 pH->first = pNew;
116349 pEntry->count++;
116350 pEntry->chain = pNew;
116354 /* Resize the hash table so that it cantains "new_size" buckets.
116355 ** "new_size" must be a power of 2. The hash table might fail
116356 ** to resize if sqliteMalloc() fails.
116358 ** Return non-zero if a memory allocation error occurs.
116360 static int fts3Rehash(Fts3Hash *pH, int new_size){
116361 struct _fts3ht *new_ht; /* The new hash table */
116362 Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
116363 int (*xHash)(const void*,int); /* The hash function */
116365 assert( (new_size & (new_size-1))==0 );
116366 new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
116367 if( new_ht==0 ) return 1;
116368 fts3HashFree(pH->ht);
116369 pH->ht = new_ht;
116370 pH->htsize = new_size;
116371 xHash = ftsHashFunction(pH->keyClass);
116372 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
116373 int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
116374 next_elem = elem->next;
116375 fts3HashInsertElement(pH, &new_ht[h], elem);
116377 return 0;
116380 /* This function (for internal use only) locates an element in an
116381 ** hash table that matches the given key. The hash for this key has
116382 ** already been computed and is passed as the 4th parameter.
116384 static Fts3HashElem *fts3FindElementByHash(
116385 const Fts3Hash *pH, /* The pH to be searched */
116386 const void *pKey, /* The key we are searching for */
116387 int nKey,
116388 int h /* The hash for this key. */
116390 Fts3HashElem *elem; /* Used to loop thru the element list */
116391 int count; /* Number of elements left to test */
116392 int (*xCompare)(const void*,int,const void*,int); /* comparison function */
116394 if( pH->ht ){
116395 struct _fts3ht *pEntry = &pH->ht[h];
116396 elem = pEntry->chain;
116397 count = pEntry->count;
116398 xCompare = ftsCompareFunction(pH->keyClass);
116399 while( count-- && elem ){
116400 if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
116401 return elem;
116403 elem = elem->next;
116406 return 0;
116409 /* Remove a single entry from the hash table given a pointer to that
116410 ** element and a hash on the element's key.
116412 static void fts3RemoveElementByHash(
116413 Fts3Hash *pH, /* The pH containing "elem" */
116414 Fts3HashElem* elem, /* The element to be removed from the pH */
116415 int h /* Hash value for the element */
116417 struct _fts3ht *pEntry;
116418 if( elem->prev ){
116419 elem->prev->next = elem->next;
116420 }else{
116421 pH->first = elem->next;
116423 if( elem->next ){
116424 elem->next->prev = elem->prev;
116426 pEntry = &pH->ht[h];
116427 if( pEntry->chain==elem ){
116428 pEntry->chain = elem->next;
116430 pEntry->count--;
116431 if( pEntry->count<=0 ){
116432 pEntry->chain = 0;
116434 if( pH->copyKey && elem->pKey ){
116435 fts3HashFree(elem->pKey);
116437 fts3HashFree( elem );
116438 pH->count--;
116439 if( pH->count<=0 ){
116440 assert( pH->first==0 );
116441 assert( pH->count==0 );
116442 fts3HashClear(pH);
116446 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
116447 const Fts3Hash *pH,
116448 const void *pKey,
116449 int nKey
116451 int h; /* A hash on key */
116452 int (*xHash)(const void*,int); /* The hash function */
116454 if( pH==0 || pH->ht==0 ) return 0;
116455 xHash = ftsHashFunction(pH->keyClass);
116456 assert( xHash!=0 );
116457 h = (*xHash)(pKey,nKey);
116458 assert( (pH->htsize & (pH->htsize-1))==0 );
116459 return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
116463 ** Attempt to locate an element of the hash table pH with a key
116464 ** that matches pKey,nKey. Return the data for this element if it is
116465 ** found, or NULL if there is no match.
116467 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
116468 Fts3HashElem *pElem; /* The element that matches key (if any) */
116470 pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
116471 return pElem ? pElem->data : 0;
116474 /* Insert an element into the hash table pH. The key is pKey,nKey
116475 ** and the data is "data".
116477 ** If no element exists with a matching key, then a new
116478 ** element is created. A copy of the key is made if the copyKey
116479 ** flag is set. NULL is returned.
116481 ** If another element already exists with the same key, then the
116482 ** new data replaces the old data and the old data is returned.
116483 ** The key is not copied in this instance. If a malloc fails, then
116484 ** the new data is returned and the hash table is unchanged.
116486 ** If the "data" parameter to this function is NULL, then the
116487 ** element corresponding to "key" is removed from the hash table.
116489 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
116490 Fts3Hash *pH, /* The hash table to insert into */
116491 const void *pKey, /* The key */
116492 int nKey, /* Number of bytes in the key */
116493 void *data /* The data */
116495 int hraw; /* Raw hash value of the key */
116496 int h; /* the hash of the key modulo hash table size */
116497 Fts3HashElem *elem; /* Used to loop thru the element list */
116498 Fts3HashElem *new_elem; /* New element added to the pH */
116499 int (*xHash)(const void*,int); /* The hash function */
116501 assert( pH!=0 );
116502 xHash = ftsHashFunction(pH->keyClass);
116503 assert( xHash!=0 );
116504 hraw = (*xHash)(pKey, nKey);
116505 assert( (pH->htsize & (pH->htsize-1))==0 );
116506 h = hraw & (pH->htsize-1);
116507 elem = fts3FindElementByHash(pH,pKey,nKey,h);
116508 if( elem ){
116509 void *old_data = elem->data;
116510 if( data==0 ){
116511 fts3RemoveElementByHash(pH,elem,h);
116512 }else{
116513 elem->data = data;
116515 return old_data;
116517 if( data==0 ) return 0;
116518 if( (pH->htsize==0 && fts3Rehash(pH,8))
116519 || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
116521 pH->count = 0;
116522 return data;
116524 assert( pH->htsize>0 );
116525 new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
116526 if( new_elem==0 ) return data;
116527 if( pH->copyKey && pKey!=0 ){
116528 new_elem->pKey = fts3HashMalloc( nKey );
116529 if( new_elem->pKey==0 ){
116530 fts3HashFree(new_elem);
116531 return data;
116533 memcpy((void*)new_elem->pKey, pKey, nKey);
116534 }else{
116535 new_elem->pKey = (void*)pKey;
116537 new_elem->nKey = nKey;
116538 pH->count++;
116539 assert( pH->htsize>0 );
116540 assert( (pH->htsize & (pH->htsize-1))==0 );
116541 h = hraw & (pH->htsize-1);
116542 fts3HashInsertElement(pH, &pH->ht[h], new_elem);
116543 new_elem->data = data;
116544 return 0;
116547 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
116549 /************** End of fts3_hash.c *******************************************/
116550 /************** Begin file fts3_porter.c *************************************/
116552 ** 2006 September 30
116554 ** The author disclaims copyright to this source code. In place of
116555 ** a legal notice, here is a blessing:
116557 ** May you do good and not evil.
116558 ** May you find forgiveness for yourself and forgive others.
116559 ** May you share freely, never taking more than you give.
116561 *************************************************************************
116562 ** Implementation of the full-text-search tokenizer that implements
116563 ** a Porter stemmer.
116567 ** The code in this file is only compiled if:
116569 ** * The FTS3 module is being built as an extension
116570 ** (in which case SQLITE_CORE is not defined), or
116572 ** * The FTS3 module is being built into the core of
116573 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
116575 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116581 ** Class derived from sqlite3_tokenizer
116583 typedef struct porter_tokenizer {
116584 sqlite3_tokenizer base; /* Base class */
116585 } porter_tokenizer;
116588 ** Class derived from sqlit3_tokenizer_cursor
116590 typedef struct porter_tokenizer_cursor {
116591 sqlite3_tokenizer_cursor base;
116592 const char *zInput; /* input we are tokenizing */
116593 int nInput; /* size of the input */
116594 int iOffset; /* current position in zInput */
116595 int iToken; /* index of next token to be returned */
116596 char *zToken; /* storage for current token */
116597 int nAllocated; /* space allocated to zToken buffer */
116598 } porter_tokenizer_cursor;
116602 ** Create a new tokenizer instance.
116604 static int porterCreate(
116605 int argc, const char * const *argv,
116606 sqlite3_tokenizer **ppTokenizer
116608 porter_tokenizer *t;
116610 UNUSED_PARAMETER(argc);
116611 UNUSED_PARAMETER(argv);
116613 t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
116614 if( t==NULL ) return SQLITE_NOMEM;
116615 memset(t, 0, sizeof(*t));
116616 *ppTokenizer = &t->base;
116617 return SQLITE_OK;
116621 ** Destroy a tokenizer
116623 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
116624 sqlite3_free(pTokenizer);
116625 return SQLITE_OK;
116629 ** Prepare to begin tokenizing a particular string. The input
116630 ** string to be tokenized is zInput[0..nInput-1]. A cursor
116631 ** used to incrementally tokenize this string is returned in
116632 ** *ppCursor.
116634 static int porterOpen(
116635 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
116636 const char *zInput, int nInput, /* String to be tokenized */
116637 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
116639 porter_tokenizer_cursor *c;
116641 UNUSED_PARAMETER(pTokenizer);
116643 c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
116644 if( c==NULL ) return SQLITE_NOMEM;
116646 c->zInput = zInput;
116647 if( zInput==0 ){
116648 c->nInput = 0;
116649 }else if( nInput<0 ){
116650 c->nInput = (int)strlen(zInput);
116651 }else{
116652 c->nInput = nInput;
116654 c->iOffset = 0; /* start tokenizing at the beginning */
116655 c->iToken = 0;
116656 c->zToken = NULL; /* no space allocated, yet. */
116657 c->nAllocated = 0;
116659 *ppCursor = &c->base;
116660 return SQLITE_OK;
116664 ** Close a tokenization cursor previously opened by a call to
116665 ** porterOpen() above.
116667 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
116668 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
116669 sqlite3_free(c->zToken);
116670 sqlite3_free(c);
116671 return SQLITE_OK;
116674 ** Vowel or consonant
116676 static const char vOrCType[] = {
116677 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
116678 1, 1, 1, 2, 1
116682 ** isConsonant() and isVowel() determine if their first character in
116683 ** the string they point to is a consonant or a vowel, according
116684 ** to Porter ruls.
116686 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
116687 ** 'Y' is a consonant unless it follows another consonant,
116688 ** in which case it is a vowel.
116690 ** In these routine, the letters are in reverse order. So the 'y' rule
116691 ** is that 'y' is a consonant unless it is followed by another
116692 ** consonent.
116694 static int isVowel(const char*);
116695 static int isConsonant(const char *z){
116696 int j;
116697 char x = *z;
116698 if( x==0 ) return 0;
116699 assert( x>='a' && x<='z' );
116700 j = vOrCType[x-'a'];
116701 if( j<2 ) return j;
116702 return z[1]==0 || isVowel(z + 1);
116704 static int isVowel(const char *z){
116705 int j;
116706 char x = *z;
116707 if( x==0 ) return 0;
116708 assert( x>='a' && x<='z' );
116709 j = vOrCType[x-'a'];
116710 if( j<2 ) return 1-j;
116711 return isConsonant(z + 1);
116715 ** Let any sequence of one or more vowels be represented by V and let
116716 ** C be sequence of one or more consonants. Then every word can be
116717 ** represented as:
116719 ** [C] (VC){m} [V]
116721 ** In prose: A word is an optional consonant followed by zero or
116722 ** vowel-consonant pairs followed by an optional vowel. "m" is the
116723 ** number of vowel consonant pairs. This routine computes the value
116724 ** of m for the first i bytes of a word.
116726 ** Return true if the m-value for z is 1 or more. In other words,
116727 ** return true if z contains at least one vowel that is followed
116728 ** by a consonant.
116730 ** In this routine z[] is in reverse order. So we are really looking
116731 ** for an instance of of a consonant followed by a vowel.
116733 static int m_gt_0(const char *z){
116734 while( isVowel(z) ){ z++; }
116735 if( *z==0 ) return 0;
116736 while( isConsonant(z) ){ z++; }
116737 return *z!=0;
116740 /* Like mgt0 above except we are looking for a value of m which is
116741 ** exactly 1
116743 static int m_eq_1(const char *z){
116744 while( isVowel(z) ){ z++; }
116745 if( *z==0 ) return 0;
116746 while( isConsonant(z) ){ z++; }
116747 if( *z==0 ) return 0;
116748 while( isVowel(z) ){ z++; }
116749 if( *z==0 ) return 1;
116750 while( isConsonant(z) ){ z++; }
116751 return *z==0;
116754 /* Like mgt0 above except we are looking for a value of m>1 instead
116755 ** or m>0
116757 static int m_gt_1(const char *z){
116758 while( isVowel(z) ){ z++; }
116759 if( *z==0 ) return 0;
116760 while( isConsonant(z) ){ z++; }
116761 if( *z==0 ) return 0;
116762 while( isVowel(z) ){ z++; }
116763 if( *z==0 ) return 0;
116764 while( isConsonant(z) ){ z++; }
116765 return *z!=0;
116769 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
116771 static int hasVowel(const char *z){
116772 while( isConsonant(z) ){ z++; }
116773 return *z!=0;
116777 ** Return TRUE if the word ends in a double consonant.
116779 ** The text is reversed here. So we are really looking at
116780 ** the first two characters of z[].
116782 static int doubleConsonant(const char *z){
116783 return isConsonant(z) && z[0]==z[1];
116787 ** Return TRUE if the word ends with three letters which
116788 ** are consonant-vowel-consonent and where the final consonant
116789 ** is not 'w', 'x', or 'y'.
116791 ** The word is reversed here. So we are really checking the
116792 ** first three letters and the first one cannot be in [wxy].
116794 static int star_oh(const char *z){
116795 return
116796 isConsonant(z) &&
116797 z[0]!='w' && z[0]!='x' && z[0]!='y' &&
116798 isVowel(z+1) &&
116799 isConsonant(z+2);
116803 ** If the word ends with zFrom and xCond() is true for the stem
116804 ** of the word that preceeds the zFrom ending, then change the
116805 ** ending to zTo.
116807 ** The input word *pz and zFrom are both in reverse order. zTo
116808 ** is in normal order.
116810 ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
116811 ** match. Not that TRUE is returned even if xCond() fails and
116812 ** no substitution occurs.
116814 static int stem(
116815 char **pz, /* The word being stemmed (Reversed) */
116816 const char *zFrom, /* If the ending matches this... (Reversed) */
116817 const char *zTo, /* ... change the ending to this (not reversed) */
116818 int (*xCond)(const char*) /* Condition that must be true */
116820 char *z = *pz;
116821 while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
116822 if( *zFrom!=0 ) return 0;
116823 if( xCond && !xCond(z) ) return 1;
116824 while( *zTo ){
116825 *(--z) = *(zTo++);
116827 *pz = z;
116828 return 1;
116832 ** This is the fallback stemmer used when the porter stemmer is
116833 ** inappropriate. The input word is copied into the output with
116834 ** US-ASCII case folding. If the input word is too long (more
116835 ** than 20 bytes if it contains no digits or more than 6 bytes if
116836 ** it contains digits) then word is truncated to 20 or 6 bytes
116837 ** by taking 10 or 3 bytes from the beginning and end.
116839 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
116840 int i, mx, j;
116841 int hasDigit = 0;
116842 for(i=0; i<nIn; i++){
116843 char c = zIn[i];
116844 if( c>='A' && c<='Z' ){
116845 zOut[i] = c - 'A' + 'a';
116846 }else{
116847 if( c>='0' && c<='9' ) hasDigit = 1;
116848 zOut[i] = c;
116851 mx = hasDigit ? 3 : 10;
116852 if( nIn>mx*2 ){
116853 for(j=mx, i=nIn-mx; i<nIn; i++, j++){
116854 zOut[j] = zOut[i];
116856 i = j;
116858 zOut[i] = 0;
116859 *pnOut = i;
116864 ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
116865 ** zOut is at least big enough to hold nIn bytes. Write the actual
116866 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
116868 ** Any upper-case characters in the US-ASCII character set ([A-Z])
116869 ** are converted to lower case. Upper-case UTF characters are
116870 ** unchanged.
116872 ** Words that are longer than about 20 bytes are stemmed by retaining
116873 ** a few bytes from the beginning and the end of the word. If the
116874 ** word contains digits, 3 bytes are taken from the beginning and
116875 ** 3 bytes from the end. For long words without digits, 10 bytes
116876 ** are taken from each end. US-ASCII case folding still applies.
116878 ** If the input word contains not digits but does characters not
116879 ** in [a-zA-Z] then no stemming is attempted and this routine just
116880 ** copies the input into the input into the output with US-ASCII
116881 ** case folding.
116883 ** Stemming never increases the length of the word. So there is
116884 ** no chance of overflowing the zOut buffer.
116886 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
116887 int i, j;
116888 char zReverse[28];
116889 char *z, *z2;
116890 if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
116891 /* The word is too big or too small for the porter stemmer.
116892 ** Fallback to the copy stemmer */
116893 copy_stemmer(zIn, nIn, zOut, pnOut);
116894 return;
116896 for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
116897 char c = zIn[i];
116898 if( c>='A' && c<='Z' ){
116899 zReverse[j] = c + 'a' - 'A';
116900 }else if( c>='a' && c<='z' ){
116901 zReverse[j] = c;
116902 }else{
116903 /* The use of a character not in [a-zA-Z] means that we fallback
116904 ** to the copy stemmer */
116905 copy_stemmer(zIn, nIn, zOut, pnOut);
116906 return;
116909 memset(&zReverse[sizeof(zReverse)-5], 0, 5);
116910 z = &zReverse[j+1];
116913 /* Step 1a */
116914 if( z[0]=='s' ){
116916 !stem(&z, "sess", "ss", 0) &&
116917 !stem(&z, "sei", "i", 0) &&
116918 !stem(&z, "ss", "ss", 0)
116924 /* Step 1b */
116925 z2 = z;
116926 if( stem(&z, "dee", "ee", m_gt_0) ){
116927 /* Do nothing. The work was all in the test */
116928 }else if(
116929 (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
116930 && z!=z2
116932 if( stem(&z, "ta", "ate", 0) ||
116933 stem(&z, "lb", "ble", 0) ||
116934 stem(&z, "zi", "ize", 0) ){
116935 /* Do nothing. The work was all in the test */
116936 }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
116938 }else if( m_eq_1(z) && star_oh(z) ){
116939 *(--z) = 'e';
116943 /* Step 1c */
116944 if( z[0]=='y' && hasVowel(z+1) ){
116945 z[0] = 'i';
116948 /* Step 2 */
116949 switch( z[1] ){
116950 case 'a':
116951 stem(&z, "lanoita", "ate", m_gt_0) ||
116952 stem(&z, "lanoit", "tion", m_gt_0);
116953 break;
116954 case 'c':
116955 stem(&z, "icne", "ence", m_gt_0) ||
116956 stem(&z, "icna", "ance", m_gt_0);
116957 break;
116958 case 'e':
116959 stem(&z, "rezi", "ize", m_gt_0);
116960 break;
116961 case 'g':
116962 stem(&z, "igol", "log", m_gt_0);
116963 break;
116964 case 'l':
116965 stem(&z, "ilb", "ble", m_gt_0) ||
116966 stem(&z, "illa", "al", m_gt_0) ||
116967 stem(&z, "iltne", "ent", m_gt_0) ||
116968 stem(&z, "ile", "e", m_gt_0) ||
116969 stem(&z, "ilsuo", "ous", m_gt_0);
116970 break;
116971 case 'o':
116972 stem(&z, "noitazi", "ize", m_gt_0) ||
116973 stem(&z, "noita", "ate", m_gt_0) ||
116974 stem(&z, "rota", "ate", m_gt_0);
116975 break;
116976 case 's':
116977 stem(&z, "msila", "al", m_gt_0) ||
116978 stem(&z, "ssenevi", "ive", m_gt_0) ||
116979 stem(&z, "ssenluf", "ful", m_gt_0) ||
116980 stem(&z, "ssensuo", "ous", m_gt_0);
116981 break;
116982 case 't':
116983 stem(&z, "itila", "al", m_gt_0) ||
116984 stem(&z, "itivi", "ive", m_gt_0) ||
116985 stem(&z, "itilib", "ble", m_gt_0);
116986 break;
116989 /* Step 3 */
116990 switch( z[0] ){
116991 case 'e':
116992 stem(&z, "etaci", "ic", m_gt_0) ||
116993 stem(&z, "evita", "", m_gt_0) ||
116994 stem(&z, "ezila", "al", m_gt_0);
116995 break;
116996 case 'i':
116997 stem(&z, "itici", "ic", m_gt_0);
116998 break;
116999 case 'l':
117000 stem(&z, "laci", "ic", m_gt_0) ||
117001 stem(&z, "luf", "", m_gt_0);
117002 break;
117003 case 's':
117004 stem(&z, "ssen", "", m_gt_0);
117005 break;
117008 /* Step 4 */
117009 switch( z[1] ){
117010 case 'a':
117011 if( z[0]=='l' && m_gt_1(z+2) ){
117012 z += 2;
117014 break;
117015 case 'c':
117016 if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
117017 z += 4;
117019 break;
117020 case 'e':
117021 if( z[0]=='r' && m_gt_1(z+2) ){
117022 z += 2;
117024 break;
117025 case 'i':
117026 if( z[0]=='c' && m_gt_1(z+2) ){
117027 z += 2;
117029 break;
117030 case 'l':
117031 if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
117032 z += 4;
117034 break;
117035 case 'n':
117036 if( z[0]=='t' ){
117037 if( z[2]=='a' ){
117038 if( m_gt_1(z+3) ){
117039 z += 3;
117041 }else if( z[2]=='e' ){
117042 stem(&z, "tneme", "", m_gt_1) ||
117043 stem(&z, "tnem", "", m_gt_1) ||
117044 stem(&z, "tne", "", m_gt_1);
117047 break;
117048 case 'o':
117049 if( z[0]=='u' ){
117050 if( m_gt_1(z+2) ){
117051 z += 2;
117053 }else if( z[3]=='s' || z[3]=='t' ){
117054 stem(&z, "noi", "", m_gt_1);
117056 break;
117057 case 's':
117058 if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
117059 z += 3;
117061 break;
117062 case 't':
117063 stem(&z, "eta", "", m_gt_1) ||
117064 stem(&z, "iti", "", m_gt_1);
117065 break;
117066 case 'u':
117067 if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
117068 z += 3;
117070 break;
117071 case 'v':
117072 case 'z':
117073 if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
117074 z += 3;
117076 break;
117079 /* Step 5a */
117080 if( z[0]=='e' ){
117081 if( m_gt_1(z+1) ){
117083 }else if( m_eq_1(z+1) && !star_oh(z+1) ){
117088 /* Step 5b */
117089 if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
117093 /* z[] is now the stemmed word in reverse order. Flip it back
117094 ** around into forward order and return.
117096 *pnOut = i = (int)strlen(z);
117097 zOut[i] = 0;
117098 while( *z ){
117099 zOut[--i] = *(z++);
117104 ** Characters that can be part of a token. We assume any character
117105 ** whose value is greater than 0x80 (any UTF character) can be
117106 ** part of a token. In other words, delimiters all must have
117107 ** values of 0x7f or lower.
117109 static const char porterIdChar[] = {
117110 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
117111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
117112 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
117113 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
117114 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
117115 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
117117 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
117120 ** Extract the next token from a tokenization cursor. The cursor must
117121 ** have been opened by a prior call to porterOpen().
117123 static int porterNext(
117124 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
117125 const char **pzToken, /* OUT: *pzToken is the token text */
117126 int *pnBytes, /* OUT: Number of bytes in token */
117127 int *piStartOffset, /* OUT: Starting offset of token */
117128 int *piEndOffset, /* OUT: Ending offset of token */
117129 int *piPosition /* OUT: Position integer of token */
117131 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
117132 const char *z = c->zInput;
117134 while( c->iOffset<c->nInput ){
117135 int iStartOffset, ch;
117137 /* Scan past delimiter characters */
117138 while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
117139 c->iOffset++;
117142 /* Count non-delimiter characters. */
117143 iStartOffset = c->iOffset;
117144 while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
117145 c->iOffset++;
117148 if( c->iOffset>iStartOffset ){
117149 int n = c->iOffset-iStartOffset;
117150 if( n>c->nAllocated ){
117151 char *pNew;
117152 c->nAllocated = n+20;
117153 pNew = sqlite3_realloc(c->zToken, c->nAllocated);
117154 if( !pNew ) return SQLITE_NOMEM;
117155 c->zToken = pNew;
117157 porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
117158 *pzToken = c->zToken;
117159 *piStartOffset = iStartOffset;
117160 *piEndOffset = c->iOffset;
117161 *piPosition = c->iToken++;
117162 return SQLITE_OK;
117165 return SQLITE_DONE;
117169 ** The set of routines that implement the porter-stemmer tokenizer
117171 static const sqlite3_tokenizer_module porterTokenizerModule = {
117173 porterCreate,
117174 porterDestroy,
117175 porterOpen,
117176 porterClose,
117177 porterNext,
117181 ** Allocate a new porter tokenizer. Return a pointer to the new
117182 ** tokenizer in *ppModule
117184 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
117185 sqlite3_tokenizer_module const**ppModule
117187 *ppModule = &porterTokenizerModule;
117190 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
117192 /************** End of fts3_porter.c *****************************************/
117193 /************** Begin file fts3_tokenizer.c **********************************/
117195 ** 2007 June 22
117197 ** The author disclaims copyright to this source code. In place of
117198 ** a legal notice, here is a blessing:
117200 ** May you do good and not evil.
117201 ** May you find forgiveness for yourself and forgive others.
117202 ** May you share freely, never taking more than you give.
117204 ******************************************************************************
117206 ** This is part of an SQLite module implementing full-text search.
117207 ** This particular file implements the generic tokenizer interface.
117211 ** The code in this file is only compiled if:
117213 ** * The FTS3 module is being built as an extension
117214 ** (in which case SQLITE_CORE is not defined), or
117216 ** * The FTS3 module is being built into the core of
117217 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
117219 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117221 #ifndef SQLITE_CORE
117222 SQLITE_EXTENSION_INIT1
117223 #endif
117227 ** Implementation of the SQL scalar function for accessing the underlying
117228 ** hash table. This function may be called as follows:
117230 ** SELECT <function-name>(<key-name>);
117231 ** SELECT <function-name>(<key-name>, <pointer>);
117233 ** where <function-name> is the name passed as the second argument
117234 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
117236 ** If the <pointer> argument is specified, it must be a blob value
117237 ** containing a pointer to be stored as the hash data corresponding
117238 ** to the string <key-name>. If <pointer> is not specified, then
117239 ** the string <key-name> must already exist in the has table. Otherwise,
117240 ** an error is returned.
117242 ** Whether or not the <pointer> argument is specified, the value returned
117243 ** is a blob containing the pointer stored as the hash data corresponding
117244 ** to string <key-name> (after the hash-table is updated, if applicable).
117246 static void scalarFunc(
117247 sqlite3_context *context,
117248 int argc,
117249 sqlite3_value **argv
117251 Fts3Hash *pHash;
117252 void *pPtr = 0;
117253 const unsigned char *zName;
117254 int nName;
117256 assert( argc==1 || argc==2 );
117258 pHash = (Fts3Hash *)sqlite3_user_data(context);
117260 zName = sqlite3_value_text(argv[0]);
117261 nName = sqlite3_value_bytes(argv[0])+1;
117263 if( argc==2 ){
117264 void *pOld;
117265 int n = sqlite3_value_bytes(argv[1]);
117266 if( n!=sizeof(pPtr) ){
117267 sqlite3_result_error(context, "argument type mismatch", -1);
117268 return;
117270 pPtr = *(void **)sqlite3_value_blob(argv[1]);
117271 pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
117272 if( pOld==pPtr ){
117273 sqlite3_result_error(context, "out of memory", -1);
117274 return;
117276 }else{
117277 pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
117278 if( !pPtr ){
117279 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
117280 sqlite3_result_error(context, zErr, -1);
117281 sqlite3_free(zErr);
117282 return;
117286 sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
117289 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
117290 static const char isFtsIdChar[] = {
117291 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
117292 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
117293 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
117294 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
117295 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
117296 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
117297 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
117298 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
117300 return (c&0x80 || isFtsIdChar[(int)(c)]);
117303 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
117304 const char *z1;
117305 const char *z2 = 0;
117307 /* Find the start of the next token. */
117308 z1 = zStr;
117309 while( z2==0 ){
117310 char c = *z1;
117311 switch( c ){
117312 case '\0': return 0; /* No more tokens here */
117313 case '\'':
117314 case '"':
117315 case '`': {
117316 z2 = z1;
117317 while( *++z2 && (*z2!=c || *++z2==c) );
117318 break;
117320 case '[':
117321 z2 = &z1[1];
117322 while( *z2 && z2[0]!=']' ) z2++;
117323 if( *z2 ) z2++;
117324 break;
117326 default:
117327 if( sqlite3Fts3IsIdChar(*z1) ){
117328 z2 = &z1[1];
117329 while( sqlite3Fts3IsIdChar(*z2) ) z2++;
117330 }else{
117331 z1++;
117336 *pn = (int)(z2-z1);
117337 return z1;
117340 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
117341 Fts3Hash *pHash, /* Tokenizer hash table */
117342 const char *zArg, /* Tokenizer name */
117343 sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
117344 char **pzErr /* OUT: Set to malloced error message */
117346 int rc;
117347 char *z = (char *)zArg;
117348 int n;
117349 char *zCopy;
117350 char *zEnd; /* Pointer to nul-term of zCopy */
117351 sqlite3_tokenizer_module *m;
117353 zCopy = sqlite3_mprintf("%s", zArg);
117354 if( !zCopy ) return SQLITE_NOMEM;
117355 zEnd = &zCopy[strlen(zCopy)];
117357 z = (char *)sqlite3Fts3NextToken(zCopy, &n);
117358 z[n] = '\0';
117359 sqlite3Fts3Dequote(z);
117361 m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
117362 if( !m ){
117363 *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
117364 rc = SQLITE_ERROR;
117365 }else{
117366 char const **aArg = 0;
117367 int iArg = 0;
117368 z = &z[n+1];
117369 while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
117370 int nNew = sizeof(char *)*(iArg+1);
117371 char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
117372 if( !aNew ){
117373 sqlite3_free(zCopy);
117374 sqlite3_free((void *)aArg);
117375 return SQLITE_NOMEM;
117377 aArg = aNew;
117378 aArg[iArg++] = z;
117379 z[n] = '\0';
117380 sqlite3Fts3Dequote(z);
117381 z = &z[n+1];
117383 rc = m->xCreate(iArg, aArg, ppTok);
117384 assert( rc!=SQLITE_OK || *ppTok );
117385 if( rc!=SQLITE_OK ){
117386 *pzErr = sqlite3_mprintf("unknown tokenizer");
117387 }else{
117388 (*ppTok)->pModule = m;
117390 sqlite3_free((void *)aArg);
117393 sqlite3_free(zCopy);
117394 return rc;
117398 #ifdef SQLITE_TEST
117402 ** Implementation of a special SQL scalar function for testing tokenizers
117403 ** designed to be used in concert with the Tcl testing framework. This
117404 ** function must be called with two arguments:
117406 ** SELECT <function-name>(<key-name>, <input-string>);
117407 ** SELECT <function-name>(<key-name>, <pointer>);
117409 ** where <function-name> is the name passed as the second argument
117410 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
117411 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
117413 ** The return value is a string that may be interpreted as a Tcl
117414 ** list. For each token in the <input-string>, three elements are
117415 ** added to the returned list. The first is the token position, the
117416 ** second is the token text (folded, stemmed, etc.) and the third is the
117417 ** substring of <input-string> associated with the token. For example,
117418 ** using the built-in "simple" tokenizer:
117420 ** SELECT fts_tokenizer_test('simple', 'I don't see how');
117422 ** will return the string:
117424 ** "{0 i I 1 dont don't 2 see see 3 how how}"
117427 static void testFunc(
117428 sqlite3_context *context,
117429 int argc,
117430 sqlite3_value **argv
117432 Fts3Hash *pHash;
117433 sqlite3_tokenizer_module *p;
117434 sqlite3_tokenizer *pTokenizer = 0;
117435 sqlite3_tokenizer_cursor *pCsr = 0;
117437 const char *zErr = 0;
117439 const char *zName;
117440 int nName;
117441 const char *zInput;
117442 int nInput;
117444 const char *zArg = 0;
117446 const char *zToken;
117447 int nToken;
117448 int iStart;
117449 int iEnd;
117450 int iPos;
117452 Tcl_Obj *pRet;
117454 assert( argc==2 || argc==3 );
117456 nName = sqlite3_value_bytes(argv[0]);
117457 zName = (const char *)sqlite3_value_text(argv[0]);
117458 nInput = sqlite3_value_bytes(argv[argc-1]);
117459 zInput = (const char *)sqlite3_value_text(argv[argc-1]);
117461 if( argc==3 ){
117462 zArg = (const char *)sqlite3_value_text(argv[1]);
117465 pHash = (Fts3Hash *)sqlite3_user_data(context);
117466 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
117468 if( !p ){
117469 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
117470 sqlite3_result_error(context, zErr, -1);
117471 sqlite3_free(zErr);
117472 return;
117475 pRet = Tcl_NewObj();
117476 Tcl_IncrRefCount(pRet);
117478 if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
117479 zErr = "error in xCreate()";
117480 goto finish;
117482 pTokenizer->pModule = p;
117483 if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
117484 zErr = "error in xOpen()";
117485 goto finish;
117487 pCsr->pTokenizer = pTokenizer;
117489 while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
117490 Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
117491 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
117492 zToken = &zInput[iStart];
117493 nToken = iEnd-iStart;
117494 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
117497 if( SQLITE_OK!=p->xClose(pCsr) ){
117498 zErr = "error in xClose()";
117499 goto finish;
117501 if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
117502 zErr = "error in xDestroy()";
117503 goto finish;
117506 finish:
117507 if( zErr ){
117508 sqlite3_result_error(context, zErr, -1);
117509 }else{
117510 sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
117512 Tcl_DecrRefCount(pRet);
117515 static
117516 int registerTokenizer(
117517 sqlite3 *db,
117518 char *zName,
117519 const sqlite3_tokenizer_module *p
117521 int rc;
117522 sqlite3_stmt *pStmt;
117523 const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
117525 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
117526 if( rc!=SQLITE_OK ){
117527 return rc;
117530 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
117531 sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
117532 sqlite3_step(pStmt);
117534 return sqlite3_finalize(pStmt);
117537 static
117538 int queryTokenizer(
117539 sqlite3 *db,
117540 char *zName,
117541 const sqlite3_tokenizer_module **pp
117543 int rc;
117544 sqlite3_stmt *pStmt;
117545 const char zSql[] = "SELECT fts3_tokenizer(?)";
117547 *pp = 0;
117548 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
117549 if( rc!=SQLITE_OK ){
117550 return rc;
117553 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
117554 if( SQLITE_ROW==sqlite3_step(pStmt) ){
117555 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
117556 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
117560 return sqlite3_finalize(pStmt);
117563 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
117566 ** Implementation of the scalar function fts3_tokenizer_internal_test().
117567 ** This function is used for testing only, it is not included in the
117568 ** build unless SQLITE_TEST is defined.
117570 ** The purpose of this is to test that the fts3_tokenizer() function
117571 ** can be used as designed by the C-code in the queryTokenizer and
117572 ** registerTokenizer() functions above. These two functions are repeated
117573 ** in the README.tokenizer file as an example, so it is important to
117574 ** test them.
117576 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
117577 ** function with no arguments. An assert() will fail if a problem is
117578 ** detected. i.e.:
117580 ** SELECT fts3_tokenizer_internal_test();
117583 static void intTestFunc(
117584 sqlite3_context *context,
117585 int argc,
117586 sqlite3_value **argv
117588 int rc;
117589 const sqlite3_tokenizer_module *p1;
117590 const sqlite3_tokenizer_module *p2;
117591 sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
117593 UNUSED_PARAMETER(argc);
117594 UNUSED_PARAMETER(argv);
117596 /* Test the query function */
117597 sqlite3Fts3SimpleTokenizerModule(&p1);
117598 rc = queryTokenizer(db, "simple", &p2);
117599 assert( rc==SQLITE_OK );
117600 assert( p1==p2 );
117601 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
117602 assert( rc==SQLITE_ERROR );
117603 assert( p2==0 );
117604 assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
117606 /* Test the storage function */
117607 rc = registerTokenizer(db, "nosuchtokenizer", p1);
117608 assert( rc==SQLITE_OK );
117609 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
117610 assert( rc==SQLITE_OK );
117611 assert( p2==p1 );
117613 sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
117616 #endif
117619 ** Set up SQL objects in database db used to access the contents of
117620 ** the hash table pointed to by argument pHash. The hash table must
117621 ** been initialised to use string keys, and to take a private copy
117622 ** of the key when a value is inserted. i.e. by a call similar to:
117624 ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
117626 ** This function adds a scalar function (see header comment above
117627 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
117628 ** defined at compilation time, a temporary virtual table (see header
117629 ** comment above struct HashTableVtab) to the database schema. Both
117630 ** provide read/write access to the contents of *pHash.
117632 ** The third argument to this function, zName, is used as the name
117633 ** of both the scalar and, if created, the virtual table.
117635 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
117636 sqlite3 *db,
117637 Fts3Hash *pHash,
117638 const char *zName
117640 int rc = SQLITE_OK;
117641 void *p = (void *)pHash;
117642 const int any = SQLITE_ANY;
117644 #ifdef SQLITE_TEST
117645 char *zTest = 0;
117646 char *zTest2 = 0;
117647 void *pdb = (void *)db;
117648 zTest = sqlite3_mprintf("%s_test", zName);
117649 zTest2 = sqlite3_mprintf("%s_internal_test", zName);
117650 if( !zTest || !zTest2 ){
117651 rc = SQLITE_NOMEM;
117653 #endif
117655 if( SQLITE_OK==rc ){
117656 rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
117658 if( SQLITE_OK==rc ){
117659 rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
117661 #ifdef SQLITE_TEST
117662 if( SQLITE_OK==rc ){
117663 rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
117665 if( SQLITE_OK==rc ){
117666 rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
117668 if( SQLITE_OK==rc ){
117669 rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
117671 #endif
117673 #ifdef SQLITE_TEST
117674 sqlite3_free(zTest);
117675 sqlite3_free(zTest2);
117676 #endif
117678 return rc;
117681 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
117683 /************** End of fts3_tokenizer.c **************************************/
117684 /************** Begin file fts3_tokenizer1.c *********************************/
117686 ** 2006 Oct 10
117688 ** The author disclaims copyright to this source code. In place of
117689 ** a legal notice, here is a blessing:
117691 ** May you do good and not evil.
117692 ** May you find forgiveness for yourself and forgive others.
117693 ** May you share freely, never taking more than you give.
117695 ******************************************************************************
117697 ** Implementation of the "simple" full-text-search tokenizer.
117701 ** The code in this file is only compiled if:
117703 ** * The FTS3 module is being built as an extension
117704 ** (in which case SQLITE_CORE is not defined), or
117706 ** * The FTS3 module is being built into the core of
117707 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
117709 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117714 typedef struct simple_tokenizer {
117715 sqlite3_tokenizer base;
117716 char delim[128]; /* flag ASCII delimiters */
117717 } simple_tokenizer;
117719 typedef struct simple_tokenizer_cursor {
117720 sqlite3_tokenizer_cursor base;
117721 const char *pInput; /* input we are tokenizing */
117722 int nBytes; /* size of the input */
117723 int iOffset; /* current position in pInput */
117724 int iToken; /* index of next token to be returned */
117725 char *pToken; /* storage for current token */
117726 int nTokenAllocated; /* space allocated to zToken buffer */
117727 } simple_tokenizer_cursor;
117730 static int simpleDelim(simple_tokenizer *t, unsigned char c){
117731 return c<0x80 && t->delim[c];
117733 static int fts3_isalnum(int x){
117734 return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
117738 ** Create a new tokenizer instance.
117740 static int simpleCreate(
117741 int argc, const char * const *argv,
117742 sqlite3_tokenizer **ppTokenizer
117744 simple_tokenizer *t;
117746 t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
117747 if( t==NULL ) return SQLITE_NOMEM;
117748 memset(t, 0, sizeof(*t));
117750 /* TODO(shess) Delimiters need to remain the same from run to run,
117751 ** else we need to reindex. One solution would be a meta-table to
117752 ** track such information in the database, then we'd only want this
117753 ** information on the initial create.
117755 if( argc>1 ){
117756 int i, n = (int)strlen(argv[1]);
117757 for(i=0; i<n; i++){
117758 unsigned char ch = argv[1][i];
117759 /* We explicitly don't support UTF-8 delimiters for now. */
117760 if( ch>=0x80 ){
117761 sqlite3_free(t);
117762 return SQLITE_ERROR;
117764 t->delim[ch] = 1;
117766 } else {
117767 /* Mark non-alphanumeric ASCII characters as delimiters */
117768 int i;
117769 for(i=1; i<0x80; i++){
117770 t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
117774 *ppTokenizer = &t->base;
117775 return SQLITE_OK;
117779 ** Destroy a tokenizer
117781 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
117782 sqlite3_free(pTokenizer);
117783 return SQLITE_OK;
117787 ** Prepare to begin tokenizing a particular string. The input
117788 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
117789 ** used to incrementally tokenize this string is returned in
117790 ** *ppCursor.
117792 static int simpleOpen(
117793 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
117794 const char *pInput, int nBytes, /* String to be tokenized */
117795 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
117797 simple_tokenizer_cursor *c;
117799 UNUSED_PARAMETER(pTokenizer);
117801 c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
117802 if( c==NULL ) return SQLITE_NOMEM;
117804 c->pInput = pInput;
117805 if( pInput==0 ){
117806 c->nBytes = 0;
117807 }else if( nBytes<0 ){
117808 c->nBytes = (int)strlen(pInput);
117809 }else{
117810 c->nBytes = nBytes;
117812 c->iOffset = 0; /* start tokenizing at the beginning */
117813 c->iToken = 0;
117814 c->pToken = NULL; /* no space allocated, yet. */
117815 c->nTokenAllocated = 0;
117817 *ppCursor = &c->base;
117818 return SQLITE_OK;
117822 ** Close a tokenization cursor previously opened by a call to
117823 ** simpleOpen() above.
117825 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
117826 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
117827 sqlite3_free(c->pToken);
117828 sqlite3_free(c);
117829 return SQLITE_OK;
117833 ** Extract the next token from a tokenization cursor. The cursor must
117834 ** have been opened by a prior call to simpleOpen().
117836 static int simpleNext(
117837 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
117838 const char **ppToken, /* OUT: *ppToken is the token text */
117839 int *pnBytes, /* OUT: Number of bytes in token */
117840 int *piStartOffset, /* OUT: Starting offset of token */
117841 int *piEndOffset, /* OUT: Ending offset of token */
117842 int *piPosition /* OUT: Position integer of token */
117844 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
117845 simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
117846 unsigned char *p = (unsigned char *)c->pInput;
117848 while( c->iOffset<c->nBytes ){
117849 int iStartOffset;
117851 /* Scan past delimiter characters */
117852 while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
117853 c->iOffset++;
117856 /* Count non-delimiter characters. */
117857 iStartOffset = c->iOffset;
117858 while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
117859 c->iOffset++;
117862 if( c->iOffset>iStartOffset ){
117863 int i, n = c->iOffset-iStartOffset;
117864 if( n>c->nTokenAllocated ){
117865 char *pNew;
117866 c->nTokenAllocated = n+20;
117867 pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
117868 if( !pNew ) return SQLITE_NOMEM;
117869 c->pToken = pNew;
117871 for(i=0; i<n; i++){
117872 /* TODO(shess) This needs expansion to handle UTF-8
117873 ** case-insensitivity.
117875 unsigned char ch = p[iStartOffset+i];
117876 c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
117878 *ppToken = c->pToken;
117879 *pnBytes = n;
117880 *piStartOffset = iStartOffset;
117881 *piEndOffset = c->iOffset;
117882 *piPosition = c->iToken++;
117884 return SQLITE_OK;
117887 return SQLITE_DONE;
117891 ** The set of routines that implement the simple tokenizer
117893 static const sqlite3_tokenizer_module simpleTokenizerModule = {
117895 simpleCreate,
117896 simpleDestroy,
117897 simpleOpen,
117898 simpleClose,
117899 simpleNext,
117903 ** Allocate a new simple tokenizer. Return a pointer to the new
117904 ** tokenizer in *ppModule
117906 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
117907 sqlite3_tokenizer_module const**ppModule
117909 *ppModule = &simpleTokenizerModule;
117912 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
117914 /************** End of fts3_tokenizer1.c *************************************/
117915 /************** Begin file fts3_write.c **************************************/
117917 ** 2009 Oct 23
117919 ** The author disclaims copyright to this source code. In place of
117920 ** a legal notice, here is a blessing:
117922 ** May you do good and not evil.
117923 ** May you find forgiveness for yourself and forgive others.
117924 ** May you share freely, never taking more than you give.
117926 ******************************************************************************
117928 ** This file is part of the SQLite FTS3 extension module. Specifically,
117929 ** this file contains code to insert, update and delete rows from FTS3
117930 ** tables. It also contains code to merge FTS3 b-tree segments. Some
117931 ** of the sub-routines used to merge segments are also used by the query
117932 ** code in fts3.c.
117935 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117939 ** When full-text index nodes are loaded from disk, the buffer that they
117940 ** are loaded into has the following number of bytes of padding at the end
117941 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
117942 ** of 920 bytes is allocated for it.
117944 ** This means that if we have a pointer into a buffer containing node data,
117945 ** it is always safe to read up to two varints from it without risking an
117946 ** overread, even if the node data is corrupted.
117948 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
117950 typedef struct PendingList PendingList;
117951 typedef struct SegmentNode SegmentNode;
117952 typedef struct SegmentWriter SegmentWriter;
117955 ** Data structure used while accumulating terms in the pending-terms hash
117956 ** table. The hash table entry maps from term (a string) to a malloc'd
117957 ** instance of this structure.
117959 struct PendingList {
117960 int nData;
117961 char *aData;
117962 int nSpace;
117963 sqlite3_int64 iLastDocid;
117964 sqlite3_int64 iLastCol;
117965 sqlite3_int64 iLastPos;
117970 ** Each cursor has a (possibly empty) linked list of the following objects.
117972 struct Fts3DeferredToken {
117973 Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
117974 int iCol; /* Column token must occur in */
117975 Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
117976 PendingList *pList; /* Doclist is assembled here */
117980 ** An instance of this structure is used to iterate through the terms on
117981 ** a contiguous set of segment b-tree leaf nodes. Although the details of
117982 ** this structure are only manipulated by code in this file, opaque handles
117983 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
117984 ** terms when querying the full-text index. See functions:
117986 ** sqlite3Fts3SegReaderNew()
117987 ** sqlite3Fts3SegReaderFree()
117988 ** sqlite3Fts3SegReaderCost()
117989 ** sqlite3Fts3SegReaderIterate()
117991 ** Methods used to manipulate Fts3SegReader structures:
117993 ** fts3SegReaderNext()
117994 ** fts3SegReaderFirstDocid()
117995 ** fts3SegReaderNextDocid()
117997 struct Fts3SegReader {
117998 int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
118000 sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
118001 sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
118002 sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
118003 sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
118005 char *aNode; /* Pointer to node data (or NULL) */
118006 int nNode; /* Size of buffer at aNode (or 0) */
118007 Fts3HashElem **ppNextElem;
118009 /* Variables set by fts3SegReaderNext(). These may be read directly
118010 ** by the caller. They are valid from the time SegmentReaderNew() returns
118011 ** until SegmentReaderNext() returns something other than SQLITE_OK
118012 ** (i.e. SQLITE_DONE).
118014 int nTerm; /* Number of bytes in current term */
118015 char *zTerm; /* Pointer to current term */
118016 int nTermAlloc; /* Allocated size of zTerm buffer */
118017 char *aDoclist; /* Pointer to doclist of current entry */
118018 int nDoclist; /* Size of doclist in current entry */
118020 /* The following variables are used to iterate through the current doclist */
118021 char *pOffsetList;
118022 sqlite3_int64 iDocid;
118025 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
118026 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
118029 ** An instance of this structure is used to create a segment b-tree in the
118030 ** database. The internal details of this type are only accessed by the
118031 ** following functions:
118033 ** fts3SegWriterAdd()
118034 ** fts3SegWriterFlush()
118035 ** fts3SegWriterFree()
118037 struct SegmentWriter {
118038 SegmentNode *pTree; /* Pointer to interior tree structure */
118039 sqlite3_int64 iFirst; /* First slot in %_segments written */
118040 sqlite3_int64 iFree; /* Next free slot in %_segments */
118041 char *zTerm; /* Pointer to previous term buffer */
118042 int nTerm; /* Number of bytes in zTerm */
118043 int nMalloc; /* Size of malloc'd buffer at zMalloc */
118044 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
118045 int nSize; /* Size of allocation at aData */
118046 int nData; /* Bytes of data in aData */
118047 char *aData; /* Pointer to block from malloc() */
118051 ** Type SegmentNode is used by the following three functions to create
118052 ** the interior part of the segment b+-tree structures (everything except
118053 ** the leaf nodes). These functions and type are only ever used by code
118054 ** within the fts3SegWriterXXX() family of functions described above.
118056 ** fts3NodeAddTerm()
118057 ** fts3NodeWrite()
118058 ** fts3NodeFree()
118060 struct SegmentNode {
118061 SegmentNode *pParent; /* Parent node (or NULL for root node) */
118062 SegmentNode *pRight; /* Pointer to right-sibling */
118063 SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
118064 int nEntry; /* Number of terms written to node so far */
118065 char *zTerm; /* Pointer to previous term buffer */
118066 int nTerm; /* Number of bytes in zTerm */
118067 int nMalloc; /* Size of malloc'd buffer at zMalloc */
118068 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
118069 int nData; /* Bytes of valid data so far */
118070 char *aData; /* Node data */
118074 ** Valid values for the second argument to fts3SqlStmt().
118076 #define SQL_DELETE_CONTENT 0
118077 #define SQL_IS_EMPTY 1
118078 #define SQL_DELETE_ALL_CONTENT 2
118079 #define SQL_DELETE_ALL_SEGMENTS 3
118080 #define SQL_DELETE_ALL_SEGDIR 4
118081 #define SQL_DELETE_ALL_DOCSIZE 5
118082 #define SQL_DELETE_ALL_STAT 6
118083 #define SQL_SELECT_CONTENT_BY_ROWID 7
118084 #define SQL_NEXT_SEGMENT_INDEX 8
118085 #define SQL_INSERT_SEGMENTS 9
118086 #define SQL_NEXT_SEGMENTS_ID 10
118087 #define SQL_INSERT_SEGDIR 11
118088 #define SQL_SELECT_LEVEL 12
118089 #define SQL_SELECT_ALL_LEVEL 13
118090 #define SQL_SELECT_LEVEL_COUNT 14
118091 #define SQL_SELECT_SEGDIR_COUNT_MAX 15
118092 #define SQL_DELETE_SEGDIR_BY_LEVEL 16
118093 #define SQL_DELETE_SEGMENTS_RANGE 17
118094 #define SQL_CONTENT_INSERT 18
118095 #define SQL_DELETE_DOCSIZE 19
118096 #define SQL_REPLACE_DOCSIZE 20
118097 #define SQL_SELECT_DOCSIZE 21
118098 #define SQL_SELECT_DOCTOTAL 22
118099 #define SQL_REPLACE_DOCTOTAL 23
118102 ** This function is used to obtain an SQLite prepared statement handle
118103 ** for the statement identified by the second argument. If successful,
118104 ** *pp is set to the requested statement handle and SQLITE_OK returned.
118105 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
118107 ** If argument apVal is not NULL, then it must point to an array with
118108 ** at least as many entries as the requested statement has bound
118109 ** parameters. The values are bound to the statements parameters before
118110 ** returning.
118112 static int fts3SqlStmt(
118113 Fts3Table *p, /* Virtual table handle */
118114 int eStmt, /* One of the SQL_XXX constants above */
118115 sqlite3_stmt **pp, /* OUT: Statement handle */
118116 sqlite3_value **apVal /* Values to bind to statement */
118118 const char *azSql[] = {
118119 /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
118120 /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
118121 /* 2 */ "DELETE FROM %Q.'%q_content'",
118122 /* 3 */ "DELETE FROM %Q.'%q_segments'",
118123 /* 4 */ "DELETE FROM %Q.'%q_segdir'",
118124 /* 5 */ "DELETE FROM %Q.'%q_docsize'",
118125 /* 6 */ "DELETE FROM %Q.'%q_stat'",
118126 /* 7 */ "SELECT %s FROM %Q.'%q_content' AS x WHERE rowid=?",
118127 /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
118128 /* 9 */ "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
118129 /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
118130 /* 11 */ "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
118132 /* Return segments in order from oldest to newest.*/
118133 /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
118134 "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
118135 /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
118136 "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
118138 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
118139 /* 15 */ "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
118141 /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
118142 /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
118143 /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
118144 /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
118145 /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
118146 /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
118147 /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=0",
118148 /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
118150 int rc = SQLITE_OK;
118151 sqlite3_stmt *pStmt;
118153 assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
118154 assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
118156 pStmt = p->aStmt[eStmt];
118157 if( !pStmt ){
118158 char *zSql;
118159 if( eStmt==SQL_CONTENT_INSERT ){
118160 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
118161 }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
118162 zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist, p->zDb, p->zName);
118163 }else{
118164 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
118166 if( !zSql ){
118167 rc = SQLITE_NOMEM;
118168 }else{
118169 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
118170 sqlite3_free(zSql);
118171 assert( rc==SQLITE_OK || pStmt==0 );
118172 p->aStmt[eStmt] = pStmt;
118175 if( apVal ){
118176 int i;
118177 int nParam = sqlite3_bind_parameter_count(pStmt);
118178 for(i=0; rc==SQLITE_OK && i<nParam; i++){
118179 rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
118182 *pp = pStmt;
118183 return rc;
118186 static int fts3SelectDocsize(
118187 Fts3Table *pTab, /* FTS3 table handle */
118188 int eStmt, /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
118189 sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
118190 sqlite3_stmt **ppStmt /* OUT: Statement handle */
118192 sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
118193 int rc; /* Return code */
118195 assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
118197 rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
118198 if( rc==SQLITE_OK ){
118199 if( eStmt==SQL_SELECT_DOCSIZE ){
118200 sqlite3_bind_int64(pStmt, 1, iDocid);
118202 rc = sqlite3_step(pStmt);
118203 if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
118204 rc = sqlite3_reset(pStmt);
118205 if( rc==SQLITE_OK ) rc = SQLITE_CORRUPT;
118206 pStmt = 0;
118207 }else{
118208 rc = SQLITE_OK;
118212 *ppStmt = pStmt;
118213 return rc;
118216 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
118217 Fts3Table *pTab, /* Fts3 table handle */
118218 sqlite3_stmt **ppStmt /* OUT: Statement handle */
118220 return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
118223 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
118224 Fts3Table *pTab, /* Fts3 table handle */
118225 sqlite3_int64 iDocid, /* Docid to read size data for */
118226 sqlite3_stmt **ppStmt /* OUT: Statement handle */
118228 return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
118232 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
118233 ** array apVal[] to the SQL statement identified by eStmt, the statement
118234 ** is executed.
118236 ** Returns SQLITE_OK if the statement is successfully executed, or an
118237 ** SQLite error code otherwise.
118239 static void fts3SqlExec(
118240 int *pRC, /* Result code */
118241 Fts3Table *p, /* The FTS3 table */
118242 int eStmt, /* Index of statement to evaluate */
118243 sqlite3_value **apVal /* Parameters to bind */
118245 sqlite3_stmt *pStmt;
118246 int rc;
118247 if( *pRC ) return;
118248 rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
118249 if( rc==SQLITE_OK ){
118250 sqlite3_step(pStmt);
118251 rc = sqlite3_reset(pStmt);
118253 *pRC = rc;
118258 ** This function ensures that the caller has obtained a shared-cache
118259 ** table-lock on the %_content table. This is required before reading
118260 ** data from the fts3 table. If this lock is not acquired first, then
118261 ** the caller may end up holding read-locks on the %_segments and %_segdir
118262 ** tables, but no read-lock on the %_content table. If this happens
118263 ** a second connection will be able to write to the fts3 table, but
118264 ** attempting to commit those writes might return SQLITE_LOCKED or
118265 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
118266 ** write-locks on the %_segments and %_segdir ** tables).
118268 ** We try to avoid this because if FTS3 returns any error when committing
118269 ** a transaction, the whole transaction will be rolled back. And this is
118270 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
118271 ** still happen if the user reads data directly from the %_segments or
118272 ** %_segdir tables instead of going through FTS3 though.
118274 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
118275 int rc; /* Return code */
118276 sqlite3_stmt *pStmt; /* Statement used to obtain lock */
118278 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
118279 if( rc==SQLITE_OK ){
118280 sqlite3_bind_null(pStmt, 1);
118281 sqlite3_step(pStmt);
118282 rc = sqlite3_reset(pStmt);
118284 return rc;
118288 ** Set *ppStmt to a statement handle that may be used to iterate through
118289 ** all rows in the %_segdir table, from oldest to newest. If successful,
118290 ** return SQLITE_OK. If an error occurs while preparing the statement,
118291 ** return an SQLite error code.
118293 ** There is only ever one instance of this SQL statement compiled for
118294 ** each FTS3 table.
118296 ** The statement returns the following columns from the %_segdir table:
118298 ** 0: idx
118299 ** 1: start_block
118300 ** 2: leaves_end_block
118301 ** 3: end_block
118302 ** 4: root
118304 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, int iLevel, sqlite3_stmt **ppStmt){
118305 int rc;
118306 sqlite3_stmt *pStmt = 0;
118307 if( iLevel<0 ){
118308 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, &pStmt, 0);
118309 }else{
118310 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
118311 if( rc==SQLITE_OK ) sqlite3_bind_int(pStmt, 1, iLevel);
118313 *ppStmt = pStmt;
118314 return rc;
118319 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
118320 ** if successful, or an SQLite error code otherwise.
118322 ** This function also serves to allocate the PendingList structure itself.
118323 ** For example, to create a new PendingList structure containing two
118324 ** varints:
118326 ** PendingList *p = 0;
118327 ** fts3PendingListAppendVarint(&p, 1);
118328 ** fts3PendingListAppendVarint(&p, 2);
118330 static int fts3PendingListAppendVarint(
118331 PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
118332 sqlite3_int64 i /* Value to append to data */
118334 PendingList *p = *pp;
118336 /* Allocate or grow the PendingList as required. */
118337 if( !p ){
118338 p = sqlite3_malloc(sizeof(*p) + 100);
118339 if( !p ){
118340 return SQLITE_NOMEM;
118342 p->nSpace = 100;
118343 p->aData = (char *)&p[1];
118344 p->nData = 0;
118346 else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
118347 int nNew = p->nSpace * 2;
118348 p = sqlite3_realloc(p, sizeof(*p) + nNew);
118349 if( !p ){
118350 sqlite3_free(*pp);
118351 *pp = 0;
118352 return SQLITE_NOMEM;
118354 p->nSpace = nNew;
118355 p->aData = (char *)&p[1];
118358 /* Append the new serialized varint to the end of the list. */
118359 p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
118360 p->aData[p->nData] = '\0';
118361 *pp = p;
118362 return SQLITE_OK;
118366 ** Add a docid/column/position entry to a PendingList structure. Non-zero
118367 ** is returned if the structure is sqlite3_realloced as part of adding
118368 ** the entry. Otherwise, zero.
118370 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
118371 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
118372 ** it is set to SQLITE_OK.
118374 static int fts3PendingListAppend(
118375 PendingList **pp, /* IN/OUT: PendingList structure */
118376 sqlite3_int64 iDocid, /* Docid for entry to add */
118377 sqlite3_int64 iCol, /* Column for entry to add */
118378 sqlite3_int64 iPos, /* Position of term for entry to add */
118379 int *pRc /* OUT: Return code */
118381 PendingList *p = *pp;
118382 int rc = SQLITE_OK;
118384 assert( !p || p->iLastDocid<=iDocid );
118386 if( !p || p->iLastDocid!=iDocid ){
118387 sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
118388 if( p ){
118389 assert( p->nData<p->nSpace );
118390 assert( p->aData[p->nData]==0 );
118391 p->nData++;
118393 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
118394 goto pendinglistappend_out;
118396 p->iLastCol = -1;
118397 p->iLastPos = 0;
118398 p->iLastDocid = iDocid;
118400 if( iCol>0 && p->iLastCol!=iCol ){
118401 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
118402 || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
118404 goto pendinglistappend_out;
118406 p->iLastCol = iCol;
118407 p->iLastPos = 0;
118409 if( iCol>=0 ){
118410 assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
118411 rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
118412 if( rc==SQLITE_OK ){
118413 p->iLastPos = iPos;
118417 pendinglistappend_out:
118418 *pRc = rc;
118419 if( p!=*pp ){
118420 *pp = p;
118421 return 1;
118423 return 0;
118427 ** Tokenize the nul-terminated string zText and add all tokens to the
118428 ** pending-terms hash-table. The docid used is that currently stored in
118429 ** p->iPrevDocid, and the column is specified by argument iCol.
118431 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
118433 static int fts3PendingTermsAdd(
118434 Fts3Table *p, /* Table into which text will be inserted */
118435 const char *zText, /* Text of document to be inserted */
118436 int iCol, /* Column into which text is being inserted */
118437 u32 *pnWord /* OUT: Number of tokens inserted */
118439 int rc;
118440 int iStart;
118441 int iEnd;
118442 int iPos;
118443 int nWord = 0;
118445 char const *zToken;
118446 int nToken;
118448 sqlite3_tokenizer *pTokenizer = p->pTokenizer;
118449 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
118450 sqlite3_tokenizer_cursor *pCsr;
118451 int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
118452 const char**,int*,int*,int*,int*);
118454 assert( pTokenizer && pModule );
118456 rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
118457 if( rc!=SQLITE_OK ){
118458 return rc;
118460 pCsr->pTokenizer = pTokenizer;
118462 xNext = pModule->xNext;
118463 while( SQLITE_OK==rc
118464 && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
118466 PendingList *pList;
118468 if( iPos>=nWord ) nWord = iPos+1;
118470 /* Positions cannot be negative; we use -1 as a terminator internally.
118471 ** Tokens must have a non-zero length.
118473 if( iPos<0 || !zToken || nToken<=0 ){
118474 rc = SQLITE_ERROR;
118475 break;
118478 pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
118479 if( pList ){
118480 p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
118482 if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
118483 if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
118484 /* Malloc failed while inserting the new entry. This can only
118485 ** happen if there was no previous entry for this token.
118487 assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
118488 sqlite3_free(pList);
118489 rc = SQLITE_NOMEM;
118492 if( rc==SQLITE_OK ){
118493 p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
118497 pModule->xClose(pCsr);
118498 *pnWord = nWord;
118499 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
118503 ** Calling this function indicates that subsequent calls to
118504 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
118505 ** contents of the document with docid iDocid.
118507 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
118508 /* TODO(shess) Explore whether partially flushing the buffer on
118509 ** forced-flush would provide better performance. I suspect that if
118510 ** we ordered the doclists by size and flushed the largest until the
118511 ** buffer was half empty, that would let the less frequent terms
118512 ** generate longer doclists.
118514 if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
118515 int rc = sqlite3Fts3PendingTermsFlush(p);
118516 if( rc!=SQLITE_OK ) return rc;
118518 p->iPrevDocid = iDocid;
118519 return SQLITE_OK;
118523 ** Discard the contents of the pending-terms hash table.
118525 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
118526 Fts3HashElem *pElem;
118527 for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
118528 sqlite3_free(fts3HashData(pElem));
118530 fts3HashClear(&p->pendingTerms);
118531 p->nPendingData = 0;
118535 ** This function is called by the xUpdate() method as part of an INSERT
118536 ** operation. It adds entries for each term in the new record to the
118537 ** pendingTerms hash table.
118539 ** Argument apVal is the same as the similarly named argument passed to
118540 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
118542 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
118543 int i; /* Iterator variable */
118544 for(i=2; i<p->nColumn+2; i++){
118545 const char *zText = (const char *)sqlite3_value_text(apVal[i]);
118546 if( zText ){
118547 int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
118548 if( rc!=SQLITE_OK ){
118549 return rc;
118552 aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
118554 return SQLITE_OK;
118558 ** This function is called by the xUpdate() method for an INSERT operation.
118559 ** The apVal parameter is passed a copy of the apVal argument passed by
118560 ** SQLite to the xUpdate() method. i.e:
118562 ** apVal[0] Not used for INSERT.
118563 ** apVal[1] rowid
118564 ** apVal[2] Left-most user-defined column
118565 ** ...
118566 ** apVal[p->nColumn+1] Right-most user-defined column
118567 ** apVal[p->nColumn+2] Hidden column with same name as table
118568 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
118570 static int fts3InsertData(
118571 Fts3Table *p, /* Full-text table */
118572 sqlite3_value **apVal, /* Array of values to insert */
118573 sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
118575 int rc; /* Return code */
118576 sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
118578 /* Locate the statement handle used to insert data into the %_content
118579 ** table. The SQL for this statement is:
118581 ** INSERT INTO %_content VALUES(?, ?, ?, ...)
118583 ** The statement features N '?' variables, where N is the number of user
118584 ** defined columns in the FTS3 table, plus one for the docid field.
118586 rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
118587 if( rc!=SQLITE_OK ){
118588 return rc;
118591 /* There is a quirk here. The users INSERT statement may have specified
118592 ** a value for the "rowid" field, for the "docid" field, or for both.
118593 ** Which is a problem, since "rowid" and "docid" are aliases for the
118594 ** same value. For example:
118596 ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
118598 ** In FTS3, this is an error. It is an error to specify non-NULL values
118599 ** for both docid and some other rowid alias.
118601 if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
118602 if( SQLITE_NULL==sqlite3_value_type(apVal[0])
118603 && SQLITE_NULL!=sqlite3_value_type(apVal[1])
118605 /* A rowid/docid conflict. */
118606 return SQLITE_ERROR;
118608 rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
118609 if( rc!=SQLITE_OK ) return rc;
118612 /* Execute the statement to insert the record. Set *piDocid to the
118613 ** new docid value.
118615 sqlite3_step(pContentInsert);
118616 rc = sqlite3_reset(pContentInsert);
118618 *piDocid = sqlite3_last_insert_rowid(p->db);
118619 return rc;
118625 ** Remove all data from the FTS3 table. Clear the hash table containing
118626 ** pending terms.
118628 static int fts3DeleteAll(Fts3Table *p){
118629 int rc = SQLITE_OK; /* Return code */
118631 /* Discard the contents of the pending-terms hash table. */
118632 sqlite3Fts3PendingTermsClear(p);
118634 /* Delete everything from the %_content, %_segments and %_segdir tables. */
118635 fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
118636 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
118637 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
118638 if( p->bHasDocsize ){
118639 fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
118641 if( p->bHasStat ){
118642 fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
118644 return rc;
118648 ** The first element in the apVal[] array is assumed to contain the docid
118649 ** (an integer) of a row about to be deleted. Remove all terms from the
118650 ** full-text index.
118652 static void fts3DeleteTerms(
118653 int *pRC, /* Result code */
118654 Fts3Table *p, /* The FTS table to delete from */
118655 sqlite3_value **apVal, /* apVal[] contains the docid to be deleted */
118656 u32 *aSz /* Sizes of deleted document written here */
118658 int rc;
118659 sqlite3_stmt *pSelect;
118661 if( *pRC ) return;
118662 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
118663 if( rc==SQLITE_OK ){
118664 if( SQLITE_ROW==sqlite3_step(pSelect) ){
118665 int i;
118666 for(i=1; i<=p->nColumn; i++){
118667 const char *zText = (const char *)sqlite3_column_text(pSelect, i);
118668 rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
118669 if( rc!=SQLITE_OK ){
118670 sqlite3_reset(pSelect);
118671 *pRC = rc;
118672 return;
118674 aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
118677 rc = sqlite3_reset(pSelect);
118678 }else{
118679 sqlite3_reset(pSelect);
118681 *pRC = rc;
118685 ** Forward declaration to account for the circular dependency between
118686 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
118688 static int fts3SegmentMerge(Fts3Table *, int);
118691 ** This function allocates a new level iLevel index in the segdir table.
118692 ** Usually, indexes are allocated within a level sequentially starting
118693 ** with 0, so the allocated index is one greater than the value returned
118694 ** by:
118696 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
118698 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
118699 ** level, they are merged into a single level (iLevel+1) segment and the
118700 ** allocated index is 0.
118702 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
118703 ** returned. Otherwise, an SQLite error code is returned.
118705 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
118706 int rc; /* Return Code */
118707 sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
118708 int iNext = 0; /* Result of query pNextIdx */
118710 /* Set variable iNext to the next available segdir index at level iLevel. */
118711 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
118712 if( rc==SQLITE_OK ){
118713 sqlite3_bind_int(pNextIdx, 1, iLevel);
118714 if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
118715 iNext = sqlite3_column_int(pNextIdx, 0);
118717 rc = sqlite3_reset(pNextIdx);
118720 if( rc==SQLITE_OK ){
118721 /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
118722 ** full, merge all segments in level iLevel into a single iLevel+1
118723 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
118724 ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
118726 if( iNext>=FTS3_MERGE_COUNT ){
118727 rc = fts3SegmentMerge(p, iLevel);
118728 *piIdx = 0;
118729 }else{
118730 *piIdx = iNext;
118734 return rc;
118738 ** The %_segments table is declared as follows:
118740 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
118742 ** This function reads data from a single row of the %_segments table. The
118743 ** specific row is identified by the iBlockid parameter. If paBlob is not
118744 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
118745 ** with the contents of the blob stored in the "block" column of the
118746 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
118747 ** to the size of the blob in bytes before returning.
118749 ** If an error occurs, or the table does not contain the specified row,
118750 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
118751 ** paBlob is non-NULL, then it is the responsibility of the caller to
118752 ** eventually free the returned buffer.
118754 ** This function may leave an open sqlite3_blob* handle in the
118755 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
118756 ** to this function. The handle may be closed by calling the
118757 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
118758 ** performance improvement, but the blob handle should always be closed
118759 ** before control is returned to the user (to prevent a lock being held
118760 ** on the database file for longer than necessary). Thus, any virtual table
118761 ** method (xFilter etc.) that may directly or indirectly call this function
118762 ** must call sqlite3Fts3SegmentsClose() before returning.
118764 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
118765 Fts3Table *p, /* FTS3 table handle */
118766 sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
118767 char **paBlob, /* OUT: Blob data in malloc'd buffer */
118768 int *pnBlob /* OUT: Size of blob data */
118770 int rc; /* Return code */
118772 /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
118773 assert( pnBlob);
118775 if( p->pSegments ){
118776 rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
118777 }else{
118778 if( 0==p->zSegmentsTbl ){
118779 p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
118780 if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
118782 rc = sqlite3_blob_open(
118783 p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
118787 if( rc==SQLITE_OK ){
118788 int nByte = sqlite3_blob_bytes(p->pSegments);
118789 if( paBlob ){
118790 char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
118791 if( !aByte ){
118792 rc = SQLITE_NOMEM;
118793 }else{
118794 rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
118795 memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
118796 if( rc!=SQLITE_OK ){
118797 sqlite3_free(aByte);
118798 aByte = 0;
118801 *paBlob = aByte;
118803 *pnBlob = nByte;
118806 return rc;
118810 ** Close the blob handle at p->pSegments, if it is open. See comments above
118811 ** the sqlite3Fts3ReadBlock() function for details.
118813 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
118814 sqlite3_blob_close(p->pSegments);
118815 p->pSegments = 0;
118819 ** Move the iterator passed as the first argument to the next term in the
118820 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
118821 ** SQLITE_DONE. Otherwise, an SQLite error code.
118823 static int fts3SegReaderNext(Fts3Table *p, Fts3SegReader *pReader){
118824 char *pNext; /* Cursor variable */
118825 int nPrefix; /* Number of bytes in term prefix */
118826 int nSuffix; /* Number of bytes in term suffix */
118828 if( !pReader->aDoclist ){
118829 pNext = pReader->aNode;
118830 }else{
118831 pNext = &pReader->aDoclist[pReader->nDoclist];
118834 if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
118835 int rc; /* Return code from Fts3ReadBlock() */
118837 if( fts3SegReaderIsPending(pReader) ){
118838 Fts3HashElem *pElem = *(pReader->ppNextElem);
118839 if( pElem==0 ){
118840 pReader->aNode = 0;
118841 }else{
118842 PendingList *pList = (PendingList *)fts3HashData(pElem);
118843 pReader->zTerm = (char *)fts3HashKey(pElem);
118844 pReader->nTerm = fts3HashKeysize(pElem);
118845 pReader->nNode = pReader->nDoclist = pList->nData + 1;
118846 pReader->aNode = pReader->aDoclist = pList->aData;
118847 pReader->ppNextElem++;
118848 assert( pReader->aNode );
118850 return SQLITE_OK;
118853 if( !fts3SegReaderIsRootOnly(pReader) ){
118854 sqlite3_free(pReader->aNode);
118856 pReader->aNode = 0;
118858 /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
118859 ** blocks have already been traversed. */
118860 assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
118861 if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
118862 return SQLITE_OK;
118865 rc = sqlite3Fts3ReadBlock(
118866 p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode
118868 if( rc!=SQLITE_OK ) return rc;
118869 pNext = pReader->aNode;
118872 /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
118873 ** safe (no risk of overread) even if the node data is corrupted.
118875 pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
118876 pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
118877 if( nPrefix<0 || nSuffix<=0
118878 || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
118880 return SQLITE_CORRUPT;
118883 if( nPrefix+nSuffix>pReader->nTermAlloc ){
118884 int nNew = (nPrefix+nSuffix)*2;
118885 char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
118886 if( !zNew ){
118887 return SQLITE_NOMEM;
118889 pReader->zTerm = zNew;
118890 pReader->nTermAlloc = nNew;
118892 memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
118893 pReader->nTerm = nPrefix+nSuffix;
118894 pNext += nSuffix;
118895 pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
118896 pReader->aDoclist = pNext;
118897 pReader->pOffsetList = 0;
118899 /* Check that the doclist does not appear to extend past the end of the
118900 ** b-tree node. And that the final byte of the doclist is 0x00. If either
118901 ** of these statements is untrue, then the data structure is corrupt.
118903 if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
118904 || pReader->aDoclist[pReader->nDoclist-1]
118906 return SQLITE_CORRUPT;
118908 return SQLITE_OK;
118912 ** Set the SegReader to point to the first docid in the doclist associated
118913 ** with the current term.
118915 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
118916 int n;
118917 assert( pReader->aDoclist );
118918 assert( !pReader->pOffsetList );
118919 n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
118920 pReader->pOffsetList = &pReader->aDoclist[n];
118924 ** Advance the SegReader to point to the next docid in the doclist
118925 ** associated with the current term.
118927 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
118928 ** *ppOffsetList is set to point to the first column-offset list
118929 ** in the doclist entry (i.e. immediately past the docid varint).
118930 ** *pnOffsetList is set to the length of the set of column-offset
118931 ** lists, not including the nul-terminator byte. For example:
118933 static void fts3SegReaderNextDocid(
118934 Fts3SegReader *pReader,
118935 char **ppOffsetList,
118936 int *pnOffsetList
118938 char *p = pReader->pOffsetList;
118939 char c = 0;
118941 /* Pointer p currently points at the first byte of an offset list. The
118942 ** following two lines advance it to point one byte past the end of
118943 ** the same offset list.
118945 while( *p | c ) c = *p++ & 0x80;
118948 /* If required, populate the output variables with a pointer to and the
118949 ** size of the previous offset-list.
118951 if( ppOffsetList ){
118952 *ppOffsetList = pReader->pOffsetList;
118953 *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
118956 /* If there are no more entries in the doclist, set pOffsetList to
118957 ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
118958 ** Fts3SegReader.pOffsetList to point to the next offset list before
118959 ** returning.
118961 if( p>=&pReader->aDoclist[pReader->nDoclist] ){
118962 pReader->pOffsetList = 0;
118963 }else{
118964 sqlite3_int64 iDelta;
118965 pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
118966 pReader->iDocid += iDelta;
118971 ** This function is called to estimate the amount of data that will be
118972 ** loaded from the disk If SegReaderIterate() is called on this seg-reader,
118973 ** in units of average document size.
118975 ** This can be used as follows: If the caller has a small doclist that
118976 ** contains references to N documents, and is considering merging it with
118977 ** a large doclist (size X "average documents"), it may opt not to load
118978 ** the large doclist if X>N.
118980 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(
118981 Fts3Cursor *pCsr, /* FTS3 cursor handle */
118982 Fts3SegReader *pReader, /* Segment-reader handle */
118983 int *pnCost /* IN/OUT: Number of bytes read */
118985 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
118986 int rc = SQLITE_OK; /* Return code */
118987 int nCost = 0; /* Cost in bytes to return */
118988 int pgsz = p->nPgsz; /* Database page size */
118990 /* If this seg-reader is reading the pending-terms table, or if all data
118991 ** for the segment is stored on the root page of the b-tree, then the cost
118992 ** is zero. In this case all required data is already in main memory.
118994 if( p->bHasStat
118995 && !fts3SegReaderIsPending(pReader)
118996 && !fts3SegReaderIsRootOnly(pReader)
118998 int nBlob = 0;
118999 sqlite3_int64 iBlock;
119001 if( pCsr->nRowAvg==0 ){
119002 /* The average document size, which is required to calculate the cost
119003 ** of each doclist, has not yet been determined. Read the required
119004 ** data from the %_stat table to calculate it.
119006 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
119007 ** varints, where nCol is the number of columns in the FTS3 table.
119008 ** The first varint is the number of documents currently stored in
119009 ** the table. The following nCol varints contain the total amount of
119010 ** data stored in all rows of each column of the table, from left
119011 ** to right.
119013 sqlite3_stmt *pStmt;
119014 sqlite3_int64 nDoc = 0;
119015 sqlite3_int64 nByte = 0;
119016 const char *pEnd;
119017 const char *a;
119019 rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
119020 if( rc!=SQLITE_OK ) return rc;
119021 a = sqlite3_column_blob(pStmt, 0);
119022 assert( a );
119024 pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
119025 a += sqlite3Fts3GetVarint(a, &nDoc);
119026 while( a<pEnd ){
119027 a += sqlite3Fts3GetVarint(a, &nByte);
119029 if( nDoc==0 || nByte==0 ){
119030 sqlite3_reset(pStmt);
119031 return SQLITE_CORRUPT;
119034 pCsr->nRowAvg = (int)(((nByte / nDoc) + pgsz) / pgsz);
119035 assert( pCsr->nRowAvg>0 );
119036 rc = sqlite3_reset(pStmt);
119037 if( rc!=SQLITE_OK ) return rc;
119040 /* Assume that a blob flows over onto overflow pages if it is larger
119041 ** than (pgsz-35) bytes in size (the file-format documentation
119042 ** confirms this).
119044 for(iBlock=pReader->iStartBlock; iBlock<=pReader->iLeafEndBlock; iBlock++){
119045 rc = sqlite3Fts3ReadBlock(p, iBlock, 0, &nBlob);
119046 if( rc!=SQLITE_OK ) break;
119047 if( (nBlob+35)>pgsz ){
119048 int nOvfl = (nBlob + 34)/pgsz;
119049 nCost += ((nOvfl + pCsr->nRowAvg - 1)/pCsr->nRowAvg);
119054 *pnCost += nCost;
119055 return rc;
119059 ** Free all allocations associated with the iterator passed as the
119060 ** second argument.
119062 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
119063 if( pReader && !fts3SegReaderIsPending(pReader) ){
119064 sqlite3_free(pReader->zTerm);
119065 if( !fts3SegReaderIsRootOnly(pReader) ){
119066 sqlite3_free(pReader->aNode);
119069 sqlite3_free(pReader);
119073 ** Allocate a new SegReader object.
119075 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
119076 int iAge, /* Segment "age". */
119077 sqlite3_int64 iStartLeaf, /* First leaf to traverse */
119078 sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
119079 sqlite3_int64 iEndBlock, /* Final block of segment */
119080 const char *zRoot, /* Buffer containing root node */
119081 int nRoot, /* Size of buffer containing root node */
119082 Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
119084 int rc = SQLITE_OK; /* Return code */
119085 Fts3SegReader *pReader; /* Newly allocated SegReader object */
119086 int nExtra = 0; /* Bytes to allocate segment root node */
119088 assert( iStartLeaf<=iEndLeaf );
119089 if( iStartLeaf==0 ){
119090 nExtra = nRoot + FTS3_NODE_PADDING;
119093 pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
119094 if( !pReader ){
119095 return SQLITE_NOMEM;
119097 memset(pReader, 0, sizeof(Fts3SegReader));
119098 pReader->iIdx = iAge;
119099 pReader->iStartBlock = iStartLeaf;
119100 pReader->iLeafEndBlock = iEndLeaf;
119101 pReader->iEndBlock = iEndBlock;
119103 if( nExtra ){
119104 /* The entire segment is stored in the root node. */
119105 pReader->aNode = (char *)&pReader[1];
119106 pReader->nNode = nRoot;
119107 memcpy(pReader->aNode, zRoot, nRoot);
119108 memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
119109 }else{
119110 pReader->iCurrentBlock = iStartLeaf-1;
119113 if( rc==SQLITE_OK ){
119114 *ppReader = pReader;
119115 }else{
119116 sqlite3Fts3SegReaderFree(pReader);
119118 return rc;
119122 ** This is a comparison function used as a qsort() callback when sorting
119123 ** an array of pending terms by term. This occurs as part of flushing
119124 ** the contents of the pending-terms hash table to the database.
119126 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
119127 char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
119128 char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
119129 int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
119130 int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
119132 int n = (n1<n2 ? n1 : n2);
119133 int c = memcmp(z1, z2, n);
119134 if( c==0 ){
119135 c = n1 - n2;
119137 return c;
119141 ** This function is used to allocate an Fts3SegReader that iterates through
119142 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
119144 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
119145 Fts3Table *p, /* Virtual table handle */
119146 const char *zTerm, /* Term to search for */
119147 int nTerm, /* Size of buffer zTerm */
119148 int isPrefix, /* True for a term-prefix query */
119149 Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
119151 Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
119152 Fts3HashElem *pE; /* Iterator variable */
119153 Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
119154 int nElem = 0; /* Size of array at aElem */
119155 int rc = SQLITE_OK; /* Return Code */
119157 if( isPrefix ){
119158 int nAlloc = 0; /* Size of allocated array at aElem */
119160 for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
119161 char *zKey = (char *)fts3HashKey(pE);
119162 int nKey = fts3HashKeysize(pE);
119163 if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
119164 if( nElem==nAlloc ){
119165 Fts3HashElem **aElem2;
119166 nAlloc += 16;
119167 aElem2 = (Fts3HashElem **)sqlite3_realloc(
119168 aElem, nAlloc*sizeof(Fts3HashElem *)
119170 if( !aElem2 ){
119171 rc = SQLITE_NOMEM;
119172 nElem = 0;
119173 break;
119175 aElem = aElem2;
119177 aElem[nElem++] = pE;
119181 /* If more than one term matches the prefix, sort the Fts3HashElem
119182 ** objects in term order using qsort(). This uses the same comparison
119183 ** callback as is used when flushing terms to disk.
119185 if( nElem>1 ){
119186 qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
119189 }else{
119190 pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
119191 if( pE ){
119192 aElem = &pE;
119193 nElem = 1;
119197 if( nElem>0 ){
119198 int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
119199 pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
119200 if( !pReader ){
119201 rc = SQLITE_NOMEM;
119202 }else{
119203 memset(pReader, 0, nByte);
119204 pReader->iIdx = 0x7FFFFFFF;
119205 pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
119206 memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
119210 if( isPrefix ){
119211 sqlite3_free(aElem);
119213 *ppReader = pReader;
119214 return rc;
119218 ** Compare the entries pointed to by two Fts3SegReader structures.
119219 ** Comparison is as follows:
119221 ** 1) EOF is greater than not EOF.
119223 ** 2) The current terms (if any) are compared using memcmp(). If one
119224 ** term is a prefix of another, the longer term is considered the
119225 ** larger.
119227 ** 3) By segment age. An older segment is considered larger.
119229 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
119230 int rc;
119231 if( pLhs->aNode && pRhs->aNode ){
119232 int rc2 = pLhs->nTerm - pRhs->nTerm;
119233 if( rc2<0 ){
119234 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
119235 }else{
119236 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
119238 if( rc==0 ){
119239 rc = rc2;
119241 }else{
119242 rc = (pLhs->aNode==0) - (pRhs->aNode==0);
119244 if( rc==0 ){
119245 rc = pRhs->iIdx - pLhs->iIdx;
119247 assert( rc!=0 );
119248 return rc;
119252 ** A different comparison function for SegReader structures. In this
119253 ** version, it is assumed that each SegReader points to an entry in
119254 ** a doclist for identical terms. Comparison is made as follows:
119256 ** 1) EOF (end of doclist in this case) is greater than not EOF.
119258 ** 2) By current docid.
119260 ** 3) By segment age. An older segment is considered larger.
119262 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
119263 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
119264 if( rc==0 ){
119265 if( pLhs->iDocid==pRhs->iDocid ){
119266 rc = pRhs->iIdx - pLhs->iIdx;
119267 }else{
119268 rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
119271 assert( pLhs->aNode && pRhs->aNode );
119272 return rc;
119276 ** Compare the term that the Fts3SegReader object passed as the first argument
119277 ** points to with the term specified by arguments zTerm and nTerm.
119279 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
119280 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
119281 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
119283 static int fts3SegReaderTermCmp(
119284 Fts3SegReader *pSeg, /* Segment reader object */
119285 const char *zTerm, /* Term to compare to */
119286 int nTerm /* Size of term zTerm in bytes */
119288 int res = 0;
119289 if( pSeg->aNode ){
119290 if( pSeg->nTerm>nTerm ){
119291 res = memcmp(pSeg->zTerm, zTerm, nTerm);
119292 }else{
119293 res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
119295 if( res==0 ){
119296 res = pSeg->nTerm-nTerm;
119299 return res;
119303 ** Argument apSegment is an array of nSegment elements. It is known that
119304 ** the final (nSegment-nSuspect) members are already in sorted order
119305 ** (according to the comparison function provided). This function shuffles
119306 ** the array around until all entries are in sorted order.
119308 static void fts3SegReaderSort(
119309 Fts3SegReader **apSegment, /* Array to sort entries of */
119310 int nSegment, /* Size of apSegment array */
119311 int nSuspect, /* Unsorted entry count */
119312 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
119314 int i; /* Iterator variable */
119316 assert( nSuspect<=nSegment );
119318 if( nSuspect==nSegment ) nSuspect--;
119319 for(i=nSuspect-1; i>=0; i--){
119320 int j;
119321 for(j=i; j<(nSegment-1); j++){
119322 Fts3SegReader *pTmp;
119323 if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
119324 pTmp = apSegment[j+1];
119325 apSegment[j+1] = apSegment[j];
119326 apSegment[j] = pTmp;
119330 #ifndef NDEBUG
119331 /* Check that the list really is sorted now. */
119332 for(i=0; i<(nSuspect-1); i++){
119333 assert( xCmp(apSegment[i], apSegment[i+1])<0 );
119335 #endif
119339 ** Insert a record into the %_segments table.
119341 static int fts3WriteSegment(
119342 Fts3Table *p, /* Virtual table handle */
119343 sqlite3_int64 iBlock, /* Block id for new block */
119344 char *z, /* Pointer to buffer containing block data */
119345 int n /* Size of buffer z in bytes */
119347 sqlite3_stmt *pStmt;
119348 int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
119349 if( rc==SQLITE_OK ){
119350 sqlite3_bind_int64(pStmt, 1, iBlock);
119351 sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
119352 sqlite3_step(pStmt);
119353 rc = sqlite3_reset(pStmt);
119355 return rc;
119359 ** Insert a record into the %_segdir table.
119361 static int fts3WriteSegdir(
119362 Fts3Table *p, /* Virtual table handle */
119363 int iLevel, /* Value for "level" field */
119364 int iIdx, /* Value for "idx" field */
119365 sqlite3_int64 iStartBlock, /* Value for "start_block" field */
119366 sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
119367 sqlite3_int64 iEndBlock, /* Value for "end_block" field */
119368 char *zRoot, /* Blob value for "root" field */
119369 int nRoot /* Number of bytes in buffer zRoot */
119371 sqlite3_stmt *pStmt;
119372 int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
119373 if( rc==SQLITE_OK ){
119374 sqlite3_bind_int(pStmt, 1, iLevel);
119375 sqlite3_bind_int(pStmt, 2, iIdx);
119376 sqlite3_bind_int64(pStmt, 3, iStartBlock);
119377 sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
119378 sqlite3_bind_int64(pStmt, 5, iEndBlock);
119379 sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
119380 sqlite3_step(pStmt);
119381 rc = sqlite3_reset(pStmt);
119383 return rc;
119387 ** Return the size of the common prefix (if any) shared by zPrev and
119388 ** zNext, in bytes. For example,
119390 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
119391 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
119392 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
119394 static int fts3PrefixCompress(
119395 const char *zPrev, /* Buffer containing previous term */
119396 int nPrev, /* Size of buffer zPrev in bytes */
119397 const char *zNext, /* Buffer containing next term */
119398 int nNext /* Size of buffer zNext in bytes */
119400 int n;
119401 UNUSED_PARAMETER(nNext);
119402 for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
119403 return n;
119407 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
119408 ** (according to memcmp) than the previous term.
119410 static int fts3NodeAddTerm(
119411 Fts3Table *p, /* Virtual table handle */
119412 SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
119413 int isCopyTerm, /* True if zTerm/nTerm is transient */
119414 const char *zTerm, /* Pointer to buffer containing term */
119415 int nTerm /* Size of term in bytes */
119417 SegmentNode *pTree = *ppTree;
119418 int rc;
119419 SegmentNode *pNew;
119421 /* First try to append the term to the current node. Return early if
119422 ** this is possible.
119424 if( pTree ){
119425 int nData = pTree->nData; /* Current size of node in bytes */
119426 int nReq = nData; /* Required space after adding zTerm */
119427 int nPrefix; /* Number of bytes of prefix compression */
119428 int nSuffix; /* Suffix length */
119430 nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
119431 nSuffix = nTerm-nPrefix;
119433 nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
119434 if( nReq<=p->nNodeSize || !pTree->zTerm ){
119436 if( nReq>p->nNodeSize ){
119437 /* An unusual case: this is the first term to be added to the node
119438 ** and the static node buffer (p->nNodeSize bytes) is not large
119439 ** enough. Use a separately malloced buffer instead This wastes
119440 ** p->nNodeSize bytes, but since this scenario only comes about when
119441 ** the database contain two terms that share a prefix of almost 2KB,
119442 ** this is not expected to be a serious problem.
119444 assert( pTree->aData==(char *)&pTree[1] );
119445 pTree->aData = (char *)sqlite3_malloc(nReq);
119446 if( !pTree->aData ){
119447 return SQLITE_NOMEM;
119451 if( pTree->zTerm ){
119452 /* There is no prefix-length field for first term in a node */
119453 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
119456 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
119457 memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
119458 pTree->nData = nData + nSuffix;
119459 pTree->nEntry++;
119461 if( isCopyTerm ){
119462 if( pTree->nMalloc<nTerm ){
119463 char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
119464 if( !zNew ){
119465 return SQLITE_NOMEM;
119467 pTree->nMalloc = nTerm*2;
119468 pTree->zMalloc = zNew;
119470 pTree->zTerm = pTree->zMalloc;
119471 memcpy(pTree->zTerm, zTerm, nTerm);
119472 pTree->nTerm = nTerm;
119473 }else{
119474 pTree->zTerm = (char *)zTerm;
119475 pTree->nTerm = nTerm;
119477 return SQLITE_OK;
119481 /* If control flows to here, it was not possible to append zTerm to the
119482 ** current node. Create a new node (a right-sibling of the current node).
119483 ** If this is the first node in the tree, the term is added to it.
119485 ** Otherwise, the term is not added to the new node, it is left empty for
119486 ** now. Instead, the term is inserted into the parent of pTree. If pTree
119487 ** has no parent, one is created here.
119489 pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
119490 if( !pNew ){
119491 return SQLITE_NOMEM;
119493 memset(pNew, 0, sizeof(SegmentNode));
119494 pNew->nData = 1 + FTS3_VARINT_MAX;
119495 pNew->aData = (char *)&pNew[1];
119497 if( pTree ){
119498 SegmentNode *pParent = pTree->pParent;
119499 rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
119500 if( pTree->pParent==0 ){
119501 pTree->pParent = pParent;
119503 pTree->pRight = pNew;
119504 pNew->pLeftmost = pTree->pLeftmost;
119505 pNew->pParent = pParent;
119506 pNew->zMalloc = pTree->zMalloc;
119507 pNew->nMalloc = pTree->nMalloc;
119508 pTree->zMalloc = 0;
119509 }else{
119510 pNew->pLeftmost = pNew;
119511 rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
119514 *ppTree = pNew;
119515 return rc;
119519 ** Helper function for fts3NodeWrite().
119521 static int fts3TreeFinishNode(
119522 SegmentNode *pTree,
119523 int iHeight,
119524 sqlite3_int64 iLeftChild
119526 int nStart;
119527 assert( iHeight>=1 && iHeight<128 );
119528 nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
119529 pTree->aData[nStart] = (char)iHeight;
119530 sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
119531 return nStart;
119535 ** Write the buffer for the segment node pTree and all of its peers to the
119536 ** database. Then call this function recursively to write the parent of
119537 ** pTree and its peers to the database.
119539 ** Except, if pTree is a root node, do not write it to the database. Instead,
119540 ** set output variables *paRoot and *pnRoot to contain the root node.
119542 ** If successful, SQLITE_OK is returned and output variable *piLast is
119543 ** set to the largest blockid written to the database (or zero if no
119544 ** blocks were written to the db). Otherwise, an SQLite error code is
119545 ** returned.
119547 static int fts3NodeWrite(
119548 Fts3Table *p, /* Virtual table handle */
119549 SegmentNode *pTree, /* SegmentNode handle */
119550 int iHeight, /* Height of this node in tree */
119551 sqlite3_int64 iLeaf, /* Block id of first leaf node */
119552 sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
119553 sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
119554 char **paRoot, /* OUT: Data for root node */
119555 int *pnRoot /* OUT: Size of root node in bytes */
119557 int rc = SQLITE_OK;
119559 if( !pTree->pParent ){
119560 /* Root node of the tree. */
119561 int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
119562 *piLast = iFree-1;
119563 *pnRoot = pTree->nData - nStart;
119564 *paRoot = &pTree->aData[nStart];
119565 }else{
119566 SegmentNode *pIter;
119567 sqlite3_int64 iNextFree = iFree;
119568 sqlite3_int64 iNextLeaf = iLeaf;
119569 for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
119570 int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
119571 int nWrite = pIter->nData - nStart;
119573 rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
119574 iNextFree++;
119575 iNextLeaf += (pIter->nEntry+1);
119577 if( rc==SQLITE_OK ){
119578 assert( iNextLeaf==iFree );
119579 rc = fts3NodeWrite(
119580 p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
119585 return rc;
119589 ** Free all memory allocations associated with the tree pTree.
119591 static void fts3NodeFree(SegmentNode *pTree){
119592 if( pTree ){
119593 SegmentNode *p = pTree->pLeftmost;
119594 fts3NodeFree(p->pParent);
119595 while( p ){
119596 SegmentNode *pRight = p->pRight;
119597 if( p->aData!=(char *)&p[1] ){
119598 sqlite3_free(p->aData);
119600 assert( pRight==0 || p->zMalloc==0 );
119601 sqlite3_free(p->zMalloc);
119602 sqlite3_free(p);
119603 p = pRight;
119609 ** Add a term to the segment being constructed by the SegmentWriter object
119610 ** *ppWriter. When adding the first term to a segment, *ppWriter should
119611 ** be passed NULL. This function will allocate a new SegmentWriter object
119612 ** and return it via the input/output variable *ppWriter in this case.
119614 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
119616 static int fts3SegWriterAdd(
119617 Fts3Table *p, /* Virtual table handle */
119618 SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
119619 int isCopyTerm, /* True if buffer zTerm must be copied */
119620 const char *zTerm, /* Pointer to buffer containing term */
119621 int nTerm, /* Size of term in bytes */
119622 const char *aDoclist, /* Pointer to buffer containing doclist */
119623 int nDoclist /* Size of doclist in bytes */
119625 int nPrefix; /* Size of term prefix in bytes */
119626 int nSuffix; /* Size of term suffix in bytes */
119627 int nReq; /* Number of bytes required on leaf page */
119628 int nData;
119629 SegmentWriter *pWriter = *ppWriter;
119631 if( !pWriter ){
119632 int rc;
119633 sqlite3_stmt *pStmt;
119635 /* Allocate the SegmentWriter structure */
119636 pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
119637 if( !pWriter ) return SQLITE_NOMEM;
119638 memset(pWriter, 0, sizeof(SegmentWriter));
119639 *ppWriter = pWriter;
119641 /* Allocate a buffer in which to accumulate data */
119642 pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
119643 if( !pWriter->aData ) return SQLITE_NOMEM;
119644 pWriter->nSize = p->nNodeSize;
119646 /* Find the next free blockid in the %_segments table */
119647 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
119648 if( rc!=SQLITE_OK ) return rc;
119649 if( SQLITE_ROW==sqlite3_step(pStmt) ){
119650 pWriter->iFree = sqlite3_column_int64(pStmt, 0);
119651 pWriter->iFirst = pWriter->iFree;
119653 rc = sqlite3_reset(pStmt);
119654 if( rc!=SQLITE_OK ) return rc;
119656 nData = pWriter->nData;
119658 nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
119659 nSuffix = nTerm-nPrefix;
119661 /* Figure out how many bytes are required by this new entry */
119662 nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
119663 sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
119664 nSuffix + /* Term suffix */
119665 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
119666 nDoclist; /* Doclist data */
119668 if( nData>0 && nData+nReq>p->nNodeSize ){
119669 int rc;
119671 /* The current leaf node is full. Write it out to the database. */
119672 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
119673 if( rc!=SQLITE_OK ) return rc;
119675 /* Add the current term to the interior node tree. The term added to
119676 ** the interior tree must:
119678 ** a) be greater than the largest term on the leaf node just written
119679 ** to the database (still available in pWriter->zTerm), and
119681 ** b) be less than or equal to the term about to be added to the new
119682 ** leaf node (zTerm/nTerm).
119684 ** In other words, it must be the prefix of zTerm 1 byte longer than
119685 ** the common prefix (if any) of zTerm and pWriter->zTerm.
119687 assert( nPrefix<nTerm );
119688 rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
119689 if( rc!=SQLITE_OK ) return rc;
119691 nData = 0;
119692 pWriter->nTerm = 0;
119694 nPrefix = 0;
119695 nSuffix = nTerm;
119696 nReq = 1 + /* varint containing prefix size */
119697 sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
119698 nTerm + /* Term suffix */
119699 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
119700 nDoclist; /* Doclist data */
119703 /* If the buffer currently allocated is too small for this entry, realloc
119704 ** the buffer to make it large enough.
119706 if( nReq>pWriter->nSize ){
119707 char *aNew = sqlite3_realloc(pWriter->aData, nReq);
119708 if( !aNew ) return SQLITE_NOMEM;
119709 pWriter->aData = aNew;
119710 pWriter->nSize = nReq;
119712 assert( nData+nReq<=pWriter->nSize );
119714 /* Append the prefix-compressed term and doclist to the buffer. */
119715 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
119716 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
119717 memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
119718 nData += nSuffix;
119719 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
119720 memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
119721 pWriter->nData = nData + nDoclist;
119723 /* Save the current term so that it can be used to prefix-compress the next.
119724 ** If the isCopyTerm parameter is true, then the buffer pointed to by
119725 ** zTerm is transient, so take a copy of the term data. Otherwise, just
119726 ** store a copy of the pointer.
119728 if( isCopyTerm ){
119729 if( nTerm>pWriter->nMalloc ){
119730 char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
119731 if( !zNew ){
119732 return SQLITE_NOMEM;
119734 pWriter->nMalloc = nTerm*2;
119735 pWriter->zMalloc = zNew;
119736 pWriter->zTerm = zNew;
119738 assert( pWriter->zTerm==pWriter->zMalloc );
119739 memcpy(pWriter->zTerm, zTerm, nTerm);
119740 }else{
119741 pWriter->zTerm = (char *)zTerm;
119743 pWriter->nTerm = nTerm;
119745 return SQLITE_OK;
119749 ** Flush all data associated with the SegmentWriter object pWriter to the
119750 ** database. This function must be called after all terms have been added
119751 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
119752 ** returned. Otherwise, an SQLite error code.
119754 static int fts3SegWriterFlush(
119755 Fts3Table *p, /* Virtual table handle */
119756 SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
119757 int iLevel, /* Value for 'level' column of %_segdir */
119758 int iIdx /* Value for 'idx' column of %_segdir */
119760 int rc; /* Return code */
119761 if( pWriter->pTree ){
119762 sqlite3_int64 iLast = 0; /* Largest block id written to database */
119763 sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
119764 char *zRoot = NULL; /* Pointer to buffer containing root node */
119765 int nRoot = 0; /* Size of buffer zRoot */
119767 iLastLeaf = pWriter->iFree;
119768 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
119769 if( rc==SQLITE_OK ){
119770 rc = fts3NodeWrite(p, pWriter->pTree, 1,
119771 pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
119773 if( rc==SQLITE_OK ){
119774 rc = fts3WriteSegdir(
119775 p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
119777 }else{
119778 /* The entire tree fits on the root node. Write it to the segdir table. */
119779 rc = fts3WriteSegdir(
119780 p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
119782 return rc;
119786 ** Release all memory held by the SegmentWriter object passed as the
119787 ** first argument.
119789 static void fts3SegWriterFree(SegmentWriter *pWriter){
119790 if( pWriter ){
119791 sqlite3_free(pWriter->aData);
119792 sqlite3_free(pWriter->zMalloc);
119793 fts3NodeFree(pWriter->pTree);
119794 sqlite3_free(pWriter);
119799 ** The first value in the apVal[] array is assumed to contain an integer.
119800 ** This function tests if there exist any documents with docid values that
119801 ** are different from that integer. i.e. if deleting the document with docid
119802 ** apVal[0] would mean the FTS3 table were empty.
119804 ** If successful, *pisEmpty is set to true if the table is empty except for
119805 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
119806 ** error occurs, an SQLite error code is returned.
119808 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
119809 sqlite3_stmt *pStmt;
119810 int rc;
119811 rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
119812 if( rc==SQLITE_OK ){
119813 if( SQLITE_ROW==sqlite3_step(pStmt) ){
119814 *pisEmpty = sqlite3_column_int(pStmt, 0);
119816 rc = sqlite3_reset(pStmt);
119818 return rc;
119822 ** Set *pnSegment to the total number of segments in the database. Set
119823 ** *pnMax to the largest segment level in the database (segment levels
119824 ** are stored in the 'level' column of the %_segdir table).
119826 ** Return SQLITE_OK if successful, or an SQLite error code if not.
119828 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
119829 sqlite3_stmt *pStmt;
119830 int rc;
119832 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
119833 if( rc!=SQLITE_OK ) return rc;
119834 if( SQLITE_ROW==sqlite3_step(pStmt) ){
119835 *pnSegment = sqlite3_column_int(pStmt, 0);
119836 *pnMax = sqlite3_column_int(pStmt, 1);
119838 return sqlite3_reset(pStmt);
119842 ** This function is used after merging multiple segments into a single large
119843 ** segment to delete the old, now redundant, segment b-trees. Specifically,
119844 ** it:
119846 ** 1) Deletes all %_segments entries for the segments associated with
119847 ** each of the SegReader objects in the array passed as the third
119848 ** argument, and
119850 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
119851 ** entries regardless of level if (iLevel<0).
119853 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
119855 static int fts3DeleteSegdir(
119856 Fts3Table *p, /* Virtual table handle */
119857 int iLevel, /* Level of %_segdir entries to delete */
119858 Fts3SegReader **apSegment, /* Array of SegReader objects */
119859 int nReader /* Size of array apSegment */
119861 int rc; /* Return Code */
119862 int i; /* Iterator variable */
119863 sqlite3_stmt *pDelete; /* SQL statement to delete rows */
119865 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
119866 for(i=0; rc==SQLITE_OK && i<nReader; i++){
119867 Fts3SegReader *pSegment = apSegment[i];
119868 if( pSegment->iStartBlock ){
119869 sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
119870 sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
119871 sqlite3_step(pDelete);
119872 rc = sqlite3_reset(pDelete);
119875 if( rc!=SQLITE_OK ){
119876 return rc;
119879 if( iLevel==FTS3_SEGCURSOR_ALL ){
119880 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
119881 }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
119882 sqlite3Fts3PendingTermsClear(p);
119883 }else{
119884 assert( iLevel>=0 );
119885 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
119886 if( rc==SQLITE_OK ){
119887 sqlite3_bind_int(pDelete, 1, iLevel);
119888 sqlite3_step(pDelete);
119889 rc = sqlite3_reset(pDelete);
119893 return rc;
119897 ** When this function is called, buffer *ppList (size *pnList bytes) contains
119898 ** a position list that may (or may not) feature multiple columns. This
119899 ** function adjusts the pointer *ppList and the length *pnList so that they
119900 ** identify the subset of the position list that corresponds to column iCol.
119902 ** If there are no entries in the input position list for column iCol, then
119903 ** *pnList is set to zero before returning.
119905 static void fts3ColumnFilter(
119906 int iCol, /* Column to filter on */
119907 char **ppList, /* IN/OUT: Pointer to position list */
119908 int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
119910 char *pList = *ppList;
119911 int nList = *pnList;
119912 char *pEnd = &pList[nList];
119913 int iCurrent = 0;
119914 char *p = pList;
119916 assert( iCol>=0 );
119917 while( 1 ){
119918 char c = 0;
119919 while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
119921 if( iCol==iCurrent ){
119922 nList = (int)(p - pList);
119923 break;
119926 nList -= (int)(p - pList);
119927 pList = p;
119928 if( nList==0 ){
119929 break;
119931 p = &pList[1];
119932 p += sqlite3Fts3GetVarint32(p, &iCurrent);
119935 *ppList = pList;
119936 *pnList = nList;
119939 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
119940 Fts3Table *p, /* Virtual table handle */
119941 Fts3SegReaderCursor *pCsr, /* Cursor object */
119942 Fts3SegFilter *pFilter /* Restrictions on range of iteration */
119944 int i;
119946 /* Initialize the cursor object */
119947 pCsr->pFilter = pFilter;
119949 /* If the Fts3SegFilter defines a specific term (or term prefix) to search
119950 ** for, then advance each segment iterator until it points to a term of
119951 ** equal or greater value than the specified term. This prevents many
119952 ** unnecessary merge/sort operations for the case where single segment
119953 ** b-tree leaf nodes contain more than one term.
119955 for(i=0; i<pCsr->nSegment; i++){
119956 int nTerm = pFilter->nTerm;
119957 const char *zTerm = pFilter->zTerm;
119958 Fts3SegReader *pSeg = pCsr->apSegment[i];
119960 int rc = fts3SegReaderNext(p, pSeg);
119961 if( rc!=SQLITE_OK ) return rc;
119962 }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
119964 fts3SegReaderSort(
119965 pCsr->apSegment, pCsr->nSegment, pCsr->nSegment, fts3SegReaderCmp);
119967 return SQLITE_OK;
119970 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
119971 Fts3Table *p, /* Virtual table handle */
119972 Fts3SegReaderCursor *pCsr /* Cursor object */
119974 int rc = SQLITE_OK;
119976 int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
119977 int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
119978 int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
119979 int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
119980 int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
119982 Fts3SegReader **apSegment = pCsr->apSegment;
119983 int nSegment = pCsr->nSegment;
119984 Fts3SegFilter *pFilter = pCsr->pFilter;
119986 if( pCsr->nSegment==0 ) return SQLITE_OK;
119989 int nMerge;
119990 int i;
119992 /* Advance the first pCsr->nAdvance entries in the apSegment[] array
119993 ** forward. Then sort the list in order of current term again.
119995 for(i=0; i<pCsr->nAdvance; i++){
119996 rc = fts3SegReaderNext(p, apSegment[i]);
119997 if( rc!=SQLITE_OK ) return rc;
119999 fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
120000 pCsr->nAdvance = 0;
120002 /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
120003 assert( rc==SQLITE_OK );
120004 if( apSegment[0]->aNode==0 ) break;
120006 pCsr->nTerm = apSegment[0]->nTerm;
120007 pCsr->zTerm = apSegment[0]->zTerm;
120009 /* If this is a prefix-search, and if the term that apSegment[0] points
120010 ** to does not share a suffix with pFilter->zTerm/nTerm, then all
120011 ** required callbacks have been made. In this case exit early.
120013 ** Similarly, if this is a search for an exact match, and the first term
120014 ** of segment apSegment[0] is not a match, exit early.
120016 if( pFilter->zTerm && !isScan ){
120017 if( pCsr->nTerm<pFilter->nTerm
120018 || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
120019 || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
120021 break;
120025 nMerge = 1;
120026 while( nMerge<nSegment
120027 && apSegment[nMerge]->aNode
120028 && apSegment[nMerge]->nTerm==pCsr->nTerm
120029 && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
120031 nMerge++;
120034 assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
120035 if( nMerge==1 && !isIgnoreEmpty ){
120036 pCsr->aDoclist = apSegment[0]->aDoclist;
120037 pCsr->nDoclist = apSegment[0]->nDoclist;
120038 rc = SQLITE_ROW;
120039 }else{
120040 int nDoclist = 0; /* Size of doclist */
120041 sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
120043 /* The current term of the first nMerge entries in the array
120044 ** of Fts3SegReader objects is the same. The doclists must be merged
120045 ** and a single term returned with the merged doclist.
120047 for(i=0; i<nMerge; i++){
120048 fts3SegReaderFirstDocid(apSegment[i]);
120050 fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
120051 while( apSegment[0]->pOffsetList ){
120052 int j; /* Number of segments that share a docid */
120053 char *pList;
120054 int nList;
120055 int nByte;
120056 sqlite3_int64 iDocid = apSegment[0]->iDocid;
120057 fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
120058 j = 1;
120059 while( j<nMerge
120060 && apSegment[j]->pOffsetList
120061 && apSegment[j]->iDocid==iDocid
120063 fts3SegReaderNextDocid(apSegment[j], 0, 0);
120067 if( isColFilter ){
120068 fts3ColumnFilter(pFilter->iCol, &pList, &nList);
120071 if( !isIgnoreEmpty || nList>0 ){
120072 nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
120073 if( nDoclist+nByte>pCsr->nBuffer ){
120074 char *aNew;
120075 pCsr->nBuffer = (nDoclist+nByte)*2;
120076 aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
120077 if( !aNew ){
120078 return SQLITE_NOMEM;
120080 pCsr->aBuffer = aNew;
120082 nDoclist += sqlite3Fts3PutVarint(
120083 &pCsr->aBuffer[nDoclist], iDocid-iPrev
120085 iPrev = iDocid;
120086 if( isRequirePos ){
120087 memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
120088 nDoclist += nList;
120089 pCsr->aBuffer[nDoclist++] = '\0';
120093 fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
120095 if( nDoclist>0 ){
120096 pCsr->aDoclist = pCsr->aBuffer;
120097 pCsr->nDoclist = nDoclist;
120098 rc = SQLITE_ROW;
120101 pCsr->nAdvance = nMerge;
120102 }while( rc==SQLITE_OK );
120104 return rc;
120107 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
120108 Fts3SegReaderCursor *pCsr /* Cursor object */
120110 if( pCsr ){
120111 int i;
120112 for(i=0; i<pCsr->nSegment; i++){
120113 sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
120115 sqlite3_free(pCsr->apSegment);
120116 sqlite3_free(pCsr->aBuffer);
120118 pCsr->nSegment = 0;
120119 pCsr->apSegment = 0;
120120 pCsr->aBuffer = 0;
120125 ** Merge all level iLevel segments in the database into a single
120126 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
120127 ** single segment with a level equal to the numerically largest level
120128 ** currently present in the database.
120130 ** If this function is called with iLevel<0, but there is only one
120131 ** segment in the database, SQLITE_DONE is returned immediately.
120132 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
120133 ** an SQLite error code is returned.
120135 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
120136 int rc; /* Return code */
120137 int iIdx = 0; /* Index of new segment */
120138 int iNewLevel = 0; /* Level to create new segment at */
120139 SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
120140 Fts3SegFilter filter; /* Segment term filter condition */
120141 Fts3SegReaderCursor csr; /* Cursor to iterate through level(s) */
120143 rc = sqlite3Fts3SegReaderCursor(p, iLevel, 0, 0, 1, 0, &csr);
120144 if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
120146 if( iLevel==FTS3_SEGCURSOR_ALL ){
120147 /* This call is to merge all segments in the database to a single
120148 ** segment. The level of the new segment is equal to the the numerically
120149 ** greatest segment level currently present in the database. The index
120150 ** of the new segment is always 0. */
120151 int nDummy; /* TODO: Remove this */
120152 if( csr.nSegment==1 ){
120153 rc = SQLITE_DONE;
120154 goto finished;
120156 rc = fts3SegmentCountMax(p, &nDummy, &iNewLevel);
120157 }else{
120158 /* This call is to merge all segments at level iLevel. Find the next
120159 ** available segment index at level iLevel+1. The call to
120160 ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
120161 ** a single iLevel+2 segment if necessary. */
120162 iNewLevel = iLevel+1;
120163 rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
120165 if( rc!=SQLITE_OK ) goto finished;
120166 assert( csr.nSegment>0 );
120167 assert( iNewLevel>=0 );
120169 memset(&filter, 0, sizeof(Fts3SegFilter));
120170 filter.flags = FTS3_SEGMENT_REQUIRE_POS;
120171 filter.flags |= (iLevel==FTS3_SEGCURSOR_ALL ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
120173 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
120174 while( SQLITE_OK==rc ){
120175 rc = sqlite3Fts3SegReaderStep(p, &csr);
120176 if( rc!=SQLITE_ROW ) break;
120177 rc = fts3SegWriterAdd(p, &pWriter, 1,
120178 csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
120180 if( rc!=SQLITE_OK ) goto finished;
120181 assert( pWriter );
120183 rc = fts3DeleteSegdir(p, iLevel, csr.apSegment, csr.nSegment);
120184 if( rc!=SQLITE_OK ) goto finished;
120185 rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
120187 finished:
120188 fts3SegWriterFree(pWriter);
120189 sqlite3Fts3SegReaderFinish(&csr);
120190 return rc;
120195 ** Flush the contents of pendingTerms to a level 0 segment.
120197 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
120198 return fts3SegmentMerge(p, FTS3_SEGCURSOR_PENDING);
120202 ** Encode N integers as varints into a blob.
120204 static void fts3EncodeIntArray(
120205 int N, /* The number of integers to encode */
120206 u32 *a, /* The integer values */
120207 char *zBuf, /* Write the BLOB here */
120208 int *pNBuf /* Write number of bytes if zBuf[] used here */
120210 int i, j;
120211 for(i=j=0; i<N; i++){
120212 j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
120214 *pNBuf = j;
120218 ** Decode a blob of varints into N integers
120220 static void fts3DecodeIntArray(
120221 int N, /* The number of integers to decode */
120222 u32 *a, /* Write the integer values */
120223 const char *zBuf, /* The BLOB containing the varints */
120224 int nBuf /* size of the BLOB */
120226 int i, j;
120227 UNUSED_PARAMETER(nBuf);
120228 for(i=j=0; i<N; i++){
120229 sqlite3_int64 x;
120230 j += sqlite3Fts3GetVarint(&zBuf[j], &x);
120231 assert(j<=nBuf);
120232 a[i] = (u32)(x & 0xffffffff);
120237 ** Insert the sizes (in tokens) for each column of the document
120238 ** with docid equal to p->iPrevDocid. The sizes are encoded as
120239 ** a blob of varints.
120241 static void fts3InsertDocsize(
120242 int *pRC, /* Result code */
120243 Fts3Table *p, /* Table into which to insert */
120244 u32 *aSz /* Sizes of each column */
120246 char *pBlob; /* The BLOB encoding of the document size */
120247 int nBlob; /* Number of bytes in the BLOB */
120248 sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
120249 int rc; /* Result code from subfunctions */
120251 if( *pRC ) return;
120252 pBlob = sqlite3_malloc( 10*p->nColumn );
120253 if( pBlob==0 ){
120254 *pRC = SQLITE_NOMEM;
120255 return;
120257 fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
120258 rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
120259 if( rc ){
120260 sqlite3_free(pBlob);
120261 *pRC = rc;
120262 return;
120264 sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
120265 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
120266 sqlite3_step(pStmt);
120267 *pRC = sqlite3_reset(pStmt);
120271 ** Record 0 of the %_stat table contains a blob consisting of N varints,
120272 ** where N is the number of user defined columns in the fts3 table plus
120273 ** two. If nCol is the number of user defined columns, then values of the
120274 ** varints are set as follows:
120276 ** Varint 0: Total number of rows in the table.
120278 ** Varint 1..nCol: For each column, the total number of tokens stored in
120279 ** the column for all rows of the table.
120281 ** Varint 1+nCol: The total size, in bytes, of all text values in all
120282 ** columns of all rows of the table.
120285 static void fts3UpdateDocTotals(
120286 int *pRC, /* The result code */
120287 Fts3Table *p, /* Table being updated */
120288 u32 *aSzIns, /* Size increases */
120289 u32 *aSzDel, /* Size decreases */
120290 int nChng /* Change in the number of documents */
120292 char *pBlob; /* Storage for BLOB written into %_stat */
120293 int nBlob; /* Size of BLOB written into %_stat */
120294 u32 *a; /* Array of integers that becomes the BLOB */
120295 sqlite3_stmt *pStmt; /* Statement for reading and writing */
120296 int i; /* Loop counter */
120297 int rc; /* Result code from subfunctions */
120299 const int nStat = p->nColumn+2;
120301 if( *pRC ) return;
120302 a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
120303 if( a==0 ){
120304 *pRC = SQLITE_NOMEM;
120305 return;
120307 pBlob = (char*)&a[nStat];
120308 rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
120309 if( rc ){
120310 sqlite3_free(a);
120311 *pRC = rc;
120312 return;
120314 if( sqlite3_step(pStmt)==SQLITE_ROW ){
120315 fts3DecodeIntArray(nStat, a,
120316 sqlite3_column_blob(pStmt, 0),
120317 sqlite3_column_bytes(pStmt, 0));
120318 }else{
120319 memset(a, 0, sizeof(u32)*(nStat) );
120321 sqlite3_reset(pStmt);
120322 if( nChng<0 && a[0]<(u32)(-nChng) ){
120323 a[0] = 0;
120324 }else{
120325 a[0] += nChng;
120327 for(i=0; i<p->nColumn+1; i++){
120328 u32 x = a[i+1];
120329 if( x+aSzIns[i] < aSzDel[i] ){
120330 x = 0;
120331 }else{
120332 x = x + aSzIns[i] - aSzDel[i];
120334 a[i+1] = x;
120336 fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
120337 rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
120338 if( rc ){
120339 sqlite3_free(a);
120340 *pRC = rc;
120341 return;
120343 sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
120344 sqlite3_step(pStmt);
120345 *pRC = sqlite3_reset(pStmt);
120346 sqlite3_free(a);
120350 ** Handle a 'special' INSERT of the form:
120352 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
120354 ** Argument pVal contains the result of <expr>. Currently the only
120355 ** meaningful value to insert is the text 'optimize'.
120357 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
120358 int rc; /* Return Code */
120359 const char *zVal = (const char *)sqlite3_value_text(pVal);
120360 int nVal = sqlite3_value_bytes(pVal);
120362 if( !zVal ){
120363 return SQLITE_NOMEM;
120364 }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
120365 rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
120366 if( rc==SQLITE_DONE ){
120367 rc = SQLITE_OK;
120368 }else{
120369 sqlite3Fts3PendingTermsClear(p);
120371 #ifdef SQLITE_TEST
120372 }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
120373 p->nNodeSize = atoi(&zVal[9]);
120374 rc = SQLITE_OK;
120375 }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
120376 p->nMaxPendingData = atoi(&zVal[11]);
120377 rc = SQLITE_OK;
120378 #endif
120379 }else{
120380 rc = SQLITE_ERROR;
120383 sqlite3Fts3SegmentsClose(p);
120384 return rc;
120388 ** Return the deferred doclist associated with deferred token pDeferred.
120389 ** This function assumes that sqlite3Fts3CacheDeferredDoclists() has already
120390 ** been called to allocate and populate the doclist.
120392 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *pDeferred, int *pnByte){
120393 if( pDeferred->pList ){
120394 *pnByte = pDeferred->pList->nData;
120395 return pDeferred->pList->aData;
120397 *pnByte = 0;
120398 return 0;
120402 ** Helper fucntion for FreeDeferredDoclists(). This function removes all
120403 ** references to deferred doclists from within the tree of Fts3Expr
120404 ** structures headed by
120406 static void fts3DeferredDoclistClear(Fts3Expr *pExpr){
120407 if( pExpr ){
120408 fts3DeferredDoclistClear(pExpr->pLeft);
120409 fts3DeferredDoclistClear(pExpr->pRight);
120410 if( pExpr->isLoaded ){
120411 sqlite3_free(pExpr->aDoclist);
120412 pExpr->isLoaded = 0;
120413 pExpr->aDoclist = 0;
120414 pExpr->nDoclist = 0;
120415 pExpr->pCurrent = 0;
120416 pExpr->iCurrent = 0;
120422 ** Delete all cached deferred doclists. Deferred doclists are cached
120423 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
120425 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
120426 Fts3DeferredToken *pDef;
120427 for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
120428 sqlite3_free(pDef->pList);
120429 pDef->pList = 0;
120431 if( pCsr->pDeferred ){
120432 fts3DeferredDoclistClear(pCsr->pExpr);
120437 ** Free all entries in the pCsr->pDeffered list. Entries are added to
120438 ** this list using sqlite3Fts3DeferToken().
120440 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
120441 Fts3DeferredToken *pDef;
120442 Fts3DeferredToken *pNext;
120443 for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
120444 pNext = pDef->pNext;
120445 sqlite3_free(pDef->pList);
120446 sqlite3_free(pDef);
120448 pCsr->pDeferred = 0;
120452 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
120453 ** based on the row that pCsr currently points to.
120455 ** A deferred-doclist is like any other doclist with position information
120456 ** included, except that it only contains entries for a single row of the
120457 ** table, not for all rows.
120459 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
120460 int rc = SQLITE_OK; /* Return code */
120461 if( pCsr->pDeferred ){
120462 int i; /* Used to iterate through table columns */
120463 sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
120464 Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
120466 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
120467 sqlite3_tokenizer *pT = p->pTokenizer;
120468 sqlite3_tokenizer_module const *pModule = pT->pModule;
120470 assert( pCsr->isRequireSeek==0 );
120471 iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
120473 for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
120474 const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
120475 sqlite3_tokenizer_cursor *pTC = 0;
120477 rc = pModule->xOpen(pT, zText, -1, &pTC);
120478 while( rc==SQLITE_OK ){
120479 char const *zToken; /* Buffer containing token */
120480 int nToken; /* Number of bytes in token */
120481 int iDum1, iDum2; /* Dummy variables */
120482 int iPos; /* Position of token in zText */
120484 pTC->pTokenizer = pT;
120485 rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
120486 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
120487 Fts3PhraseToken *pPT = pDef->pToken;
120488 if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
120489 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
120490 && (0==memcmp(zToken, pPT->z, pPT->n))
120492 fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
120496 if( pTC ) pModule->xClose(pTC);
120497 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
120500 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
120501 if( pDef->pList ){
120502 rc = fts3PendingListAppendVarint(&pDef->pList, 0);
120507 return rc;
120511 ** Add an entry for token pToken to the pCsr->pDeferred list.
120513 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
120514 Fts3Cursor *pCsr, /* Fts3 table cursor */
120515 Fts3PhraseToken *pToken, /* Token to defer */
120516 int iCol /* Column that token must appear in (or -1) */
120518 Fts3DeferredToken *pDeferred;
120519 pDeferred = sqlite3_malloc(sizeof(*pDeferred));
120520 if( !pDeferred ){
120521 return SQLITE_NOMEM;
120523 memset(pDeferred, 0, sizeof(*pDeferred));
120524 pDeferred->pToken = pToken;
120525 pDeferred->pNext = pCsr->pDeferred;
120526 pDeferred->iCol = iCol;
120527 pCsr->pDeferred = pDeferred;
120529 assert( pToken->pDeferred==0 );
120530 pToken->pDeferred = pDeferred;
120532 return SQLITE_OK;
120537 ** This function does the work for the xUpdate method of FTS3 virtual
120538 ** tables.
120540 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
120541 sqlite3_vtab *pVtab, /* FTS3 vtab object */
120542 int nArg, /* Size of argument array */
120543 sqlite3_value **apVal, /* Array of arguments */
120544 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
120546 Fts3Table *p = (Fts3Table *)pVtab;
120547 int rc = SQLITE_OK; /* Return Code */
120548 int isRemove = 0; /* True for an UPDATE or DELETE */
120549 sqlite3_int64 iRemove = 0; /* Rowid removed by UPDATE or DELETE */
120550 u32 *aSzIns; /* Sizes of inserted documents */
120551 u32 *aSzDel; /* Sizes of deleted documents */
120552 int nChng = 0; /* Net change in number of documents */
120554 assert( p->pSegments==0 );
120556 /* Allocate space to hold the change in document sizes */
120557 aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
120558 if( aSzIns==0 ) return SQLITE_NOMEM;
120559 aSzDel = &aSzIns[p->nColumn+1];
120560 memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
120562 /* If this is a DELETE or UPDATE operation, remove the old record. */
120563 if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
120564 int isEmpty = 0;
120565 rc = fts3IsEmpty(p, apVal, &isEmpty);
120566 if( rc==SQLITE_OK ){
120567 if( isEmpty ){
120568 /* Deleting this row means the whole table is empty. In this case
120569 ** delete the contents of all three tables and throw away any
120570 ** data in the pendingTerms hash table.
120572 rc = fts3DeleteAll(p);
120573 }else{
120574 isRemove = 1;
120575 iRemove = sqlite3_value_int64(apVal[0]);
120576 rc = fts3PendingTermsDocid(p, iRemove);
120577 fts3DeleteTerms(&rc, p, apVal, aSzDel);
120578 fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
120579 if( p->bHasDocsize ){
120580 fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
120582 nChng--;
120585 }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
120586 sqlite3_free(aSzIns);
120587 return fts3SpecialInsert(p, apVal[p->nColumn+2]);
120590 /* If this is an INSERT or UPDATE operation, insert the new record. */
120591 if( nArg>1 && rc==SQLITE_OK ){
120592 rc = fts3InsertData(p, apVal, pRowid);
120593 if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
120594 rc = fts3PendingTermsDocid(p, *pRowid);
120596 if( rc==SQLITE_OK ){
120597 rc = fts3InsertTerms(p, apVal, aSzIns);
120599 if( p->bHasDocsize ){
120600 fts3InsertDocsize(&rc, p, aSzIns);
120602 nChng++;
120605 if( p->bHasStat ){
120606 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
120609 sqlite3_free(aSzIns);
120610 sqlite3Fts3SegmentsClose(p);
120611 return rc;
120615 ** Flush any data in the pending-terms hash table to disk. If successful,
120616 ** merge all segments in the database (including the new segment, if
120617 ** there was any data to flush) into a single segment.
120619 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
120620 int rc;
120621 rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
120622 if( rc==SQLITE_OK ){
120623 rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
120624 if( rc==SQLITE_OK ){
120625 rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
120626 if( rc==SQLITE_OK ){
120627 sqlite3Fts3PendingTermsClear(p);
120629 }else{
120630 sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
120631 sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
120634 sqlite3Fts3SegmentsClose(p);
120635 return rc;
120638 #endif
120640 /************** End of fts3_write.c ******************************************/
120641 /************** Begin file fts3_snippet.c ************************************/
120643 ** 2009 Oct 23
120645 ** The author disclaims copyright to this source code. In place of
120646 ** a legal notice, here is a blessing:
120648 ** May you do good and not evil.
120649 ** May you find forgiveness for yourself and forgive others.
120650 ** May you share freely, never taking more than you give.
120652 ******************************************************************************
120655 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
120659 ** Characters that may appear in the second argument to matchinfo().
120661 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
120662 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
120663 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
120664 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
120665 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
120666 #define FTS3_MATCHINFO_LCS 's' /* nCol values */
120667 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
120670 ** The default value for the second argument to matchinfo().
120672 #define FTS3_MATCHINFO_DEFAULT "pcx"
120676 ** Used as an fts3ExprIterate() context when loading phrase doclists to
120677 ** Fts3Expr.aDoclist[]/nDoclist.
120679 typedef struct LoadDoclistCtx LoadDoclistCtx;
120680 struct LoadDoclistCtx {
120681 Fts3Cursor *pCsr; /* FTS3 Cursor */
120682 int nPhrase; /* Number of phrases seen so far */
120683 int nToken; /* Number of tokens seen so far */
120687 ** The following types are used as part of the implementation of the
120688 ** fts3BestSnippet() routine.
120690 typedef struct SnippetIter SnippetIter;
120691 typedef struct SnippetPhrase SnippetPhrase;
120692 typedef struct SnippetFragment SnippetFragment;
120694 struct SnippetIter {
120695 Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
120696 int iCol; /* Extract snippet from this column */
120697 int nSnippet; /* Requested snippet length (in tokens) */
120698 int nPhrase; /* Number of phrases in query */
120699 SnippetPhrase *aPhrase; /* Array of size nPhrase */
120700 int iCurrent; /* First token of current snippet */
120703 struct SnippetPhrase {
120704 int nToken; /* Number of tokens in phrase */
120705 char *pList; /* Pointer to start of phrase position list */
120706 int iHead; /* Next value in position list */
120707 char *pHead; /* Position list data following iHead */
120708 int iTail; /* Next value in trailing position list */
120709 char *pTail; /* Position list data following iTail */
120712 struct SnippetFragment {
120713 int iCol; /* Column snippet is extracted from */
120714 int iPos; /* Index of first token in snippet */
120715 u64 covered; /* Mask of query phrases covered */
120716 u64 hlmask; /* Mask of snippet terms to highlight */
120720 ** This type is used as an fts3ExprIterate() context object while
120721 ** accumulating the data returned by the matchinfo() function.
120723 typedef struct MatchInfo MatchInfo;
120724 struct MatchInfo {
120725 Fts3Cursor *pCursor; /* FTS3 Cursor */
120726 int nCol; /* Number of columns in table */
120727 int nPhrase; /* Number of matchable phrases in query */
120728 sqlite3_int64 nDoc; /* Number of docs in database */
120729 u32 *aMatchinfo; /* Pre-allocated buffer */
120735 ** The snippet() and offsets() functions both return text values. An instance
120736 ** of the following structure is used to accumulate those values while the
120737 ** functions are running. See fts3StringAppend() for details.
120739 typedef struct StrBuffer StrBuffer;
120740 struct StrBuffer {
120741 char *z; /* Pointer to buffer containing string */
120742 int n; /* Length of z in bytes (excl. nul-term) */
120743 int nAlloc; /* Allocated size of buffer z in bytes */
120748 ** This function is used to help iterate through a position-list. A position
120749 ** list is a list of unique integers, sorted from smallest to largest. Each
120750 ** element of the list is represented by an FTS3 varint that takes the value
120751 ** of the difference between the current element and the previous one plus
120752 ** two. For example, to store the position-list:
120754 ** 4 9 113
120756 ** the three varints:
120758 ** 6 7 106
120760 ** are encoded.
120762 ** When this function is called, *pp points to the start of an element of
120763 ** the list. *piPos contains the value of the previous entry in the list.
120764 ** After it returns, *piPos contains the value of the next element of the
120765 ** list and *pp is advanced to the following varint.
120767 static void fts3GetDeltaPosition(char **pp, int *piPos){
120768 int iVal;
120769 *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
120770 *piPos += (iVal-2);
120774 ** Helper function for fts3ExprIterate() (see below).
120776 static int fts3ExprIterate2(
120777 Fts3Expr *pExpr, /* Expression to iterate phrases of */
120778 int *piPhrase, /* Pointer to phrase counter */
120779 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
120780 void *pCtx /* Second argument to pass to callback */
120782 int rc; /* Return code */
120783 int eType = pExpr->eType; /* Type of expression node pExpr */
120785 if( eType!=FTSQUERY_PHRASE ){
120786 assert( pExpr->pLeft && pExpr->pRight );
120787 rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
120788 if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
120789 rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
120791 }else{
120792 rc = x(pExpr, *piPhrase, pCtx);
120793 (*piPhrase)++;
120795 return rc;
120799 ** Iterate through all phrase nodes in an FTS3 query, except those that
120800 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
120801 ** For each phrase node found, the supplied callback function is invoked.
120803 ** If the callback function returns anything other than SQLITE_OK,
120804 ** the iteration is abandoned and the error code returned immediately.
120805 ** Otherwise, SQLITE_OK is returned after a callback has been made for
120806 ** all eligible phrase nodes.
120808 static int fts3ExprIterate(
120809 Fts3Expr *pExpr, /* Expression to iterate phrases of */
120810 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
120811 void *pCtx /* Second argument to pass to callback */
120813 int iPhrase = 0; /* Variable used as the phrase counter */
120814 return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
120818 ** The argument to this function is always a phrase node. Its doclist
120819 ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
120820 ** to the left of this one in the query tree have already been loaded.
120822 ** If this phrase node is part of a series of phrase nodes joined by
120823 ** NEAR operators (and is not the left-most of said series), then elements are
120824 ** removed from the phrases doclist consistent with the NEAR restriction. If
120825 ** required, elements may be removed from the doclists of phrases to the
120826 ** left of this one that are part of the same series of NEAR operator
120827 ** connected phrases.
120829 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
120831 static int fts3ExprNearTrim(Fts3Expr *pExpr){
120832 int rc = SQLITE_OK;
120833 Fts3Expr *pParent = pExpr->pParent;
120835 assert( pExpr->eType==FTSQUERY_PHRASE );
120836 while( rc==SQLITE_OK
120837 && pParent
120838 && pParent->eType==FTSQUERY_NEAR
120839 && pParent->pRight==pExpr
120841 /* This expression (pExpr) is the right-hand-side of a NEAR operator.
120842 ** Find the expression to the left of the same operator.
120844 int nNear = pParent->nNear;
120845 Fts3Expr *pLeft = pParent->pLeft;
120847 if( pLeft->eType!=FTSQUERY_PHRASE ){
120848 assert( pLeft->eType==FTSQUERY_NEAR );
120849 assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
120850 pLeft = pLeft->pRight;
120853 rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
120855 pExpr = pLeft;
120856 pParent = pExpr->pParent;
120859 return rc;
120863 ** This is an fts3ExprIterate() callback used while loading the doclists
120864 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
120865 ** fts3ExprLoadDoclists().
120867 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
120868 int rc = SQLITE_OK;
120869 LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
120871 UNUSED_PARAMETER(iPhrase);
120873 p->nPhrase++;
120874 p->nToken += pExpr->pPhrase->nToken;
120876 if( pExpr->isLoaded==0 ){
120877 rc = sqlite3Fts3ExprLoadDoclist(p->pCsr, pExpr);
120878 pExpr->isLoaded = 1;
120879 if( rc==SQLITE_OK ){
120880 rc = fts3ExprNearTrim(pExpr);
120884 return rc;
120888 ** Load the doclists for each phrase in the query associated with FTS3 cursor
120889 ** pCsr.
120891 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
120892 ** phrases in the expression (all phrases except those directly or
120893 ** indirectly descended from the right-hand-side of a NOT operator). If
120894 ** pnToken is not NULL, then it is set to the number of tokens in all
120895 ** matchable phrases of the expression.
120897 static int fts3ExprLoadDoclists(
120898 Fts3Cursor *pCsr, /* Fts3 cursor for current query */
120899 int *pnPhrase, /* OUT: Number of phrases in query */
120900 int *pnToken /* OUT: Number of tokens in query */
120902 int rc; /* Return Code */
120903 LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
120904 sCtx.pCsr = pCsr;
120905 rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
120906 if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
120907 if( pnToken ) *pnToken = sCtx.nToken;
120908 return rc;
120911 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
120912 (*(int *)ctx)++;
120913 UNUSED_PARAMETER(pExpr);
120914 UNUSED_PARAMETER(iPhrase);
120915 return SQLITE_OK;
120917 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
120918 int nPhrase = 0;
120919 (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
120920 return nPhrase;
120924 ** Advance the position list iterator specified by the first two
120925 ** arguments so that it points to the first element with a value greater
120926 ** than or equal to parameter iNext.
120928 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
120929 char *pIter = *ppIter;
120930 if( pIter ){
120931 int iIter = *piIter;
120933 while( iIter<iNext ){
120934 if( 0==(*pIter & 0xFE) ){
120935 iIter = -1;
120936 pIter = 0;
120937 break;
120939 fts3GetDeltaPosition(&pIter, &iIter);
120942 *piIter = iIter;
120943 *ppIter = pIter;
120948 ** Advance the snippet iterator to the next candidate snippet.
120950 static int fts3SnippetNextCandidate(SnippetIter *pIter){
120951 int i; /* Loop counter */
120953 if( pIter->iCurrent<0 ){
120954 /* The SnippetIter object has just been initialized. The first snippet
120955 ** candidate always starts at offset 0 (even if this candidate has a
120956 ** score of 0.0).
120958 pIter->iCurrent = 0;
120960 /* Advance the 'head' iterator of each phrase to the first offset that
120961 ** is greater than or equal to (iNext+nSnippet).
120963 for(i=0; i<pIter->nPhrase; i++){
120964 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
120965 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
120967 }else{
120968 int iStart;
120969 int iEnd = 0x7FFFFFFF;
120971 for(i=0; i<pIter->nPhrase; i++){
120972 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
120973 if( pPhrase->pHead && pPhrase->iHead<iEnd ){
120974 iEnd = pPhrase->iHead;
120977 if( iEnd==0x7FFFFFFF ){
120978 return 1;
120981 pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
120982 for(i=0; i<pIter->nPhrase; i++){
120983 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
120984 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
120985 fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
120989 return 0;
120993 ** Retrieve information about the current candidate snippet of snippet
120994 ** iterator pIter.
120996 static void fts3SnippetDetails(
120997 SnippetIter *pIter, /* Snippet iterator */
120998 u64 mCovered, /* Bitmask of phrases already covered */
120999 int *piToken, /* OUT: First token of proposed snippet */
121000 int *piScore, /* OUT: "Score" for this snippet */
121001 u64 *pmCover, /* OUT: Bitmask of phrases covered */
121002 u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
121004 int iStart = pIter->iCurrent; /* First token of snippet */
121005 int iScore = 0; /* Score of this snippet */
121006 int i; /* Loop counter */
121007 u64 mCover = 0; /* Mask of phrases covered by this snippet */
121008 u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
121010 for(i=0; i<pIter->nPhrase; i++){
121011 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
121012 if( pPhrase->pTail ){
121013 char *pCsr = pPhrase->pTail;
121014 int iCsr = pPhrase->iTail;
121016 while( iCsr<(iStart+pIter->nSnippet) ){
121017 int j;
121018 u64 mPhrase = (u64)1 << i;
121019 u64 mPos = (u64)1 << (iCsr - iStart);
121020 assert( iCsr>=iStart );
121021 if( (mCover|mCovered)&mPhrase ){
121022 iScore++;
121023 }else{
121024 iScore += 1000;
121026 mCover |= mPhrase;
121028 for(j=0; j<pPhrase->nToken; j++){
121029 mHighlight |= (mPos>>j);
121032 if( 0==(*pCsr & 0x0FE) ) break;
121033 fts3GetDeltaPosition(&pCsr, &iCsr);
121038 /* Set the output variables before returning. */
121039 *piToken = iStart;
121040 *piScore = iScore;
121041 *pmCover = mCover;
121042 *pmHighlight = mHighlight;
121046 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
121047 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
121049 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
121050 SnippetIter *p = (SnippetIter *)ctx;
121051 SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
121052 char *pCsr;
121054 pPhrase->nToken = pExpr->pPhrase->nToken;
121056 pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
121057 if( pCsr ){
121058 int iFirst = 0;
121059 pPhrase->pList = pCsr;
121060 fts3GetDeltaPosition(&pCsr, &iFirst);
121061 pPhrase->pHead = pCsr;
121062 pPhrase->pTail = pCsr;
121063 pPhrase->iHead = iFirst;
121064 pPhrase->iTail = iFirst;
121065 }else{
121066 assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
121069 return SQLITE_OK;
121073 ** Select the fragment of text consisting of nFragment contiguous tokens
121074 ** from column iCol that represent the "best" snippet. The best snippet
121075 ** is the snippet with the highest score, where scores are calculated
121076 ** by adding:
121078 ** (a) +1 point for each occurence of a matchable phrase in the snippet.
121080 ** (b) +1000 points for the first occurence of each matchable phrase in
121081 ** the snippet for which the corresponding mCovered bit is not set.
121083 ** The selected snippet parameters are stored in structure *pFragment before
121084 ** returning. The score of the selected snippet is stored in *piScore
121085 ** before returning.
121087 static int fts3BestSnippet(
121088 int nSnippet, /* Desired snippet length */
121089 Fts3Cursor *pCsr, /* Cursor to create snippet for */
121090 int iCol, /* Index of column to create snippet from */
121091 u64 mCovered, /* Mask of phrases already covered */
121092 u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
121093 SnippetFragment *pFragment, /* OUT: Best snippet found */
121094 int *piScore /* OUT: Score of snippet pFragment */
121096 int rc; /* Return Code */
121097 int nList; /* Number of phrases in expression */
121098 SnippetIter sIter; /* Iterates through snippet candidates */
121099 int nByte; /* Number of bytes of space to allocate */
121100 int iBestScore = -1; /* Best snippet score found so far */
121101 int i; /* Loop counter */
121103 memset(&sIter, 0, sizeof(sIter));
121105 /* Iterate through the phrases in the expression to count them. The same
121106 ** callback makes sure the doclists are loaded for each phrase.
121108 rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
121109 if( rc!=SQLITE_OK ){
121110 return rc;
121113 /* Now that it is known how many phrases there are, allocate and zero
121114 ** the required space using malloc().
121116 nByte = sizeof(SnippetPhrase) * nList;
121117 sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
121118 if( !sIter.aPhrase ){
121119 return SQLITE_NOMEM;
121121 memset(sIter.aPhrase, 0, nByte);
121123 /* Initialize the contents of the SnippetIter object. Then iterate through
121124 ** the set of phrases in the expression to populate the aPhrase[] array.
121126 sIter.pCsr = pCsr;
121127 sIter.iCol = iCol;
121128 sIter.nSnippet = nSnippet;
121129 sIter.nPhrase = nList;
121130 sIter.iCurrent = -1;
121131 (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
121133 /* Set the *pmSeen output variable. */
121134 for(i=0; i<nList; i++){
121135 if( sIter.aPhrase[i].pHead ){
121136 *pmSeen |= (u64)1 << i;
121140 /* Loop through all candidate snippets. Store the best snippet in
121141 ** *pFragment. Store its associated 'score' in iBestScore.
121143 pFragment->iCol = iCol;
121144 while( !fts3SnippetNextCandidate(&sIter) ){
121145 int iPos;
121146 int iScore;
121147 u64 mCover;
121148 u64 mHighlight;
121149 fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
121150 assert( iScore>=0 );
121151 if( iScore>iBestScore ){
121152 pFragment->iPos = iPos;
121153 pFragment->hlmask = mHighlight;
121154 pFragment->covered = mCover;
121155 iBestScore = iScore;
121159 sqlite3_free(sIter.aPhrase);
121160 *piScore = iBestScore;
121161 return SQLITE_OK;
121166 ** Append a string to the string-buffer passed as the first argument.
121168 ** If nAppend is negative, then the length of the string zAppend is
121169 ** determined using strlen().
121171 static int fts3StringAppend(
121172 StrBuffer *pStr, /* Buffer to append to */
121173 const char *zAppend, /* Pointer to data to append to buffer */
121174 int nAppend /* Size of zAppend in bytes (or -1) */
121176 if( nAppend<0 ){
121177 nAppend = (int)strlen(zAppend);
121180 /* If there is insufficient space allocated at StrBuffer.z, use realloc()
121181 ** to grow the buffer until so that it is big enough to accomadate the
121182 ** appended data.
121184 if( pStr->n+nAppend+1>=pStr->nAlloc ){
121185 int nAlloc = pStr->nAlloc+nAppend+100;
121186 char *zNew = sqlite3_realloc(pStr->z, nAlloc);
121187 if( !zNew ){
121188 return SQLITE_NOMEM;
121190 pStr->z = zNew;
121191 pStr->nAlloc = nAlloc;
121194 /* Append the data to the string buffer. */
121195 memcpy(&pStr->z[pStr->n], zAppend, nAppend);
121196 pStr->n += nAppend;
121197 pStr->z[pStr->n] = '\0';
121199 return SQLITE_OK;
121203 ** The fts3BestSnippet() function often selects snippets that end with a
121204 ** query term. That is, the final term of the snippet is always a term
121205 ** that requires highlighting. For example, if 'X' is a highlighted term
121206 ** and '.' is a non-highlighted term, BestSnippet() may select:
121208 ** ........X.....X
121210 ** This function "shifts" the beginning of the snippet forward in the
121211 ** document so that there are approximately the same number of
121212 ** non-highlighted terms to the right of the final highlighted term as there
121213 ** are to the left of the first highlighted term. For example, to this:
121215 ** ....X.....X....
121217 ** This is done as part of extracting the snippet text, not when selecting
121218 ** the snippet. Snippet selection is done based on doclists only, so there
121219 ** is no way for fts3BestSnippet() to know whether or not the document
121220 ** actually contains terms that follow the final highlighted term.
121222 static int fts3SnippetShift(
121223 Fts3Table *pTab, /* FTS3 table snippet comes from */
121224 int nSnippet, /* Number of tokens desired for snippet */
121225 const char *zDoc, /* Document text to extract snippet from */
121226 int nDoc, /* Size of buffer zDoc in bytes */
121227 int *piPos, /* IN/OUT: First token of snippet */
121228 u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
121230 u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
121232 if( hlmask ){
121233 int nLeft; /* Tokens to the left of first highlight */
121234 int nRight; /* Tokens to the right of last highlight */
121235 int nDesired; /* Ideal number of tokens to shift forward */
121237 for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
121238 for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
121239 nDesired = (nLeft-nRight)/2;
121241 /* Ideally, the start of the snippet should be pushed forward in the
121242 ** document nDesired tokens. This block checks if there are actually
121243 ** nDesired tokens to the right of the snippet. If so, *piPos and
121244 ** *pHlMask are updated to shift the snippet nDesired tokens to the
121245 ** right. Otherwise, the snippet is shifted by the number of tokens
121246 ** available.
121248 if( nDesired>0 ){
121249 int nShift; /* Number of tokens to shift snippet by */
121250 int iCurrent = 0; /* Token counter */
121251 int rc; /* Return Code */
121252 sqlite3_tokenizer_module *pMod;
121253 sqlite3_tokenizer_cursor *pC;
121254 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
121256 /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
121257 ** or more tokens in zDoc/nDoc.
121259 rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
121260 if( rc!=SQLITE_OK ){
121261 return rc;
121263 pC->pTokenizer = pTab->pTokenizer;
121264 while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
121265 const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
121266 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
121268 pMod->xClose(pC);
121269 if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
121271 nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
121272 assert( nShift<=nDesired );
121273 if( nShift>0 ){
121274 *piPos += nShift;
121275 *pHlmask = hlmask >> nShift;
121279 return SQLITE_OK;
121283 ** Extract the snippet text for fragment pFragment from cursor pCsr and
121284 ** append it to string buffer pOut.
121286 static int fts3SnippetText(
121287 Fts3Cursor *pCsr, /* FTS3 Cursor */
121288 SnippetFragment *pFragment, /* Snippet to extract */
121289 int iFragment, /* Fragment number */
121290 int isLast, /* True for final fragment in snippet */
121291 int nSnippet, /* Number of tokens in extracted snippet */
121292 const char *zOpen, /* String inserted before highlighted term */
121293 const char *zClose, /* String inserted after highlighted term */
121294 const char *zEllipsis, /* String inserted between snippets */
121295 StrBuffer *pOut /* Write output here */
121297 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121298 int rc; /* Return code */
121299 const char *zDoc; /* Document text to extract snippet from */
121300 int nDoc; /* Size of zDoc in bytes */
121301 int iCurrent = 0; /* Current token number of document */
121302 int iEnd = 0; /* Byte offset of end of current token */
121303 int isShiftDone = 0; /* True after snippet is shifted */
121304 int iPos = pFragment->iPos; /* First token of snippet */
121305 u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
121306 int iCol = pFragment->iCol+1; /* Query column to extract text from */
121307 sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
121308 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
121309 const char *ZDUMMY; /* Dummy argument used with tokenizer */
121310 int DUMMY1; /* Dummy argument used with tokenizer */
121312 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
121313 if( zDoc==0 ){
121314 if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
121315 return SQLITE_NOMEM;
121317 return SQLITE_OK;
121319 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
121321 /* Open a token cursor on the document. */
121322 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
121323 rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
121324 if( rc!=SQLITE_OK ){
121325 return rc;
121327 pC->pTokenizer = pTab->pTokenizer;
121329 while( rc==SQLITE_OK ){
121330 int iBegin; /* Offset in zDoc of start of token */
121331 int iFin; /* Offset in zDoc of end of token */
121332 int isHighlight; /* True for highlighted terms */
121334 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
121335 if( rc!=SQLITE_OK ){
121336 if( rc==SQLITE_DONE ){
121337 /* Special case - the last token of the snippet is also the last token
121338 ** of the column. Append any punctuation that occurred between the end
121339 ** of the previous token and the end of the document to the output.
121340 ** Then break out of the loop. */
121341 rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
121343 break;
121345 if( iCurrent<iPos ){ continue; }
121347 if( !isShiftDone ){
121348 int n = nDoc - iBegin;
121349 rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
121350 isShiftDone = 1;
121352 /* Now that the shift has been done, check if the initial "..." are
121353 ** required. They are required if (a) this is not the first fragment,
121354 ** or (b) this fragment does not begin at position 0 of its column.
121356 if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
121357 rc = fts3StringAppend(pOut, zEllipsis, -1);
121359 if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
121362 if( iCurrent>=(iPos+nSnippet) ){
121363 if( isLast ){
121364 rc = fts3StringAppend(pOut, zEllipsis, -1);
121366 break;
121369 /* Set isHighlight to true if this term should be highlighted. */
121370 isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
121372 if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
121373 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
121374 if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
121375 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
121377 iEnd = iFin;
121380 pMod->xClose(pC);
121381 return rc;
121386 ** This function is used to count the entries in a column-list (a
121387 ** delta-encoded list of term offsets within a single column of a single
121388 ** row). When this function is called, *ppCollist should point to the
121389 ** beginning of the first varint in the column-list (the varint that
121390 ** contains the position of the first matching term in the column data).
121391 ** Before returning, *ppCollist is set to point to the first byte after
121392 ** the last varint in the column-list (either the 0x00 signifying the end
121393 ** of the position-list, or the 0x01 that precedes the column number of
121394 ** the next column in the position-list).
121396 ** The number of elements in the column-list is returned.
121398 static int fts3ColumnlistCount(char **ppCollist){
121399 char *pEnd = *ppCollist;
121400 char c = 0;
121401 int nEntry = 0;
121403 /* A column-list is terminated by either a 0x01 or 0x00. */
121404 while( 0xFE & (*pEnd | c) ){
121405 c = *pEnd++ & 0x80;
121406 if( !c ) nEntry++;
121409 *ppCollist = pEnd;
121410 return nEntry;
121413 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
121414 char *pCsr = *pp;
121415 while( *pCsr ){
121416 int nHit;
121417 sqlite3_int64 iCol = 0;
121418 if( *pCsr==0x01 ){
121419 pCsr++;
121420 pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
121422 nHit = fts3ColumnlistCount(&pCsr);
121423 assert( nHit>0 );
121424 if( isGlobal ){
121425 aOut[iCol*3+1]++;
121427 aOut[iCol*3] += nHit;
121429 pCsr++;
121430 *pp = pCsr;
121434 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
121435 ** for a single query.
121437 ** fts3ExprIterate() callback to load the 'global' elements of a
121438 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
121439 ** of the matchinfo array that are constant for all rows returned by the
121440 ** current query.
121442 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
121443 ** function populates Matchinfo.aMatchinfo[] as follows:
121445 ** for(iCol=0; iCol<nCol; iCol++){
121446 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
121447 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
121450 ** where X is the number of matches for phrase iPhrase is column iCol of all
121451 ** rows of the table. Y is the number of rows for which column iCol contains
121452 ** at least one instance of phrase iPhrase.
121454 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
121455 ** Y values are set to nDoc, where nDoc is the number of documents in the
121456 ** file system. This is done because the full-text index doclist is required
121457 ** to calculate these values properly, and the full-text index doclist is
121458 ** not available for deferred tokens.
121460 static int fts3ExprGlobalHitsCb(
121461 Fts3Expr *pExpr, /* Phrase expression node */
121462 int iPhrase, /* Phrase number (numbered from zero) */
121463 void *pCtx /* Pointer to MatchInfo structure */
121465 MatchInfo *p = (MatchInfo *)pCtx;
121466 Fts3Cursor *pCsr = p->pCursor;
121467 char *pIter;
121468 char *pEnd;
121469 char *pFree = 0;
121470 u32 *aOut = &p->aMatchinfo[3*iPhrase*p->nCol];
121472 assert( pExpr->isLoaded );
121473 assert( pExpr->eType==FTSQUERY_PHRASE );
121475 if( pCsr->pDeferred ){
121476 Fts3Phrase *pPhrase = pExpr->pPhrase;
121477 int ii;
121478 for(ii=0; ii<pPhrase->nToken; ii++){
121479 if( pPhrase->aToken[ii].bFulltext ) break;
121481 if( ii<pPhrase->nToken ){
121482 int nFree = 0;
121483 int rc = sqlite3Fts3ExprLoadFtDoclist(pCsr, pExpr, &pFree, &nFree);
121484 if( rc!=SQLITE_OK ) return rc;
121485 pIter = pFree;
121486 pEnd = &pFree[nFree];
121487 }else{
121488 int iCol; /* Column index */
121489 for(iCol=0; iCol<p->nCol; iCol++){
121490 aOut[iCol*3 + 1] = (u32)p->nDoc;
121491 aOut[iCol*3 + 2] = (u32)p->nDoc;
121493 return SQLITE_OK;
121495 }else{
121496 pIter = pExpr->aDoclist;
121497 pEnd = &pExpr->aDoclist[pExpr->nDoclist];
121500 /* Fill in the global hit count matrix row for this phrase. */
121501 while( pIter<pEnd ){
121502 while( *pIter++ & 0x80 ); /* Skip past docid. */
121503 fts3LoadColumnlistCounts(&pIter, &aOut[1], 1);
121506 sqlite3_free(pFree);
121507 return SQLITE_OK;
121511 ** fts3ExprIterate() callback used to collect the "local" part of the
121512 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
121513 ** array that are different for each row returned by the query.
121515 static int fts3ExprLocalHitsCb(
121516 Fts3Expr *pExpr, /* Phrase expression node */
121517 int iPhrase, /* Phrase number */
121518 void *pCtx /* Pointer to MatchInfo structure */
121520 MatchInfo *p = (MatchInfo *)pCtx;
121521 int iStart = iPhrase * p->nCol * 3;
121522 int i;
121524 for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
121526 if( pExpr->aDoclist ){
121527 char *pCsr;
121529 pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
121530 if( pCsr ){
121531 fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
121535 return SQLITE_OK;
121538 static int fts3MatchinfoCheck(
121539 Fts3Table *pTab,
121540 char cArg,
121541 char **pzErr
121543 if( (cArg==FTS3_MATCHINFO_NPHRASE)
121544 || (cArg==FTS3_MATCHINFO_NCOL)
121545 || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
121546 || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
121547 || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
121548 || (cArg==FTS3_MATCHINFO_LCS)
121549 || (cArg==FTS3_MATCHINFO_HITS)
121551 return SQLITE_OK;
121553 *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
121554 return SQLITE_ERROR;
121557 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
121558 int nVal; /* Number of integers output by cArg */
121560 switch( cArg ){
121561 case FTS3_MATCHINFO_NDOC:
121562 case FTS3_MATCHINFO_NPHRASE:
121563 case FTS3_MATCHINFO_NCOL:
121564 nVal = 1;
121565 break;
121567 case FTS3_MATCHINFO_AVGLENGTH:
121568 case FTS3_MATCHINFO_LENGTH:
121569 case FTS3_MATCHINFO_LCS:
121570 nVal = pInfo->nCol;
121571 break;
121573 default:
121574 assert( cArg==FTS3_MATCHINFO_HITS );
121575 nVal = pInfo->nCol * pInfo->nPhrase * 3;
121576 break;
121579 return nVal;
121582 static int fts3MatchinfoSelectDoctotal(
121583 Fts3Table *pTab,
121584 sqlite3_stmt **ppStmt,
121585 sqlite3_int64 *pnDoc,
121586 const char **paLen
121588 sqlite3_stmt *pStmt;
121589 const char *a;
121590 sqlite3_int64 nDoc;
121592 if( !*ppStmt ){
121593 int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
121594 if( rc!=SQLITE_OK ) return rc;
121596 pStmt = *ppStmt;
121597 assert( sqlite3_data_count(pStmt)==1 );
121599 a = sqlite3_column_blob(pStmt, 0);
121600 a += sqlite3Fts3GetVarint(a, &nDoc);
121601 if( nDoc==0 ) return SQLITE_CORRUPT;
121602 *pnDoc = (u32)nDoc;
121604 if( paLen ) *paLen = a;
121605 return SQLITE_OK;
121609 ** An instance of the following structure is used to store state while
121610 ** iterating through a multi-column position-list corresponding to the
121611 ** hits for a single phrase on a single row in order to calculate the
121612 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
121614 typedef struct LcsIterator LcsIterator;
121615 struct LcsIterator {
121616 Fts3Expr *pExpr; /* Pointer to phrase expression */
121617 char *pRead; /* Cursor used to iterate through aDoclist */
121618 int iPosOffset; /* Tokens count up to end of this phrase */
121619 int iCol; /* Current column number */
121620 int iPos; /* Current position */
121624 ** If LcsIterator.iCol is set to the following value, the iterator has
121625 ** finished iterating through all offsets for all columns.
121627 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
121629 static int fts3MatchinfoLcsCb(
121630 Fts3Expr *pExpr, /* Phrase expression node */
121631 int iPhrase, /* Phrase number (numbered from zero) */
121632 void *pCtx /* Pointer to MatchInfo structure */
121634 LcsIterator *aIter = (LcsIterator *)pCtx;
121635 aIter[iPhrase].pExpr = pExpr;
121636 return SQLITE_OK;
121640 ** Advance the iterator passed as an argument to the next position. Return
121641 ** 1 if the iterator is at EOF or if it now points to the start of the
121642 ** position list for the next column.
121644 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
121645 char *pRead = pIter->pRead;
121646 sqlite3_int64 iRead;
121647 int rc = 0;
121649 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
121650 if( iRead==0 ){
121651 pIter->iCol = LCS_ITERATOR_FINISHED;
121652 rc = 1;
121653 }else{
121654 if( iRead==1 ){
121655 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
121656 pIter->iCol = (int)iRead;
121657 pIter->iPos = pIter->iPosOffset;
121658 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
121659 rc = 1;
121661 pIter->iPos += (int)(iRead-2);
121664 pIter->pRead = pRead;
121665 return rc;
121669 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
121671 ** If the call is successful, the longest-common-substring lengths for each
121672 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
121673 ** array before returning. SQLITE_OK is returned in this case.
121675 ** Otherwise, if an error occurs, an SQLite error code is returned and the
121676 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
121677 ** undefined.
121679 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
121680 LcsIterator *aIter;
121681 int i;
121682 int iCol;
121683 int nToken = 0;
121685 /* Allocate and populate the array of LcsIterator objects. The array
121686 ** contains one element for each matchable phrase in the query.
121688 aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
121689 if( !aIter ) return SQLITE_NOMEM;
121690 memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
121691 (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
121692 for(i=0; i<pInfo->nPhrase; i++){
121693 LcsIterator *pIter = &aIter[i];
121694 nToken -= pIter->pExpr->pPhrase->nToken;
121695 pIter->iPosOffset = nToken;
121696 pIter->pRead = sqlite3Fts3FindPositions(pIter->pExpr, pCsr->iPrevId, -1);
121697 if( pIter->pRead ){
121698 pIter->iPos = pIter->iPosOffset;
121699 fts3LcsIteratorAdvance(&aIter[i]);
121700 }else{
121701 pIter->iCol = LCS_ITERATOR_FINISHED;
121705 for(iCol=0; iCol<pInfo->nCol; iCol++){
121706 int nLcs = 0; /* LCS value for this column */
121707 int nLive = 0; /* Number of iterators in aIter not at EOF */
121709 /* Loop through the iterators in aIter[]. Set nLive to the number of
121710 ** iterators that point to a position-list corresponding to column iCol.
121712 for(i=0; i<pInfo->nPhrase; i++){
121713 assert( aIter[i].iCol>=iCol );
121714 if( aIter[i].iCol==iCol ) nLive++;
121717 /* The following loop runs until all iterators in aIter[] have finished
121718 ** iterating through positions in column iCol. Exactly one of the
121719 ** iterators is advanced each time the body of the loop is run.
121721 while( nLive>0 ){
121722 LcsIterator *pAdv = 0; /* The iterator to advance by one position */
121723 int nThisLcs = 0; /* LCS for the current iterator positions */
121725 for(i=0; i<pInfo->nPhrase; i++){
121726 LcsIterator *pIter = &aIter[i];
121727 if( iCol!=pIter->iCol ){
121728 /* This iterator is already at EOF for this column. */
121729 nThisLcs = 0;
121730 }else{
121731 if( pAdv==0 || pIter->iPos<pAdv->iPos ){
121732 pAdv = pIter;
121734 if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
121735 nThisLcs++;
121736 }else{
121737 nThisLcs = 1;
121739 if( nThisLcs>nLcs ) nLcs = nThisLcs;
121742 if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
121745 pInfo->aMatchinfo[iCol] = nLcs;
121748 sqlite3_free(aIter);
121749 return SQLITE_OK;
121753 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
121754 ** be returned by the matchinfo() function. Argument zArg contains the
121755 ** format string passed as the second argument to matchinfo (or the
121756 ** default value "pcx" if no second argument was specified). The format
121757 ** string has already been validated and the pInfo->aMatchinfo[] array
121758 ** is guaranteed to be large enough for the output.
121760 ** If bGlobal is true, then populate all fields of the matchinfo() output.
121761 ** If it is false, then assume that those fields that do not change between
121762 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
121763 ** have already been populated.
121765 ** Return SQLITE_OK if successful, or an SQLite error code if an error
121766 ** occurs. If a value other than SQLITE_OK is returned, the state the
121767 ** pInfo->aMatchinfo[] buffer is left in is undefined.
121769 static int fts3MatchinfoValues(
121770 Fts3Cursor *pCsr, /* FTS3 cursor object */
121771 int bGlobal, /* True to grab the global stats */
121772 MatchInfo *pInfo, /* Matchinfo context object */
121773 const char *zArg /* Matchinfo format string */
121775 int rc = SQLITE_OK;
121776 int i;
121777 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121778 sqlite3_stmt *pSelect = 0;
121780 for(i=0; rc==SQLITE_OK && zArg[i]; i++){
121782 switch( zArg[i] ){
121783 case FTS3_MATCHINFO_NPHRASE:
121784 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
121785 break;
121787 case FTS3_MATCHINFO_NCOL:
121788 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
121789 break;
121791 case FTS3_MATCHINFO_NDOC:
121792 if( bGlobal ){
121793 sqlite3_int64 nDoc;
121794 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
121795 pInfo->aMatchinfo[0] = (u32)nDoc;
121797 break;
121799 case FTS3_MATCHINFO_AVGLENGTH:
121800 if( bGlobal ){
121801 sqlite3_int64 nDoc; /* Number of rows in table */
121802 const char *a; /* Aggregate column length array */
121804 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
121805 if( rc==SQLITE_OK ){
121806 int iCol;
121807 for(iCol=0; iCol<pInfo->nCol; iCol++){
121808 u32 iVal;
121809 sqlite3_int64 nToken;
121810 a += sqlite3Fts3GetVarint(a, &nToken);
121811 iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
121812 pInfo->aMatchinfo[iCol] = iVal;
121816 break;
121818 case FTS3_MATCHINFO_LENGTH: {
121819 sqlite3_stmt *pSelectDocsize = 0;
121820 rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
121821 if( rc==SQLITE_OK ){
121822 int iCol;
121823 const char *a = sqlite3_column_blob(pSelectDocsize, 0);
121824 for(iCol=0; iCol<pInfo->nCol; iCol++){
121825 sqlite3_int64 nToken;
121826 a += sqlite3Fts3GetVarint(a, &nToken);
121827 pInfo->aMatchinfo[iCol] = (u32)nToken;
121830 sqlite3_reset(pSelectDocsize);
121831 break;
121834 case FTS3_MATCHINFO_LCS:
121835 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
121836 if( rc==SQLITE_OK ){
121837 rc = fts3MatchinfoLcs(pCsr, pInfo);
121839 break;
121841 default: {
121842 Fts3Expr *pExpr;
121843 assert( zArg[i]==FTS3_MATCHINFO_HITS );
121844 pExpr = pCsr->pExpr;
121845 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
121846 if( rc!=SQLITE_OK ) break;
121847 if( bGlobal ){
121848 if( pCsr->pDeferred ){
121849 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
121850 if( rc!=SQLITE_OK ) break;
121852 rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
121853 if( rc!=SQLITE_OK ) break;
121855 (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
121856 break;
121860 pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
121863 sqlite3_reset(pSelect);
121864 return rc;
121869 ** Populate pCsr->aMatchinfo[] with data for the current row. The
121870 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
121872 static int fts3GetMatchinfo(
121873 Fts3Cursor *pCsr, /* FTS3 Cursor object */
121874 const char *zArg /* Second argument to matchinfo() function */
121876 MatchInfo sInfo;
121877 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121878 int rc = SQLITE_OK;
121879 int bGlobal = 0; /* Collect 'global' stats as well as local */
121881 memset(&sInfo, 0, sizeof(MatchInfo));
121882 sInfo.pCursor = pCsr;
121883 sInfo.nCol = pTab->nColumn;
121885 /* If there is cached matchinfo() data, but the format string for the
121886 ** cache does not match the format string for this request, discard
121887 ** the cached data. */
121888 if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
121889 assert( pCsr->aMatchinfo );
121890 sqlite3_free(pCsr->aMatchinfo);
121891 pCsr->zMatchinfo = 0;
121892 pCsr->aMatchinfo = 0;
121895 /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
121896 ** matchinfo function has been called for this query. In this case
121897 ** allocate the array used to accumulate the matchinfo data and
121898 ** initialize those elements that are constant for every row.
121900 if( pCsr->aMatchinfo==0 ){
121901 int nMatchinfo = 0; /* Number of u32 elements in match-info */
121902 int nArg; /* Bytes in zArg */
121903 int i; /* Used to iterate through zArg */
121905 /* Determine the number of phrases in the query */
121906 pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
121907 sInfo.nPhrase = pCsr->nPhrase;
121909 /* Determine the number of integers in the buffer returned by this call. */
121910 for(i=0; zArg[i]; i++){
121911 nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
121914 /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
121915 nArg = (int)strlen(zArg);
121916 pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
121917 if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
121919 pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
121920 pCsr->nMatchinfo = nMatchinfo;
121921 memcpy(pCsr->zMatchinfo, zArg, nArg+1);
121922 memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
121923 pCsr->isMatchinfoNeeded = 1;
121924 bGlobal = 1;
121927 sInfo.aMatchinfo = pCsr->aMatchinfo;
121928 sInfo.nPhrase = pCsr->nPhrase;
121929 if( pCsr->isMatchinfoNeeded ){
121930 rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
121931 pCsr->isMatchinfoNeeded = 0;
121934 return rc;
121938 ** Implementation of snippet() function.
121940 SQLITE_PRIVATE void sqlite3Fts3Snippet(
121941 sqlite3_context *pCtx, /* SQLite function call context */
121942 Fts3Cursor *pCsr, /* Cursor object */
121943 const char *zStart, /* Snippet start text - "<b>" */
121944 const char *zEnd, /* Snippet end text - "</b>" */
121945 const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
121946 int iCol, /* Extract snippet from this column */
121947 int nToken /* Approximate number of tokens in snippet */
121949 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121950 int rc = SQLITE_OK;
121951 int i;
121952 StrBuffer res = {0, 0, 0};
121954 /* The returned text includes up to four fragments of text extracted from
121955 ** the data in the current row. The first iteration of the for(...) loop
121956 ** below attempts to locate a single fragment of text nToken tokens in
121957 ** size that contains at least one instance of all phrases in the query
121958 ** expression that appear in the current row. If such a fragment of text
121959 ** cannot be found, the second iteration of the loop attempts to locate
121960 ** a pair of fragments, and so on.
121962 int nSnippet = 0; /* Number of fragments in this snippet */
121963 SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
121964 int nFToken = -1; /* Number of tokens in each fragment */
121966 if( !pCsr->pExpr ){
121967 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
121968 return;
121971 for(nSnippet=1; 1; nSnippet++){
121973 int iSnip; /* Loop counter 0..nSnippet-1 */
121974 u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
121975 u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
121977 if( nToken>=0 ){
121978 nFToken = (nToken+nSnippet-1) / nSnippet;
121979 }else{
121980 nFToken = -1 * nToken;
121983 for(iSnip=0; iSnip<nSnippet; iSnip++){
121984 int iBestScore = -1; /* Best score of columns checked so far */
121985 int iRead; /* Used to iterate through columns */
121986 SnippetFragment *pFragment = &aSnippet[iSnip];
121988 memset(pFragment, 0, sizeof(*pFragment));
121990 /* Loop through all columns of the table being considered for snippets.
121991 ** If the iCol argument to this function was negative, this means all
121992 ** columns of the FTS3 table. Otherwise, only column iCol is considered.
121994 for(iRead=0; iRead<pTab->nColumn; iRead++){
121995 SnippetFragment sF = {0, 0, 0, 0};
121996 int iS;
121997 if( iCol>=0 && iRead!=iCol ) continue;
121999 /* Find the best snippet of nFToken tokens in column iRead. */
122000 rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
122001 if( rc!=SQLITE_OK ){
122002 goto snippet_out;
122004 if( iS>iBestScore ){
122005 *pFragment = sF;
122006 iBestScore = iS;
122010 mCovered |= pFragment->covered;
122013 /* If all query phrases seen by fts3BestSnippet() are present in at least
122014 ** one of the nSnippet snippet fragments, break out of the loop.
122016 assert( (mCovered&mSeen)==mCovered );
122017 if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
122020 assert( nFToken>0 );
122022 for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
122023 rc = fts3SnippetText(pCsr, &aSnippet[i],
122024 i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
122028 snippet_out:
122029 sqlite3Fts3SegmentsClose(pTab);
122030 if( rc!=SQLITE_OK ){
122031 sqlite3_result_error_code(pCtx, rc);
122032 sqlite3_free(res.z);
122033 }else{
122034 sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
122039 typedef struct TermOffset TermOffset;
122040 typedef struct TermOffsetCtx TermOffsetCtx;
122042 struct TermOffset {
122043 char *pList; /* Position-list */
122044 int iPos; /* Position just read from pList */
122045 int iOff; /* Offset of this term from read positions */
122048 struct TermOffsetCtx {
122049 int iCol; /* Column of table to populate aTerm for */
122050 int iTerm;
122051 sqlite3_int64 iDocid;
122052 TermOffset *aTerm;
122056 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
122058 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
122059 TermOffsetCtx *p = (TermOffsetCtx *)ctx;
122060 int nTerm; /* Number of tokens in phrase */
122061 int iTerm; /* For looping through nTerm phrase terms */
122062 char *pList; /* Pointer to position list for phrase */
122063 int iPos = 0; /* First position in position-list */
122065 UNUSED_PARAMETER(iPhrase);
122066 pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
122067 nTerm = pExpr->pPhrase->nToken;
122068 if( pList ){
122069 fts3GetDeltaPosition(&pList, &iPos);
122070 assert( iPos>=0 );
122073 for(iTerm=0; iTerm<nTerm; iTerm++){
122074 TermOffset *pT = &p->aTerm[p->iTerm++];
122075 pT->iOff = nTerm-iTerm-1;
122076 pT->pList = pList;
122077 pT->iPos = iPos;
122080 return SQLITE_OK;
122084 ** Implementation of offsets() function.
122086 SQLITE_PRIVATE void sqlite3Fts3Offsets(
122087 sqlite3_context *pCtx, /* SQLite function call context */
122088 Fts3Cursor *pCsr /* Cursor object */
122090 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122091 sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
122092 const char *ZDUMMY; /* Dummy argument used with xNext() */
122093 int NDUMMY; /* Dummy argument used with xNext() */
122094 int rc; /* Return Code */
122095 int nToken; /* Number of tokens in query */
122096 int iCol; /* Column currently being processed */
122097 StrBuffer res = {0, 0, 0}; /* Result string */
122098 TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
122100 if( !pCsr->pExpr ){
122101 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
122102 return;
122105 memset(&sCtx, 0, sizeof(sCtx));
122106 assert( pCsr->isRequireSeek==0 );
122108 /* Count the number of terms in the query */
122109 rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
122110 if( rc!=SQLITE_OK ) goto offsets_out;
122112 /* Allocate the array of TermOffset iterators. */
122113 sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
122114 if( 0==sCtx.aTerm ){
122115 rc = SQLITE_NOMEM;
122116 goto offsets_out;
122118 sCtx.iDocid = pCsr->iPrevId;
122120 /* Loop through the table columns, appending offset information to
122121 ** string-buffer res for each column.
122123 for(iCol=0; iCol<pTab->nColumn; iCol++){
122124 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
122125 int iStart;
122126 int iEnd;
122127 int iCurrent;
122128 const char *zDoc;
122129 int nDoc;
122131 /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
122132 ** no way that this operation can fail, so the return code from
122133 ** fts3ExprIterate() can be discarded.
122135 sCtx.iCol = iCol;
122136 sCtx.iTerm = 0;
122137 (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
122139 /* Retreive the text stored in column iCol. If an SQL NULL is stored
122140 ** in column iCol, jump immediately to the next iteration of the loop.
122141 ** If an OOM occurs while retrieving the data (this can happen if SQLite
122142 ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
122143 ** to the caller.
122145 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
122146 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
122147 if( zDoc==0 ){
122148 if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
122149 continue;
122151 rc = SQLITE_NOMEM;
122152 goto offsets_out;
122155 /* Initialize a tokenizer iterator to iterate through column iCol. */
122156 rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
122157 if( rc!=SQLITE_OK ) goto offsets_out;
122158 pC->pTokenizer = pTab->pTokenizer;
122160 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
122161 while( rc==SQLITE_OK ){
122162 int i; /* Used to loop through terms */
122163 int iMinPos = 0x7FFFFFFF; /* Position of next token */
122164 TermOffset *pTerm = 0; /* TermOffset associated with next token */
122166 for(i=0; i<nToken; i++){
122167 TermOffset *pT = &sCtx.aTerm[i];
122168 if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
122169 iMinPos = pT->iPos-pT->iOff;
122170 pTerm = pT;
122174 if( !pTerm ){
122175 /* All offsets for this column have been gathered. */
122176 break;
122177 }else{
122178 assert( iCurrent<=iMinPos );
122179 if( 0==(0xFE&*pTerm->pList) ){
122180 pTerm->pList = 0;
122181 }else{
122182 fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
122184 while( rc==SQLITE_OK && iCurrent<iMinPos ){
122185 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
122187 if( rc==SQLITE_OK ){
122188 char aBuffer[64];
122189 sqlite3_snprintf(sizeof(aBuffer), aBuffer,
122190 "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
122192 rc = fts3StringAppend(&res, aBuffer, -1);
122193 }else if( rc==SQLITE_DONE ){
122194 rc = SQLITE_CORRUPT;
122198 if( rc==SQLITE_DONE ){
122199 rc = SQLITE_OK;
122202 pMod->xClose(pC);
122203 if( rc!=SQLITE_OK ) goto offsets_out;
122206 offsets_out:
122207 sqlite3_free(sCtx.aTerm);
122208 assert( rc!=SQLITE_DONE );
122209 sqlite3Fts3SegmentsClose(pTab);
122210 if( rc!=SQLITE_OK ){
122211 sqlite3_result_error_code(pCtx, rc);
122212 sqlite3_free(res.z);
122213 }else{
122214 sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
122216 return;
122220 ** Implementation of matchinfo() function.
122222 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
122223 sqlite3_context *pContext, /* Function call context */
122224 Fts3Cursor *pCsr, /* FTS3 table cursor */
122225 const char *zArg /* Second arg to matchinfo() function */
122227 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122228 int rc;
122229 int i;
122230 const char *zFormat;
122232 if( zArg ){
122233 for(i=0; zArg[i]; i++){
122234 char *zErr = 0;
122235 if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
122236 sqlite3_result_error(pContext, zErr, -1);
122237 sqlite3_free(zErr);
122238 return;
122241 zFormat = zArg;
122242 }else{
122243 zFormat = FTS3_MATCHINFO_DEFAULT;
122246 if( !pCsr->pExpr ){
122247 sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
122248 return;
122251 /* Retrieve matchinfo() data. */
122252 rc = fts3GetMatchinfo(pCsr, zFormat);
122253 sqlite3Fts3SegmentsClose(pTab);
122255 if( rc!=SQLITE_OK ){
122256 sqlite3_result_error_code(pContext, rc);
122257 }else{
122258 int n = pCsr->nMatchinfo * sizeof(u32);
122259 sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
122263 #endif
122265 /************** End of fts3_snippet.c ****************************************/
122266 /************** Begin file rtree.c *******************************************/
122268 ** 2001 September 15
122270 ** The author disclaims copyright to this source code. In place of
122271 ** a legal notice, here is a blessing:
122273 ** May you do good and not evil.
122274 ** May you find forgiveness for yourself and forgive others.
122275 ** May you share freely, never taking more than you give.
122277 *************************************************************************
122278 ** This file contains code for implementations of the r-tree and r*-tree
122279 ** algorithms packaged as an SQLite virtual table module.
122283 ** Database Format of R-Tree Tables
122284 ** --------------------------------
122286 ** The data structure for a single virtual r-tree table is stored in three
122287 ** native SQLite tables declared as follows. In each case, the '%' character
122288 ** in the table name is replaced with the user-supplied name of the r-tree
122289 ** table.
122291 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
122292 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
122293 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
122295 ** The data for each node of the r-tree structure is stored in the %_node
122296 ** table. For each node that is not the root node of the r-tree, there is
122297 ** an entry in the %_parent table associating the node with its parent.
122298 ** And for each row of data in the table, there is an entry in the %_rowid
122299 ** table that maps from the entries rowid to the id of the node that it
122300 ** is stored on.
122302 ** The root node of an r-tree always exists, even if the r-tree table is
122303 ** empty. The nodeno of the root node is always 1. All other nodes in the
122304 ** table must be the same size as the root node. The content of each node
122305 ** is formatted as follows:
122307 ** 1. If the node is the root node (node 1), then the first 2 bytes
122308 ** of the node contain the tree depth as a big-endian integer.
122309 ** For non-root nodes, the first 2 bytes are left unused.
122311 ** 2. The next 2 bytes contain the number of entries currently
122312 ** stored in the node.
122314 ** 3. The remainder of the node contains the node entries. Each entry
122315 ** consists of a single 8-byte integer followed by an even number
122316 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
122317 ** of a record. For internal nodes it is the node number of a
122318 ** child page.
122321 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
122324 ** This file contains an implementation of a couple of different variants
122325 ** of the r-tree algorithm. See the README file for further details. The
122326 ** same data-structure is used for all, but the algorithms for insert and
122327 ** delete operations vary. The variants used are selected at compile time
122328 ** by defining the following symbols:
122331 /* Either, both or none of the following may be set to activate
122332 ** r*tree variant algorithms.
122334 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
122335 #define VARIANT_RSTARTREE_REINSERT 1
122338 ** Exactly one of the following must be set to 1.
122340 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
122341 #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
122342 #define VARIANT_RSTARTREE_SPLIT 1
122344 #define VARIANT_GUTTMAN_SPLIT \
122345 (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
122347 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
122348 #define PickNext QuadraticPickNext
122349 #define PickSeeds QuadraticPickSeeds
122350 #define AssignCells splitNodeGuttman
122351 #endif
122352 #if VARIANT_GUTTMAN_LINEAR_SPLIT
122353 #define PickNext LinearPickNext
122354 #define PickSeeds LinearPickSeeds
122355 #define AssignCells splitNodeGuttman
122356 #endif
122357 #if VARIANT_RSTARTREE_SPLIT
122358 #define AssignCells splitNodeStartree
122359 #endif
122361 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
122362 # define NDEBUG 1
122363 #endif
122365 #ifndef SQLITE_CORE
122366 SQLITE_EXTENSION_INIT1
122367 #else
122368 #endif
122371 #ifndef SQLITE_AMALGAMATION
122372 #include "sqlite3rtree.h"
122373 typedef sqlite3_int64 i64;
122374 typedef unsigned char u8;
122375 typedef unsigned int u32;
122376 #endif
122378 /* The following macro is used to suppress compiler warnings.
122380 #ifndef UNUSED_PARAMETER
122381 # define UNUSED_PARAMETER(x) (void)(x)
122382 #endif
122384 typedef struct Rtree Rtree;
122385 typedef struct RtreeCursor RtreeCursor;
122386 typedef struct RtreeNode RtreeNode;
122387 typedef struct RtreeCell RtreeCell;
122388 typedef struct RtreeConstraint RtreeConstraint;
122389 typedef struct RtreeMatchArg RtreeMatchArg;
122390 typedef struct RtreeGeomCallback RtreeGeomCallback;
122391 typedef union RtreeCoord RtreeCoord;
122393 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
122394 #define RTREE_MAX_DIMENSIONS 5
122396 /* Size of hash table Rtree.aHash. This hash table is not expected to
122397 ** ever contain very many entries, so a fixed number of buckets is
122398 ** used.
122400 #define HASHSIZE 128
122403 ** An rtree virtual-table object.
122405 struct Rtree {
122406 sqlite3_vtab base;
122407 sqlite3 *db; /* Host database connection */
122408 int iNodeSize; /* Size in bytes of each node in the node table */
122409 int nDim; /* Number of dimensions */
122410 int nBytesPerCell; /* Bytes consumed per cell */
122411 int iDepth; /* Current depth of the r-tree structure */
122412 char *zDb; /* Name of database containing r-tree table */
122413 char *zName; /* Name of r-tree table */
122414 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
122415 int nBusy; /* Current number of users of this structure */
122417 /* List of nodes removed during a CondenseTree operation. List is
122418 ** linked together via the pointer normally used for hash chains -
122419 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
122420 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
122422 RtreeNode *pDeleted;
122423 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
122425 /* Statements to read/write/delete a record from xxx_node */
122426 sqlite3_stmt *pReadNode;
122427 sqlite3_stmt *pWriteNode;
122428 sqlite3_stmt *pDeleteNode;
122430 /* Statements to read/write/delete a record from xxx_rowid */
122431 sqlite3_stmt *pReadRowid;
122432 sqlite3_stmt *pWriteRowid;
122433 sqlite3_stmt *pDeleteRowid;
122435 /* Statements to read/write/delete a record from xxx_parent */
122436 sqlite3_stmt *pReadParent;
122437 sqlite3_stmt *pWriteParent;
122438 sqlite3_stmt *pDeleteParent;
122440 int eCoordType;
122443 /* Possible values for eCoordType: */
122444 #define RTREE_COORD_REAL32 0
122445 #define RTREE_COORD_INT32 1
122448 ** The minimum number of cells allowed for a node is a third of the
122449 ** maximum. In Gutman's notation:
122451 ** m = M/3
122453 ** If an R*-tree "Reinsert" operation is required, the same number of
122454 ** cells are removed from the overfull node and reinserted into the tree.
122456 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
122457 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
122458 #define RTREE_MAXCELLS 51
122461 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
122462 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
122463 ** Therefore all non-root nodes must contain at least 3 entries. Since
122464 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
122465 ** 40 or less.
122467 #define RTREE_MAX_DEPTH 40
122470 ** An rtree cursor object.
122472 struct RtreeCursor {
122473 sqlite3_vtab_cursor base;
122474 RtreeNode *pNode; /* Node cursor is currently pointing at */
122475 int iCell; /* Index of current cell in pNode */
122476 int iStrategy; /* Copy of idxNum search parameter */
122477 int nConstraint; /* Number of entries in aConstraint */
122478 RtreeConstraint *aConstraint; /* Search constraints. */
122481 union RtreeCoord {
122482 float f;
122483 int i;
122487 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
122488 ** formatted as a double. This macro assumes that local variable pRtree points
122489 ** to the Rtree structure associated with the RtreeCoord.
122491 #define DCOORD(coord) ( \
122492 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
122493 ((double)coord.f) : \
122494 ((double)coord.i) \
122498 ** A search constraint.
122500 struct RtreeConstraint {
122501 int iCoord; /* Index of constrained coordinate */
122502 int op; /* Constraining operation */
122503 double rValue; /* Constraint value. */
122504 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
122505 sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
122508 /* Possible values for RtreeConstraint.op */
122509 #define RTREE_EQ 0x41
122510 #define RTREE_LE 0x42
122511 #define RTREE_LT 0x43
122512 #define RTREE_GE 0x44
122513 #define RTREE_GT 0x45
122514 #define RTREE_MATCH 0x46
122517 ** An rtree structure node.
122519 struct RtreeNode {
122520 RtreeNode *pParent; /* Parent node */
122521 i64 iNode;
122522 int nRef;
122523 int isDirty;
122524 u8 *zData;
122525 RtreeNode *pNext; /* Next node in this hash chain */
122527 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
122530 ** Structure to store a deserialized rtree record.
122532 struct RtreeCell {
122533 i64 iRowid;
122534 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
122539 ** Value for the first field of every RtreeMatchArg object. The MATCH
122540 ** operator tests that the first field of a blob operand matches this
122541 ** value to avoid operating on invalid blobs (which could cause a segfault).
122543 #define RTREE_GEOMETRY_MAGIC 0x891245AB
122546 ** An instance of this structure must be supplied as a blob argument to
122547 ** the right-hand-side of an SQL MATCH operator used to constrain an
122548 ** r-tree query.
122550 struct RtreeMatchArg {
122551 u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
122552 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
122553 void *pContext;
122554 int nParam;
122555 double aParam[1];
122559 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
122560 ** a single instance of the following structure is allocated. It is used
122561 ** as the context for the user-function created by by s_r_g_c(). The object
122562 ** is eventually deleted by the destructor mechanism provided by
122563 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
122564 ** the geometry callback function).
122566 struct RtreeGeomCallback {
122567 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
122568 void *pContext;
122571 #ifndef MAX
122572 # define MAX(x,y) ((x) < (y) ? (y) : (x))
122573 #endif
122574 #ifndef MIN
122575 # define MIN(x,y) ((x) > (y) ? (y) : (x))
122576 #endif
122579 ** Functions to deserialize a 16 bit integer, 32 bit real number and
122580 ** 64 bit integer. The deserialized value is returned.
122582 static int readInt16(u8 *p){
122583 return (p[0]<<8) + p[1];
122585 static void readCoord(u8 *p, RtreeCoord *pCoord){
122586 u32 i = (
122587 (((u32)p[0]) << 24) +
122588 (((u32)p[1]) << 16) +
122589 (((u32)p[2]) << 8) +
122590 (((u32)p[3]) << 0)
122592 *(u32 *)pCoord = i;
122594 static i64 readInt64(u8 *p){
122595 return (
122596 (((i64)p[0]) << 56) +
122597 (((i64)p[1]) << 48) +
122598 (((i64)p[2]) << 40) +
122599 (((i64)p[3]) << 32) +
122600 (((i64)p[4]) << 24) +
122601 (((i64)p[5]) << 16) +
122602 (((i64)p[6]) << 8) +
122603 (((i64)p[7]) << 0)
122608 ** Functions to serialize a 16 bit integer, 32 bit real number and
122609 ** 64 bit integer. The value returned is the number of bytes written
122610 ** to the argument buffer (always 2, 4 and 8 respectively).
122612 static int writeInt16(u8 *p, int i){
122613 p[0] = (i>> 8)&0xFF;
122614 p[1] = (i>> 0)&0xFF;
122615 return 2;
122617 static int writeCoord(u8 *p, RtreeCoord *pCoord){
122618 u32 i;
122619 assert( sizeof(RtreeCoord)==4 );
122620 assert( sizeof(u32)==4 );
122621 i = *(u32 *)pCoord;
122622 p[0] = (i>>24)&0xFF;
122623 p[1] = (i>>16)&0xFF;
122624 p[2] = (i>> 8)&0xFF;
122625 p[3] = (i>> 0)&0xFF;
122626 return 4;
122628 static int writeInt64(u8 *p, i64 i){
122629 p[0] = (i>>56)&0xFF;
122630 p[1] = (i>>48)&0xFF;
122631 p[2] = (i>>40)&0xFF;
122632 p[3] = (i>>32)&0xFF;
122633 p[4] = (i>>24)&0xFF;
122634 p[5] = (i>>16)&0xFF;
122635 p[6] = (i>> 8)&0xFF;
122636 p[7] = (i>> 0)&0xFF;
122637 return 8;
122641 ** Increment the reference count of node p.
122643 static void nodeReference(RtreeNode *p){
122644 if( p ){
122645 p->nRef++;
122650 ** Clear the content of node p (set all bytes to 0x00).
122652 static void nodeZero(Rtree *pRtree, RtreeNode *p){
122653 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
122654 p->isDirty = 1;
122658 ** Given a node number iNode, return the corresponding key to use
122659 ** in the Rtree.aHash table.
122661 static int nodeHash(i64 iNode){
122662 return (
122663 (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
122664 (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
122665 ) % HASHSIZE;
122669 ** Search the node hash table for node iNode. If found, return a pointer
122670 ** to it. Otherwise, return 0.
122672 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
122673 RtreeNode *p;
122674 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
122675 return p;
122679 ** Add node pNode to the node hash table.
122681 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
122682 int iHash;
122683 assert( pNode->pNext==0 );
122684 iHash = nodeHash(pNode->iNode);
122685 pNode->pNext = pRtree->aHash[iHash];
122686 pRtree->aHash[iHash] = pNode;
122690 ** Remove node pNode from the node hash table.
122692 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
122693 RtreeNode **pp;
122694 if( pNode->iNode!=0 ){
122695 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
122696 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
122697 *pp = pNode->pNext;
122698 pNode->pNext = 0;
122703 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
122704 ** indicating that node has not yet been assigned a node number. It is
122705 ** assigned a node number when nodeWrite() is called to write the
122706 ** node contents out to the database.
122708 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
122709 RtreeNode *pNode;
122710 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
122711 if( pNode ){
122712 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
122713 pNode->zData = (u8 *)&pNode[1];
122714 pNode->nRef = 1;
122715 pNode->pParent = pParent;
122716 pNode->isDirty = 1;
122717 nodeReference(pParent);
122719 return pNode;
122723 ** Obtain a reference to an r-tree node.
122725 static int
122726 nodeAcquire(
122727 Rtree *pRtree, /* R-tree structure */
122728 i64 iNode, /* Node number to load */
122729 RtreeNode *pParent, /* Either the parent node or NULL */
122730 RtreeNode **ppNode /* OUT: Acquired node */
122732 int rc;
122733 int rc2 = SQLITE_OK;
122734 RtreeNode *pNode;
122736 /* Check if the requested node is already in the hash table. If so,
122737 ** increase its reference count and return it.
122739 if( (pNode = nodeHashLookup(pRtree, iNode)) ){
122740 assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
122741 if( pParent && !pNode->pParent ){
122742 nodeReference(pParent);
122743 pNode->pParent = pParent;
122745 pNode->nRef++;
122746 *ppNode = pNode;
122747 return SQLITE_OK;
122750 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
122751 rc = sqlite3_step(pRtree->pReadNode);
122752 if( rc==SQLITE_ROW ){
122753 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
122754 if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
122755 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
122756 if( !pNode ){
122757 rc2 = SQLITE_NOMEM;
122758 }else{
122759 pNode->pParent = pParent;
122760 pNode->zData = (u8 *)&pNode[1];
122761 pNode->nRef = 1;
122762 pNode->iNode = iNode;
122763 pNode->isDirty = 0;
122764 pNode->pNext = 0;
122765 memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
122766 nodeReference(pParent);
122770 rc = sqlite3_reset(pRtree->pReadNode);
122771 if( rc==SQLITE_OK ) rc = rc2;
122773 /* If the root node was just loaded, set pRtree->iDepth to the height
122774 ** of the r-tree structure. A height of zero means all data is stored on
122775 ** the root node. A height of one means the children of the root node
122776 ** are the leaves, and so on. If the depth as specified on the root node
122777 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
122779 if( pNode && iNode==1 ){
122780 pRtree->iDepth = readInt16(pNode->zData);
122781 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
122782 rc = SQLITE_CORRUPT;
122786 /* If no error has occurred so far, check if the "number of entries"
122787 ** field on the node is too large. If so, set the return code to
122788 ** SQLITE_CORRUPT.
122790 if( pNode && rc==SQLITE_OK ){
122791 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
122792 rc = SQLITE_CORRUPT;
122796 if( rc==SQLITE_OK ){
122797 if( pNode!=0 ){
122798 nodeHashInsert(pRtree, pNode);
122799 }else{
122800 rc = SQLITE_CORRUPT;
122802 *ppNode = pNode;
122803 }else{
122804 sqlite3_free(pNode);
122805 *ppNode = 0;
122808 return rc;
122812 ** Overwrite cell iCell of node pNode with the contents of pCell.
122814 static void nodeOverwriteCell(
122815 Rtree *pRtree,
122816 RtreeNode *pNode,
122817 RtreeCell *pCell,
122818 int iCell
122820 int ii;
122821 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
122822 p += writeInt64(p, pCell->iRowid);
122823 for(ii=0; ii<(pRtree->nDim*2); ii++){
122824 p += writeCoord(p, &pCell->aCoord[ii]);
122826 pNode->isDirty = 1;
122830 ** Remove cell the cell with index iCell from node pNode.
122832 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
122833 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
122834 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
122835 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
122836 memmove(pDst, pSrc, nByte);
122837 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
122838 pNode->isDirty = 1;
122842 ** Insert the contents of cell pCell into node pNode. If the insert
122843 ** is successful, return SQLITE_OK.
122845 ** If there is not enough free space in pNode, return SQLITE_FULL.
122847 static int
122848 nodeInsertCell(
122849 Rtree *pRtree,
122850 RtreeNode *pNode,
122851 RtreeCell *pCell
122853 int nCell; /* Current number of cells in pNode */
122854 int nMaxCell; /* Maximum number of cells for pNode */
122856 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
122857 nCell = NCELL(pNode);
122859 assert( nCell<=nMaxCell );
122860 if( nCell<nMaxCell ){
122861 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
122862 writeInt16(&pNode->zData[2], nCell+1);
122863 pNode->isDirty = 1;
122866 return (nCell==nMaxCell);
122870 ** If the node is dirty, write it out to the database.
122872 static int
122873 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
122874 int rc = SQLITE_OK;
122875 if( pNode->isDirty ){
122876 sqlite3_stmt *p = pRtree->pWriteNode;
122877 if( pNode->iNode ){
122878 sqlite3_bind_int64(p, 1, pNode->iNode);
122879 }else{
122880 sqlite3_bind_null(p, 1);
122882 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
122883 sqlite3_step(p);
122884 pNode->isDirty = 0;
122885 rc = sqlite3_reset(p);
122886 if( pNode->iNode==0 && rc==SQLITE_OK ){
122887 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
122888 nodeHashInsert(pRtree, pNode);
122891 return rc;
122895 ** Release a reference to a node. If the node is dirty and the reference
122896 ** count drops to zero, the node data is written to the database.
122898 static int
122899 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
122900 int rc = SQLITE_OK;
122901 if( pNode ){
122902 assert( pNode->nRef>0 );
122903 pNode->nRef--;
122904 if( pNode->nRef==0 ){
122905 if( pNode->iNode==1 ){
122906 pRtree->iDepth = -1;
122908 if( pNode->pParent ){
122909 rc = nodeRelease(pRtree, pNode->pParent);
122911 if( rc==SQLITE_OK ){
122912 rc = nodeWrite(pRtree, pNode);
122914 nodeHashDelete(pRtree, pNode);
122915 sqlite3_free(pNode);
122918 return rc;
122922 ** Return the 64-bit integer value associated with cell iCell of
122923 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
122924 ** an internal node, then the 64-bit integer is a child page number.
122926 static i64 nodeGetRowid(
122927 Rtree *pRtree,
122928 RtreeNode *pNode,
122929 int iCell
122931 assert( iCell<NCELL(pNode) );
122932 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
122936 ** Return coordinate iCoord from cell iCell in node pNode.
122938 static void nodeGetCoord(
122939 Rtree *pRtree,
122940 RtreeNode *pNode,
122941 int iCell,
122942 int iCoord,
122943 RtreeCoord *pCoord /* Space to write result to */
122945 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
122949 ** Deserialize cell iCell of node pNode. Populate the structure pointed
122950 ** to by pCell with the results.
122952 static void nodeGetCell(
122953 Rtree *pRtree,
122954 RtreeNode *pNode,
122955 int iCell,
122956 RtreeCell *pCell
122958 int ii;
122959 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
122960 for(ii=0; ii<pRtree->nDim*2; ii++){
122961 nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
122966 /* Forward declaration for the function that does the work of
122967 ** the virtual table module xCreate() and xConnect() methods.
122969 static int rtreeInit(
122970 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
122974 ** Rtree virtual table module xCreate method.
122976 static int rtreeCreate(
122977 sqlite3 *db,
122978 void *pAux,
122979 int argc, const char *const*argv,
122980 sqlite3_vtab **ppVtab,
122981 char **pzErr
122983 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
122987 ** Rtree virtual table module xConnect method.
122989 static int rtreeConnect(
122990 sqlite3 *db,
122991 void *pAux,
122992 int argc, const char *const*argv,
122993 sqlite3_vtab **ppVtab,
122994 char **pzErr
122996 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
123000 ** Increment the r-tree reference count.
123002 static void rtreeReference(Rtree *pRtree){
123003 pRtree->nBusy++;
123007 ** Decrement the r-tree reference count. When the reference count reaches
123008 ** zero the structure is deleted.
123010 static void rtreeRelease(Rtree *pRtree){
123011 pRtree->nBusy--;
123012 if( pRtree->nBusy==0 ){
123013 sqlite3_finalize(pRtree->pReadNode);
123014 sqlite3_finalize(pRtree->pWriteNode);
123015 sqlite3_finalize(pRtree->pDeleteNode);
123016 sqlite3_finalize(pRtree->pReadRowid);
123017 sqlite3_finalize(pRtree->pWriteRowid);
123018 sqlite3_finalize(pRtree->pDeleteRowid);
123019 sqlite3_finalize(pRtree->pReadParent);
123020 sqlite3_finalize(pRtree->pWriteParent);
123021 sqlite3_finalize(pRtree->pDeleteParent);
123022 sqlite3_free(pRtree);
123027 ** Rtree virtual table module xDisconnect method.
123029 static int rtreeDisconnect(sqlite3_vtab *pVtab){
123030 rtreeRelease((Rtree *)pVtab);
123031 return SQLITE_OK;
123035 ** Rtree virtual table module xDestroy method.
123037 static int rtreeDestroy(sqlite3_vtab *pVtab){
123038 Rtree *pRtree = (Rtree *)pVtab;
123039 int rc;
123040 char *zCreate = sqlite3_mprintf(
123041 "DROP TABLE '%q'.'%q_node';"
123042 "DROP TABLE '%q'.'%q_rowid';"
123043 "DROP TABLE '%q'.'%q_parent';",
123044 pRtree->zDb, pRtree->zName,
123045 pRtree->zDb, pRtree->zName,
123046 pRtree->zDb, pRtree->zName
123048 if( !zCreate ){
123049 rc = SQLITE_NOMEM;
123050 }else{
123051 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
123052 sqlite3_free(zCreate);
123054 if( rc==SQLITE_OK ){
123055 rtreeRelease(pRtree);
123058 return rc;
123062 ** Rtree virtual table module xOpen method.
123064 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
123065 int rc = SQLITE_NOMEM;
123066 RtreeCursor *pCsr;
123068 pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
123069 if( pCsr ){
123070 memset(pCsr, 0, sizeof(RtreeCursor));
123071 pCsr->base.pVtab = pVTab;
123072 rc = SQLITE_OK;
123074 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
123076 return rc;
123081 ** Free the RtreeCursor.aConstraint[] array and its contents.
123083 static void freeCursorConstraints(RtreeCursor *pCsr){
123084 if( pCsr->aConstraint ){
123085 int i; /* Used to iterate through constraint array */
123086 for(i=0; i<pCsr->nConstraint; i++){
123087 sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
123088 if( pGeom ){
123089 if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
123090 sqlite3_free(pGeom);
123093 sqlite3_free(pCsr->aConstraint);
123094 pCsr->aConstraint = 0;
123099 ** Rtree virtual table module xClose method.
123101 static int rtreeClose(sqlite3_vtab_cursor *cur){
123102 Rtree *pRtree = (Rtree *)(cur->pVtab);
123103 int rc;
123104 RtreeCursor *pCsr = (RtreeCursor *)cur;
123105 freeCursorConstraints(pCsr);
123106 rc = nodeRelease(pRtree, pCsr->pNode);
123107 sqlite3_free(pCsr);
123108 return rc;
123112 ** Rtree virtual table module xEof method.
123114 ** Return non-zero if the cursor does not currently point to a valid
123115 ** record (i.e if the scan has finished), or zero otherwise.
123117 static int rtreeEof(sqlite3_vtab_cursor *cur){
123118 RtreeCursor *pCsr = (RtreeCursor *)cur;
123119 return (pCsr->pNode==0);
123123 ** The r-tree constraint passed as the second argument to this function is
123124 ** guaranteed to be a MATCH constraint.
123126 static int testRtreeGeom(
123127 Rtree *pRtree, /* R-Tree object */
123128 RtreeConstraint *pConstraint, /* MATCH constraint to test */
123129 RtreeCell *pCell, /* Cell to test */
123130 int *pbRes /* OUT: Test result */
123132 int i;
123133 double aCoord[RTREE_MAX_DIMENSIONS*2];
123134 int nCoord = pRtree->nDim*2;
123136 assert( pConstraint->op==RTREE_MATCH );
123137 assert( pConstraint->pGeom );
123139 for(i=0; i<nCoord; i++){
123140 aCoord[i] = DCOORD(pCell->aCoord[i]);
123142 return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
123146 ** Cursor pCursor currently points to a cell in a non-leaf page.
123147 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
123148 ** (excluded) by the constraints in the pCursor->aConstraint[]
123149 ** array, or false otherwise.
123151 ** Return SQLITE_OK if successful or an SQLite error code if an error
123152 ** occurs within a geometry callback.
123154 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
123155 RtreeCell cell;
123156 int ii;
123157 int bRes = 0;
123158 int rc = SQLITE_OK;
123160 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
123161 for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
123162 RtreeConstraint *p = &pCursor->aConstraint[ii];
123163 double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
123164 double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
123166 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
123167 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
123170 switch( p->op ){
123171 case RTREE_LE: case RTREE_LT:
123172 bRes = p->rValue<cell_min;
123173 break;
123175 case RTREE_GE: case RTREE_GT:
123176 bRes = p->rValue>cell_max;
123177 break;
123179 case RTREE_EQ:
123180 bRes = (p->rValue>cell_max || p->rValue<cell_min);
123181 break;
123183 default: {
123184 assert( p->op==RTREE_MATCH );
123185 rc = testRtreeGeom(pRtree, p, &cell, &bRes);
123186 bRes = !bRes;
123187 break;
123192 *pbEof = bRes;
123193 return rc;
123197 ** Test if the cell that cursor pCursor currently points to
123198 ** would be filtered (excluded) by the constraints in the
123199 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
123200 ** returning. If the cell is not filtered (excluded) by the constraints,
123201 ** set pbEof to zero.
123203 ** Return SQLITE_OK if successful or an SQLite error code if an error
123204 ** occurs within a geometry callback.
123206 ** This function assumes that the cell is part of a leaf node.
123208 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
123209 RtreeCell cell;
123210 int ii;
123211 *pbEof = 0;
123213 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
123214 for(ii=0; ii<pCursor->nConstraint; ii++){
123215 RtreeConstraint *p = &pCursor->aConstraint[ii];
123216 double coord = DCOORD(cell.aCoord[p->iCoord]);
123217 int res;
123218 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
123219 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
123221 switch( p->op ){
123222 case RTREE_LE: res = (coord<=p->rValue); break;
123223 case RTREE_LT: res = (coord<p->rValue); break;
123224 case RTREE_GE: res = (coord>=p->rValue); break;
123225 case RTREE_GT: res = (coord>p->rValue); break;
123226 case RTREE_EQ: res = (coord==p->rValue); break;
123227 default: {
123228 int rc;
123229 assert( p->op==RTREE_MATCH );
123230 rc = testRtreeGeom(pRtree, p, &cell, &res);
123231 if( rc!=SQLITE_OK ){
123232 return rc;
123234 break;
123238 if( !res ){
123239 *pbEof = 1;
123240 return SQLITE_OK;
123244 return SQLITE_OK;
123248 ** Cursor pCursor currently points at a node that heads a sub-tree of
123249 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
123250 ** to point to the left-most cell of the sub-tree that matches the
123251 ** configured constraints.
123253 static int descendToCell(
123254 Rtree *pRtree,
123255 RtreeCursor *pCursor,
123256 int iHeight,
123257 int *pEof /* OUT: Set to true if cannot descend */
123259 int isEof;
123260 int rc;
123261 int ii;
123262 RtreeNode *pChild;
123263 sqlite3_int64 iRowid;
123265 RtreeNode *pSavedNode = pCursor->pNode;
123266 int iSavedCell = pCursor->iCell;
123268 assert( iHeight>=0 );
123270 if( iHeight==0 ){
123271 rc = testRtreeEntry(pRtree, pCursor, &isEof);
123272 }else{
123273 rc = testRtreeCell(pRtree, pCursor, &isEof);
123275 if( rc!=SQLITE_OK || isEof || iHeight==0 ){
123276 goto descend_to_cell_out;
123279 iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
123280 rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
123281 if( rc!=SQLITE_OK ){
123282 goto descend_to_cell_out;
123285 nodeRelease(pRtree, pCursor->pNode);
123286 pCursor->pNode = pChild;
123287 isEof = 1;
123288 for(ii=0; isEof && ii<NCELL(pChild); ii++){
123289 pCursor->iCell = ii;
123290 rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
123291 if( rc!=SQLITE_OK ){
123292 goto descend_to_cell_out;
123296 if( isEof ){
123297 assert( pCursor->pNode==pChild );
123298 nodeReference(pSavedNode);
123299 nodeRelease(pRtree, pChild);
123300 pCursor->pNode = pSavedNode;
123301 pCursor->iCell = iSavedCell;
123304 descend_to_cell_out:
123305 *pEof = isEof;
123306 return rc;
123310 ** One of the cells in node pNode is guaranteed to have a 64-bit
123311 ** integer value equal to iRowid. Return the index of this cell.
123313 static int nodeRowidIndex(
123314 Rtree *pRtree,
123315 RtreeNode *pNode,
123316 i64 iRowid,
123317 int *piIndex
123319 int ii;
123320 int nCell = NCELL(pNode);
123321 for(ii=0; ii<nCell; ii++){
123322 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
123323 *piIndex = ii;
123324 return SQLITE_OK;
123327 return SQLITE_CORRUPT;
123331 ** Return the index of the cell containing a pointer to node pNode
123332 ** in its parent. If pNode is the root node, return -1.
123334 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
123335 RtreeNode *pParent = pNode->pParent;
123336 if( pParent ){
123337 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
123339 *piIndex = -1;
123340 return SQLITE_OK;
123344 ** Rtree virtual table module xNext method.
123346 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
123347 Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
123348 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
123349 int rc = SQLITE_OK;
123351 /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
123352 ** already at EOF. It is against the rules to call the xNext() method of
123353 ** a cursor that has already reached EOF.
123355 assert( pCsr->pNode );
123357 if( pCsr->iStrategy==1 ){
123358 /* This "scan" is a direct lookup by rowid. There is no next entry. */
123359 nodeRelease(pRtree, pCsr->pNode);
123360 pCsr->pNode = 0;
123361 }else{
123362 /* Move to the next entry that matches the configured constraints. */
123363 int iHeight = 0;
123364 while( pCsr->pNode ){
123365 RtreeNode *pNode = pCsr->pNode;
123366 int nCell = NCELL(pNode);
123367 for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
123368 int isEof;
123369 rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
123370 if( rc!=SQLITE_OK || !isEof ){
123371 return rc;
123374 pCsr->pNode = pNode->pParent;
123375 rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
123376 if( rc!=SQLITE_OK ){
123377 return rc;
123379 nodeReference(pCsr->pNode);
123380 nodeRelease(pRtree, pNode);
123381 iHeight++;
123385 return rc;
123389 ** Rtree virtual table module xRowid method.
123391 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
123392 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
123393 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
123395 assert(pCsr->pNode);
123396 *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
123398 return SQLITE_OK;
123402 ** Rtree virtual table module xColumn method.
123404 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
123405 Rtree *pRtree = (Rtree *)cur->pVtab;
123406 RtreeCursor *pCsr = (RtreeCursor *)cur;
123408 if( i==0 ){
123409 i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
123410 sqlite3_result_int64(ctx, iRowid);
123411 }else{
123412 RtreeCoord c;
123413 nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
123414 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
123415 sqlite3_result_double(ctx, c.f);
123416 }else{
123417 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
123418 sqlite3_result_int(ctx, c.i);
123422 return SQLITE_OK;
123426 ** Use nodeAcquire() to obtain the leaf node containing the record with
123427 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
123428 ** return SQLITE_OK. If there is no such record in the table, set
123429 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
123430 ** to zero and return an SQLite error code.
123432 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
123433 int rc;
123434 *ppLeaf = 0;
123435 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
123436 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
123437 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
123438 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
123439 sqlite3_reset(pRtree->pReadRowid);
123440 }else{
123441 rc = sqlite3_reset(pRtree->pReadRowid);
123443 return rc;
123447 ** This function is called to configure the RtreeConstraint object passed
123448 ** as the second argument for a MATCH constraint. The value passed as the
123449 ** first argument to this function is the right-hand operand to the MATCH
123450 ** operator.
123452 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
123453 RtreeMatchArg *p;
123454 sqlite3_rtree_geometry *pGeom;
123455 int nBlob;
123457 /* Check that value is actually a blob. */
123458 if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
123460 /* Check that the blob is roughly the right size. */
123461 nBlob = sqlite3_value_bytes(pValue);
123462 if( nBlob<(int)sizeof(RtreeMatchArg)
123463 || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
123465 return SQLITE_ERROR;
123468 pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
123469 sizeof(sqlite3_rtree_geometry) + nBlob
123471 if( !pGeom ) return SQLITE_NOMEM;
123472 memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
123473 p = (RtreeMatchArg *)&pGeom[1];
123475 memcpy(p, sqlite3_value_blob(pValue), nBlob);
123476 if( p->magic!=RTREE_GEOMETRY_MAGIC
123477 || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
123479 sqlite3_free(pGeom);
123480 return SQLITE_ERROR;
123483 pGeom->pContext = p->pContext;
123484 pGeom->nParam = p->nParam;
123485 pGeom->aParam = p->aParam;
123487 pCons->xGeom = p->xGeom;
123488 pCons->pGeom = pGeom;
123489 return SQLITE_OK;
123493 ** Rtree virtual table module xFilter method.
123495 static int rtreeFilter(
123496 sqlite3_vtab_cursor *pVtabCursor,
123497 int idxNum, const char *idxStr,
123498 int argc, sqlite3_value **argv
123500 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
123501 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
123503 RtreeNode *pRoot = 0;
123504 int ii;
123505 int rc = SQLITE_OK;
123507 rtreeReference(pRtree);
123509 freeCursorConstraints(pCsr);
123510 pCsr->iStrategy = idxNum;
123512 if( idxNum==1 ){
123513 /* Special case - lookup by rowid. */
123514 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
123515 i64 iRowid = sqlite3_value_int64(argv[0]);
123516 rc = findLeafNode(pRtree, iRowid, &pLeaf);
123517 pCsr->pNode = pLeaf;
123518 if( pLeaf ){
123519 assert( rc==SQLITE_OK );
123520 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
123522 }else{
123523 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
123524 ** with the configured constraints.
123526 if( argc>0 ){
123527 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
123528 pCsr->nConstraint = argc;
123529 if( !pCsr->aConstraint ){
123530 rc = SQLITE_NOMEM;
123531 }else{
123532 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
123533 assert( (idxStr==0 && argc==0) || (int)strlen(idxStr)==argc*2 );
123534 for(ii=0; ii<argc; ii++){
123535 RtreeConstraint *p = &pCsr->aConstraint[ii];
123536 p->op = idxStr[ii*2];
123537 p->iCoord = idxStr[ii*2+1]-'a';
123538 if( p->op==RTREE_MATCH ){
123539 /* A MATCH operator. The right-hand-side must be a blob that
123540 ** can be cast into an RtreeMatchArg object. One created using
123541 ** an sqlite3_rtree_geometry_callback() SQL user function.
123543 rc = deserializeGeometry(argv[ii], p);
123544 if( rc!=SQLITE_OK ){
123545 break;
123547 }else{
123548 p->rValue = sqlite3_value_double(argv[ii]);
123554 if( rc==SQLITE_OK ){
123555 pCsr->pNode = 0;
123556 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
123558 if( rc==SQLITE_OK ){
123559 int isEof = 1;
123560 int nCell = NCELL(pRoot);
123561 pCsr->pNode = pRoot;
123562 for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
123563 assert( pCsr->pNode==pRoot );
123564 rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
123565 if( !isEof ){
123566 break;
123569 if( rc==SQLITE_OK && isEof ){
123570 assert( pCsr->pNode==pRoot );
123571 nodeRelease(pRtree, pRoot);
123572 pCsr->pNode = 0;
123574 assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
123578 rtreeRelease(pRtree);
123579 return rc;
123583 ** Rtree virtual table module xBestIndex method. There are three
123584 ** table scan strategies to choose from (in order from most to
123585 ** least desirable):
123587 ** idxNum idxStr Strategy
123588 ** ------------------------------------------------
123589 ** 1 Unused Direct lookup by rowid.
123590 ** 2 See below R-tree query or full-table scan.
123591 ** ------------------------------------------------
123593 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
123594 ** 2 is used, idxStr is formatted to contain 2 bytes for each
123595 ** constraint used. The first two bytes of idxStr correspond to
123596 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
123597 ** (argvIndex==1) etc.
123599 ** The first of each pair of bytes in idxStr identifies the constraint
123600 ** operator as follows:
123602 ** Operator Byte Value
123603 ** ----------------------
123604 ** = 0x41 ('A')
123605 ** <= 0x42 ('B')
123606 ** < 0x43 ('C')
123607 ** >= 0x44 ('D')
123608 ** > 0x45 ('E')
123609 ** MATCH 0x46 ('F')
123610 ** ----------------------
123612 ** The second of each pair of bytes identifies the coordinate column
123613 ** to which the constraint applies. The leftmost coordinate column
123614 ** is 'a', the second from the left 'b' etc.
123616 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
123617 int rc = SQLITE_OK;
123618 int ii;
123620 int iIdx = 0;
123621 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
123622 memset(zIdxStr, 0, sizeof(zIdxStr));
123623 UNUSED_PARAMETER(tab);
123625 assert( pIdxInfo->idxStr==0 );
123626 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
123627 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
123629 if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
123630 /* We have an equality constraint on the rowid. Use strategy 1. */
123631 int jj;
123632 for(jj=0; jj<ii; jj++){
123633 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
123634 pIdxInfo->aConstraintUsage[jj].omit = 0;
123636 pIdxInfo->idxNum = 1;
123637 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
123638 pIdxInfo->aConstraintUsage[jj].omit = 1;
123640 /* This strategy involves a two rowid lookups on an B-Tree structures
123641 ** and then a linear search of an R-Tree node. This should be
123642 ** considered almost as quick as a direct rowid lookup (for which
123643 ** sqlite uses an internal cost of 0.0).
123645 pIdxInfo->estimatedCost = 10.0;
123646 return SQLITE_OK;
123649 if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
123650 u8 op;
123651 switch( p->op ){
123652 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
123653 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
123654 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
123655 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
123656 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
123657 default:
123658 assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
123659 op = RTREE_MATCH;
123660 break;
123662 zIdxStr[iIdx++] = op;
123663 zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
123664 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
123665 pIdxInfo->aConstraintUsage[ii].omit = 1;
123669 pIdxInfo->idxNum = 2;
123670 pIdxInfo->needToFreeIdxStr = 1;
123671 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
123672 return SQLITE_NOMEM;
123674 assert( iIdx>=0 );
123675 pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
123676 return rc;
123680 ** Return the N-dimensional volumn of the cell stored in *p.
123682 static float cellArea(Rtree *pRtree, RtreeCell *p){
123683 float area = 1.0;
123684 int ii;
123685 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123686 area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
123688 return area;
123692 ** Return the margin length of cell p. The margin length is the sum
123693 ** of the objects size in each dimension.
123695 static float cellMargin(Rtree *pRtree, RtreeCell *p){
123696 float margin = 0.0;
123697 int ii;
123698 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123699 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
123701 return margin;
123705 ** Store the union of cells p1 and p2 in p1.
123707 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
123708 int ii;
123709 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
123710 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123711 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
123712 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
123714 }else{
123715 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123716 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
123717 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
123723 ** Return true if the area covered by p2 is a subset of the area covered
123724 ** by p1. False otherwise.
123726 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
123727 int ii;
123728 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
123729 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123730 RtreeCoord *a1 = &p1->aCoord[ii];
123731 RtreeCoord *a2 = &p2->aCoord[ii];
123732 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
123733 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
123735 return 0;
123738 return 1;
123742 ** Return the amount cell p would grow by if it were unioned with pCell.
123744 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
123745 float area;
123746 RtreeCell cell;
123747 memcpy(&cell, p, sizeof(RtreeCell));
123748 area = cellArea(pRtree, &cell);
123749 cellUnion(pRtree, &cell, pCell);
123750 return (cellArea(pRtree, &cell)-area);
123753 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
123754 static float cellOverlap(
123755 Rtree *pRtree,
123756 RtreeCell *p,
123757 RtreeCell *aCell,
123758 int nCell,
123759 int iExclude
123761 int ii;
123762 float overlap = 0.0;
123763 for(ii=0; ii<nCell; ii++){
123764 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123765 if( ii!=iExclude )
123766 #else
123767 assert( iExclude==-1 );
123768 UNUSED_PARAMETER(iExclude);
123769 #endif
123771 int jj;
123772 float o = 1.0;
123773 for(jj=0; jj<(pRtree->nDim*2); jj+=2){
123774 double x1;
123775 double x2;
123777 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
123778 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
123780 if( x2<x1 ){
123781 o = 0.0;
123782 break;
123783 }else{
123784 o = o * (x2-x1);
123787 overlap += o;
123790 return overlap;
123792 #endif
123794 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123795 static float cellOverlapEnlargement(
123796 Rtree *pRtree,
123797 RtreeCell *p,
123798 RtreeCell *pInsert,
123799 RtreeCell *aCell,
123800 int nCell,
123801 int iExclude
123803 float before;
123804 float after;
123805 before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
123806 cellUnion(pRtree, p, pInsert);
123807 after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
123808 return after-before;
123810 #endif
123814 ** This function implements the ChooseLeaf algorithm from Gutman[84].
123815 ** ChooseSubTree in r*tree terminology.
123817 static int ChooseLeaf(
123818 Rtree *pRtree, /* Rtree table */
123819 RtreeCell *pCell, /* Cell to insert into rtree */
123820 int iHeight, /* Height of sub-tree rooted at pCell */
123821 RtreeNode **ppLeaf /* OUT: Selected leaf page */
123823 int rc;
123824 int ii;
123825 RtreeNode *pNode;
123826 rc = nodeAcquire(pRtree, 1, 0, &pNode);
123828 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
123829 int iCell;
123830 sqlite3_int64 iBest;
123832 float fMinGrowth;
123833 float fMinArea;
123834 float fMinOverlap;
123836 int nCell = NCELL(pNode);
123837 RtreeCell cell;
123838 RtreeNode *pChild;
123840 RtreeCell *aCell = 0;
123842 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123843 if( ii==(pRtree->iDepth-1) ){
123844 int jj;
123845 aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
123846 if( !aCell ){
123847 rc = SQLITE_NOMEM;
123848 nodeRelease(pRtree, pNode);
123849 pNode = 0;
123850 continue;
123852 for(jj=0; jj<nCell; jj++){
123853 nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
123856 #endif
123858 /* Select the child node which will be enlarged the least if pCell
123859 ** is inserted into it. Resolve ties by choosing the entry with
123860 ** the smallest area.
123862 for(iCell=0; iCell<nCell; iCell++){
123863 int bBest = 0;
123864 float growth;
123865 float area;
123866 float overlap = 0.0;
123867 nodeGetCell(pRtree, pNode, iCell, &cell);
123868 growth = cellGrowth(pRtree, &cell, pCell);
123869 area = cellArea(pRtree, &cell);
123871 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123872 if( ii==(pRtree->iDepth-1) ){
123873 overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
123875 if( (iCell==0)
123876 || (overlap<fMinOverlap)
123877 || (overlap==fMinOverlap && growth<fMinGrowth)
123878 || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
123880 bBest = 1;
123882 #else
123883 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
123884 bBest = 1;
123886 #endif
123887 if( bBest ){
123888 fMinOverlap = overlap;
123889 fMinGrowth = growth;
123890 fMinArea = area;
123891 iBest = cell.iRowid;
123895 sqlite3_free(aCell);
123896 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
123897 nodeRelease(pRtree, pNode);
123898 pNode = pChild;
123901 *ppLeaf = pNode;
123902 return rc;
123906 ** A cell with the same content as pCell has just been inserted into
123907 ** the node pNode. This function updates the bounding box cells in
123908 ** all ancestor elements.
123910 static int AdjustTree(
123911 Rtree *pRtree, /* Rtree table */
123912 RtreeNode *pNode, /* Adjust ancestry of this node. */
123913 RtreeCell *pCell /* This cell was just inserted */
123915 RtreeNode *p = pNode;
123916 while( p->pParent ){
123917 RtreeNode *pParent = p->pParent;
123918 RtreeCell cell;
123919 int iCell;
123921 if( nodeParentIndex(pRtree, p, &iCell) ){
123922 return SQLITE_CORRUPT;
123925 nodeGetCell(pRtree, pParent, iCell, &cell);
123926 if( !cellContains(pRtree, &cell, pCell) ){
123927 cellUnion(pRtree, &cell, pCell);
123928 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
123931 p = pParent;
123933 return SQLITE_OK;
123937 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
123939 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
123940 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
123941 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
123942 sqlite3_step(pRtree->pWriteRowid);
123943 return sqlite3_reset(pRtree->pWriteRowid);
123947 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
123949 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
123950 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
123951 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
123952 sqlite3_step(pRtree->pWriteParent);
123953 return sqlite3_reset(pRtree->pWriteParent);
123956 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
123958 #if VARIANT_GUTTMAN_LINEAR_SPLIT
123960 ** Implementation of the linear variant of the PickNext() function from
123961 ** Guttman[84].
123963 static RtreeCell *LinearPickNext(
123964 Rtree *pRtree,
123965 RtreeCell *aCell,
123966 int nCell,
123967 RtreeCell *pLeftBox,
123968 RtreeCell *pRightBox,
123969 int *aiUsed
123971 int ii;
123972 for(ii=0; aiUsed[ii]; ii++);
123973 aiUsed[ii] = 1;
123974 return &aCell[ii];
123978 ** Implementation of the linear variant of the PickSeeds() function from
123979 ** Guttman[84].
123981 static void LinearPickSeeds(
123982 Rtree *pRtree,
123983 RtreeCell *aCell,
123984 int nCell,
123985 int *piLeftSeed,
123986 int *piRightSeed
123988 int i;
123989 int iLeftSeed = 0;
123990 int iRightSeed = 1;
123991 float maxNormalInnerWidth = 0.0;
123993 /* Pick two "seed" cells from the array of cells. The algorithm used
123994 ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
123995 ** indices of the two seed cells in the array are stored in local
123996 ** variables iLeftSeek and iRightSeed.
123998 for(i=0; i<pRtree->nDim; i++){
123999 float x1 = DCOORD(aCell[0].aCoord[i*2]);
124000 float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
124001 float x3 = x1;
124002 float x4 = x2;
124003 int jj;
124005 int iCellLeft = 0;
124006 int iCellRight = 0;
124008 for(jj=1; jj<nCell; jj++){
124009 float left = DCOORD(aCell[jj].aCoord[i*2]);
124010 float right = DCOORD(aCell[jj].aCoord[i*2+1]);
124012 if( left<x1 ) x1 = left;
124013 if( right>x4 ) x4 = right;
124014 if( left>x3 ){
124015 x3 = left;
124016 iCellRight = jj;
124018 if( right<x2 ){
124019 x2 = right;
124020 iCellLeft = jj;
124024 if( x4!=x1 ){
124025 float normalwidth = (x3 - x2) / (x4 - x1);
124026 if( normalwidth>maxNormalInnerWidth ){
124027 iLeftSeed = iCellLeft;
124028 iRightSeed = iCellRight;
124033 *piLeftSeed = iLeftSeed;
124034 *piRightSeed = iRightSeed;
124036 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
124038 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
124040 ** Implementation of the quadratic variant of the PickNext() function from
124041 ** Guttman[84].
124043 static RtreeCell *QuadraticPickNext(
124044 Rtree *pRtree,
124045 RtreeCell *aCell,
124046 int nCell,
124047 RtreeCell *pLeftBox,
124048 RtreeCell *pRightBox,
124049 int *aiUsed
124051 #define FABS(a) ((a)<0.0?-1.0*(a):(a))
124053 int iSelect = -1;
124054 float fDiff;
124055 int ii;
124056 for(ii=0; ii<nCell; ii++){
124057 if( aiUsed[ii]==0 ){
124058 float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
124059 float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
124060 float diff = FABS(right-left);
124061 if( iSelect<0 || diff>fDiff ){
124062 fDiff = diff;
124063 iSelect = ii;
124067 aiUsed[iSelect] = 1;
124068 return &aCell[iSelect];
124072 ** Implementation of the quadratic variant of the PickSeeds() function from
124073 ** Guttman[84].
124075 static void QuadraticPickSeeds(
124076 Rtree *pRtree,
124077 RtreeCell *aCell,
124078 int nCell,
124079 int *piLeftSeed,
124080 int *piRightSeed
124082 int ii;
124083 int jj;
124085 int iLeftSeed = 0;
124086 int iRightSeed = 1;
124087 float fWaste = 0.0;
124089 for(ii=0; ii<nCell; ii++){
124090 for(jj=ii+1; jj<nCell; jj++){
124091 float right = cellArea(pRtree, &aCell[jj]);
124092 float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
124093 float waste = growth - right;
124095 if( waste>fWaste ){
124096 iLeftSeed = ii;
124097 iRightSeed = jj;
124098 fWaste = waste;
124103 *piLeftSeed = iLeftSeed;
124104 *piRightSeed = iRightSeed;
124106 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
124109 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
124110 ** nIdx. The aIdx array contains the set of integers from 0 to
124111 ** (nIdx-1) in no particular order. This function sorts the values
124112 ** in aIdx according to the indexed values in aDistance. For
124113 ** example, assuming the inputs:
124115 ** aIdx = { 0, 1, 2, 3 }
124116 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
124118 ** this function sets the aIdx array to contain:
124120 ** aIdx = { 0, 1, 2, 3 }
124122 ** The aSpare array is used as temporary working space by the
124123 ** sorting algorithm.
124125 static void SortByDistance(
124126 int *aIdx,
124127 int nIdx,
124128 float *aDistance,
124129 int *aSpare
124131 if( nIdx>1 ){
124132 int iLeft = 0;
124133 int iRight = 0;
124135 int nLeft = nIdx/2;
124136 int nRight = nIdx-nLeft;
124137 int *aLeft = aIdx;
124138 int *aRight = &aIdx[nLeft];
124140 SortByDistance(aLeft, nLeft, aDistance, aSpare);
124141 SortByDistance(aRight, nRight, aDistance, aSpare);
124143 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
124144 aLeft = aSpare;
124146 while( iLeft<nLeft || iRight<nRight ){
124147 if( iLeft==nLeft ){
124148 aIdx[iLeft+iRight] = aRight[iRight];
124149 iRight++;
124150 }else if( iRight==nRight ){
124151 aIdx[iLeft+iRight] = aLeft[iLeft];
124152 iLeft++;
124153 }else{
124154 float fLeft = aDistance[aLeft[iLeft]];
124155 float fRight = aDistance[aRight[iRight]];
124156 if( fLeft<fRight ){
124157 aIdx[iLeft+iRight] = aLeft[iLeft];
124158 iLeft++;
124159 }else{
124160 aIdx[iLeft+iRight] = aRight[iRight];
124161 iRight++;
124166 #if 0
124167 /* Check that the sort worked */
124169 int jj;
124170 for(jj=1; jj<nIdx; jj++){
124171 float left = aDistance[aIdx[jj-1]];
124172 float right = aDistance[aIdx[jj]];
124173 assert( left<=right );
124176 #endif
124181 ** Arguments aIdx, aCell and aSpare all point to arrays of size
124182 ** nIdx. The aIdx array contains the set of integers from 0 to
124183 ** (nIdx-1) in no particular order. This function sorts the values
124184 ** in aIdx according to dimension iDim of the cells in aCell. The
124185 ** minimum value of dimension iDim is considered first, the
124186 ** maximum used to break ties.
124188 ** The aSpare array is used as temporary working space by the
124189 ** sorting algorithm.
124191 static void SortByDimension(
124192 Rtree *pRtree,
124193 int *aIdx,
124194 int nIdx,
124195 int iDim,
124196 RtreeCell *aCell,
124197 int *aSpare
124199 if( nIdx>1 ){
124201 int iLeft = 0;
124202 int iRight = 0;
124204 int nLeft = nIdx/2;
124205 int nRight = nIdx-nLeft;
124206 int *aLeft = aIdx;
124207 int *aRight = &aIdx[nLeft];
124209 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
124210 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
124212 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
124213 aLeft = aSpare;
124214 while( iLeft<nLeft || iRight<nRight ){
124215 double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
124216 double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
124217 double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
124218 double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
124219 if( (iLeft!=nLeft) && ((iRight==nRight)
124220 || (xleft1<xright1)
124221 || (xleft1==xright1 && xleft2<xright2)
124223 aIdx[iLeft+iRight] = aLeft[iLeft];
124224 iLeft++;
124225 }else{
124226 aIdx[iLeft+iRight] = aRight[iRight];
124227 iRight++;
124231 #if 0
124232 /* Check that the sort worked */
124234 int jj;
124235 for(jj=1; jj<nIdx; jj++){
124236 float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
124237 float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
124238 float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
124239 float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
124240 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
124243 #endif
124247 #if VARIANT_RSTARTREE_SPLIT
124249 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
124251 static int splitNodeStartree(
124252 Rtree *pRtree,
124253 RtreeCell *aCell,
124254 int nCell,
124255 RtreeNode *pLeft,
124256 RtreeNode *pRight,
124257 RtreeCell *pBboxLeft,
124258 RtreeCell *pBboxRight
124260 int **aaSorted;
124261 int *aSpare;
124262 int ii;
124264 int iBestDim;
124265 int iBestSplit;
124266 float fBestMargin;
124268 int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
124270 aaSorted = (int **)sqlite3_malloc(nByte);
124271 if( !aaSorted ){
124272 return SQLITE_NOMEM;
124275 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
124276 memset(aaSorted, 0, nByte);
124277 for(ii=0; ii<pRtree->nDim; ii++){
124278 int jj;
124279 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
124280 for(jj=0; jj<nCell; jj++){
124281 aaSorted[ii][jj] = jj;
124283 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
124286 for(ii=0; ii<pRtree->nDim; ii++){
124287 float margin = 0.0;
124288 float fBestOverlap;
124289 float fBestArea;
124290 int iBestLeft;
124291 int nLeft;
124294 nLeft=RTREE_MINCELLS(pRtree);
124295 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
124296 nLeft++
124298 RtreeCell left;
124299 RtreeCell right;
124300 int kk;
124301 float overlap;
124302 float area;
124304 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
124305 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
124306 for(kk=1; kk<(nCell-1); kk++){
124307 if( kk<nLeft ){
124308 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
124309 }else{
124310 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
124313 margin += cellMargin(pRtree, &left);
124314 margin += cellMargin(pRtree, &right);
124315 overlap = cellOverlap(pRtree, &left, &right, 1, -1);
124316 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
124317 if( (nLeft==RTREE_MINCELLS(pRtree))
124318 || (overlap<fBestOverlap)
124319 || (overlap==fBestOverlap && area<fBestArea)
124321 iBestLeft = nLeft;
124322 fBestOverlap = overlap;
124323 fBestArea = area;
124327 if( ii==0 || margin<fBestMargin ){
124328 iBestDim = ii;
124329 fBestMargin = margin;
124330 iBestSplit = iBestLeft;
124334 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
124335 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
124336 for(ii=0; ii<nCell; ii++){
124337 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
124338 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
124339 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
124340 nodeInsertCell(pRtree, pTarget, pCell);
124341 cellUnion(pRtree, pBbox, pCell);
124344 sqlite3_free(aaSorted);
124345 return SQLITE_OK;
124347 #endif
124349 #if VARIANT_GUTTMAN_SPLIT
124351 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
124353 static int splitNodeGuttman(
124354 Rtree *pRtree,
124355 RtreeCell *aCell,
124356 int nCell,
124357 RtreeNode *pLeft,
124358 RtreeNode *pRight,
124359 RtreeCell *pBboxLeft,
124360 RtreeCell *pBboxRight
124362 int iLeftSeed = 0;
124363 int iRightSeed = 1;
124364 int *aiUsed;
124365 int i;
124367 aiUsed = sqlite3_malloc(sizeof(int)*nCell);
124368 if( !aiUsed ){
124369 return SQLITE_NOMEM;
124371 memset(aiUsed, 0, sizeof(int)*nCell);
124373 PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
124375 memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
124376 memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
124377 nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
124378 nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
124379 aiUsed[iLeftSeed] = 1;
124380 aiUsed[iRightSeed] = 1;
124382 for(i=nCell-2; i>0; i--){
124383 RtreeCell *pNext;
124384 pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
124385 float diff =
124386 cellGrowth(pRtree, pBboxLeft, pNext) -
124387 cellGrowth(pRtree, pBboxRight, pNext)
124389 if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
124390 || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
124392 nodeInsertCell(pRtree, pRight, pNext);
124393 cellUnion(pRtree, pBboxRight, pNext);
124394 }else{
124395 nodeInsertCell(pRtree, pLeft, pNext);
124396 cellUnion(pRtree, pBboxLeft, pNext);
124400 sqlite3_free(aiUsed);
124401 return SQLITE_OK;
124403 #endif
124405 static int updateMapping(
124406 Rtree *pRtree,
124407 i64 iRowid,
124408 RtreeNode *pNode,
124409 int iHeight
124411 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
124412 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
124413 if( iHeight>0 ){
124414 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
124415 if( pChild ){
124416 nodeRelease(pRtree, pChild->pParent);
124417 nodeReference(pNode);
124418 pChild->pParent = pNode;
124421 return xSetMapping(pRtree, iRowid, pNode->iNode);
124424 static int SplitNode(
124425 Rtree *pRtree,
124426 RtreeNode *pNode,
124427 RtreeCell *pCell,
124428 int iHeight
124430 int i;
124431 int newCellIsRight = 0;
124433 int rc = SQLITE_OK;
124434 int nCell = NCELL(pNode);
124435 RtreeCell *aCell;
124436 int *aiUsed;
124438 RtreeNode *pLeft = 0;
124439 RtreeNode *pRight = 0;
124441 RtreeCell leftbbox;
124442 RtreeCell rightbbox;
124444 /* Allocate an array and populate it with a copy of pCell and
124445 ** all cells from node pLeft. Then zero the original node.
124447 aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
124448 if( !aCell ){
124449 rc = SQLITE_NOMEM;
124450 goto splitnode_out;
124452 aiUsed = (int *)&aCell[nCell+1];
124453 memset(aiUsed, 0, sizeof(int)*(nCell+1));
124454 for(i=0; i<nCell; i++){
124455 nodeGetCell(pRtree, pNode, i, &aCell[i]);
124457 nodeZero(pRtree, pNode);
124458 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
124459 nCell++;
124461 if( pNode->iNode==1 ){
124462 pRight = nodeNew(pRtree, pNode);
124463 pLeft = nodeNew(pRtree, pNode);
124464 pRtree->iDepth++;
124465 pNode->isDirty = 1;
124466 writeInt16(pNode->zData, pRtree->iDepth);
124467 }else{
124468 pLeft = pNode;
124469 pRight = nodeNew(pRtree, pLeft->pParent);
124470 nodeReference(pLeft);
124473 if( !pLeft || !pRight ){
124474 rc = SQLITE_NOMEM;
124475 goto splitnode_out;
124478 memset(pLeft->zData, 0, pRtree->iNodeSize);
124479 memset(pRight->zData, 0, pRtree->iNodeSize);
124481 rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
124482 if( rc!=SQLITE_OK ){
124483 goto splitnode_out;
124486 /* Ensure both child nodes have node numbers assigned to them by calling
124487 ** nodeWrite(). Node pRight always needs a node number, as it was created
124488 ** by nodeNew() above. But node pLeft sometimes already has a node number.
124489 ** In this case avoid the all to nodeWrite().
124491 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
124492 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
124494 goto splitnode_out;
124497 rightbbox.iRowid = pRight->iNode;
124498 leftbbox.iRowid = pLeft->iNode;
124500 if( pNode->iNode==1 ){
124501 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
124502 if( rc!=SQLITE_OK ){
124503 goto splitnode_out;
124505 }else{
124506 RtreeNode *pParent = pLeft->pParent;
124507 int iCell;
124508 rc = nodeParentIndex(pRtree, pLeft, &iCell);
124509 if( rc==SQLITE_OK ){
124510 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
124511 rc = AdjustTree(pRtree, pParent, &leftbbox);
124513 if( rc!=SQLITE_OK ){
124514 goto splitnode_out;
124517 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
124518 goto splitnode_out;
124521 for(i=0; i<NCELL(pRight); i++){
124522 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
124523 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
124524 if( iRowid==pCell->iRowid ){
124525 newCellIsRight = 1;
124527 if( rc!=SQLITE_OK ){
124528 goto splitnode_out;
124531 if( pNode->iNode==1 ){
124532 for(i=0; i<NCELL(pLeft); i++){
124533 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
124534 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
124535 if( rc!=SQLITE_OK ){
124536 goto splitnode_out;
124539 }else if( newCellIsRight==0 ){
124540 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
124543 if( rc==SQLITE_OK ){
124544 rc = nodeRelease(pRtree, pRight);
124545 pRight = 0;
124547 if( rc==SQLITE_OK ){
124548 rc = nodeRelease(pRtree, pLeft);
124549 pLeft = 0;
124552 splitnode_out:
124553 nodeRelease(pRtree, pRight);
124554 nodeRelease(pRtree, pLeft);
124555 sqlite3_free(aCell);
124556 return rc;
124560 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
124561 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
124562 ** the pLeaf->pParent chain all the way up to the root node.
124564 ** This operation is required when a row is deleted (or updated - an update
124565 ** is implemented as a delete followed by an insert). SQLite provides the
124566 ** rowid of the row to delete, which can be used to find the leaf on which
124567 ** the entry resides (argument pLeaf). Once the leaf is located, this
124568 ** function is called to determine its ancestry.
124570 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
124571 int rc = SQLITE_OK;
124572 RtreeNode *pChild = pLeaf;
124573 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
124574 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
124575 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
124576 rc = sqlite3_step(pRtree->pReadParent);
124577 if( rc==SQLITE_ROW ){
124578 RtreeNode *pTest; /* Used to test for reference loops */
124579 i64 iNode; /* Node number of parent node */
124581 /* Before setting pChild->pParent, test that we are not creating a
124582 ** loop of references (as we would if, say, pChild==pParent). We don't
124583 ** want to do this as it leads to a memory leak when trying to delete
124584 ** the referenced counted node structures.
124586 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
124587 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
124588 if( !pTest ){
124589 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
124592 rc = sqlite3_reset(pRtree->pReadParent);
124593 if( rc==SQLITE_OK ) rc = rc2;
124594 if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
124595 pChild = pChild->pParent;
124597 return rc;
124600 static int deleteCell(Rtree *, RtreeNode *, int, int);
124602 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
124603 int rc;
124604 int rc2;
124605 RtreeNode *pParent;
124606 int iCell;
124608 assert( pNode->nRef==1 );
124610 /* Remove the entry in the parent cell. */
124611 rc = nodeParentIndex(pRtree, pNode, &iCell);
124612 if( rc==SQLITE_OK ){
124613 pParent = pNode->pParent;
124614 pNode->pParent = 0;
124615 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
124617 rc2 = nodeRelease(pRtree, pParent);
124618 if( rc==SQLITE_OK ){
124619 rc = rc2;
124621 if( rc!=SQLITE_OK ){
124622 return rc;
124625 /* Remove the xxx_node entry. */
124626 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
124627 sqlite3_step(pRtree->pDeleteNode);
124628 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
124629 return rc;
124632 /* Remove the xxx_parent entry. */
124633 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
124634 sqlite3_step(pRtree->pDeleteParent);
124635 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
124636 return rc;
124639 /* Remove the node from the in-memory hash table and link it into
124640 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
124642 nodeHashDelete(pRtree, pNode);
124643 pNode->iNode = iHeight;
124644 pNode->pNext = pRtree->pDeleted;
124645 pNode->nRef++;
124646 pRtree->pDeleted = pNode;
124648 return SQLITE_OK;
124651 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
124652 RtreeNode *pParent = pNode->pParent;
124653 int rc = SQLITE_OK;
124654 if( pParent ){
124655 int ii;
124656 int nCell = NCELL(pNode);
124657 RtreeCell box; /* Bounding box for pNode */
124658 nodeGetCell(pRtree, pNode, 0, &box);
124659 for(ii=1; ii<nCell; ii++){
124660 RtreeCell cell;
124661 nodeGetCell(pRtree, pNode, ii, &cell);
124662 cellUnion(pRtree, &box, &cell);
124664 box.iRowid = pNode->iNode;
124665 rc = nodeParentIndex(pRtree, pNode, &ii);
124666 if( rc==SQLITE_OK ){
124667 nodeOverwriteCell(pRtree, pParent, &box, ii);
124668 rc = fixBoundingBox(pRtree, pParent);
124671 return rc;
124675 ** Delete the cell at index iCell of node pNode. After removing the
124676 ** cell, adjust the r-tree data structure if required.
124678 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
124679 RtreeNode *pParent;
124680 int rc;
124682 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
124683 return rc;
124686 /* Remove the cell from the node. This call just moves bytes around
124687 ** the in-memory node image, so it cannot fail.
124689 nodeDeleteCell(pRtree, pNode, iCell);
124691 /* If the node is not the tree root and now has less than the minimum
124692 ** number of cells, remove it from the tree. Otherwise, update the
124693 ** cell in the parent node so that it tightly contains the updated
124694 ** node.
124696 pParent = pNode->pParent;
124697 assert( pParent || pNode->iNode==1 );
124698 if( pParent ){
124699 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
124700 rc = removeNode(pRtree, pNode, iHeight);
124701 }else{
124702 rc = fixBoundingBox(pRtree, pNode);
124706 return rc;
124709 static int Reinsert(
124710 Rtree *pRtree,
124711 RtreeNode *pNode,
124712 RtreeCell *pCell,
124713 int iHeight
124715 int *aOrder;
124716 int *aSpare;
124717 RtreeCell *aCell;
124718 float *aDistance;
124719 int nCell;
124720 float aCenterCoord[RTREE_MAX_DIMENSIONS];
124721 int iDim;
124722 int ii;
124723 int rc = SQLITE_OK;
124725 memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
124727 nCell = NCELL(pNode)+1;
124729 /* Allocate the buffers used by this operation. The allocation is
124730 ** relinquished before this function returns.
124732 aCell = (RtreeCell *)sqlite3_malloc(nCell * (
124733 sizeof(RtreeCell) + /* aCell array */
124734 sizeof(int) + /* aOrder array */
124735 sizeof(int) + /* aSpare array */
124736 sizeof(float) /* aDistance array */
124738 if( !aCell ){
124739 return SQLITE_NOMEM;
124741 aOrder = (int *)&aCell[nCell];
124742 aSpare = (int *)&aOrder[nCell];
124743 aDistance = (float *)&aSpare[nCell];
124745 for(ii=0; ii<nCell; ii++){
124746 if( ii==(nCell-1) ){
124747 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
124748 }else{
124749 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
124751 aOrder[ii] = ii;
124752 for(iDim=0; iDim<pRtree->nDim; iDim++){
124753 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
124754 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
124757 for(iDim=0; iDim<pRtree->nDim; iDim++){
124758 aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
124761 for(ii=0; ii<nCell; ii++){
124762 aDistance[ii] = 0.0;
124763 for(iDim=0; iDim<pRtree->nDim; iDim++){
124764 float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
124765 DCOORD(aCell[ii].aCoord[iDim*2]);
124766 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
124770 SortByDistance(aOrder, nCell, aDistance, aSpare);
124771 nodeZero(pRtree, pNode);
124773 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
124774 RtreeCell *p = &aCell[aOrder[ii]];
124775 nodeInsertCell(pRtree, pNode, p);
124776 if( p->iRowid==pCell->iRowid ){
124777 if( iHeight==0 ){
124778 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
124779 }else{
124780 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
124784 if( rc==SQLITE_OK ){
124785 rc = fixBoundingBox(pRtree, pNode);
124787 for(; rc==SQLITE_OK && ii<nCell; ii++){
124788 /* Find a node to store this cell in. pNode->iNode currently contains
124789 ** the height of the sub-tree headed by the cell.
124791 RtreeNode *pInsert;
124792 RtreeCell *p = &aCell[aOrder[ii]];
124793 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
124794 if( rc==SQLITE_OK ){
124795 int rc2;
124796 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
124797 rc2 = nodeRelease(pRtree, pInsert);
124798 if( rc==SQLITE_OK ){
124799 rc = rc2;
124804 sqlite3_free(aCell);
124805 return rc;
124809 ** Insert cell pCell into node pNode. Node pNode is the head of a
124810 ** subtree iHeight high (leaf nodes have iHeight==0).
124812 static int rtreeInsertCell(
124813 Rtree *pRtree,
124814 RtreeNode *pNode,
124815 RtreeCell *pCell,
124816 int iHeight
124818 int rc = SQLITE_OK;
124819 if( iHeight>0 ){
124820 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
124821 if( pChild ){
124822 nodeRelease(pRtree, pChild->pParent);
124823 nodeReference(pNode);
124824 pChild->pParent = pNode;
124827 if( nodeInsertCell(pRtree, pNode, pCell) ){
124828 #if VARIANT_RSTARTREE_REINSERT
124829 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
124830 rc = SplitNode(pRtree, pNode, pCell, iHeight);
124831 }else{
124832 pRtree->iReinsertHeight = iHeight;
124833 rc = Reinsert(pRtree, pNode, pCell, iHeight);
124835 #else
124836 rc = SplitNode(pRtree, pNode, pCell, iHeight);
124837 #endif
124838 }else{
124839 rc = AdjustTree(pRtree, pNode, pCell);
124840 if( rc==SQLITE_OK ){
124841 if( iHeight==0 ){
124842 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
124843 }else{
124844 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
124848 return rc;
124851 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
124852 int ii;
124853 int rc = SQLITE_OK;
124854 int nCell = NCELL(pNode);
124856 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
124857 RtreeNode *pInsert;
124858 RtreeCell cell;
124859 nodeGetCell(pRtree, pNode, ii, &cell);
124861 /* Find a node to store this cell in. pNode->iNode currently contains
124862 ** the height of the sub-tree headed by the cell.
124864 rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
124865 if( rc==SQLITE_OK ){
124866 int rc2;
124867 rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
124868 rc2 = nodeRelease(pRtree, pInsert);
124869 if( rc==SQLITE_OK ){
124870 rc = rc2;
124874 return rc;
124878 ** Select a currently unused rowid for a new r-tree record.
124880 static int newRowid(Rtree *pRtree, i64 *piRowid){
124881 int rc;
124882 sqlite3_bind_null(pRtree->pWriteRowid, 1);
124883 sqlite3_bind_null(pRtree->pWriteRowid, 2);
124884 sqlite3_step(pRtree->pWriteRowid);
124885 rc = sqlite3_reset(pRtree->pWriteRowid);
124886 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
124887 return rc;
124891 ** The xUpdate method for rtree module virtual tables.
124893 static int rtreeUpdate(
124894 sqlite3_vtab *pVtab,
124895 int nData,
124896 sqlite3_value **azData,
124897 sqlite_int64 *pRowid
124899 Rtree *pRtree = (Rtree *)pVtab;
124900 int rc = SQLITE_OK;
124902 rtreeReference(pRtree);
124904 assert(nData>=1);
124906 /* If azData[0] is not an SQL NULL value, it is the rowid of a
124907 ** record to delete from the r-tree table. The following block does
124908 ** just that.
124910 if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
124911 i64 iDelete; /* The rowid to delete */
124912 RtreeNode *pLeaf; /* Leaf node containing record iDelete */
124913 int iCell; /* Index of iDelete cell in pLeaf */
124914 RtreeNode *pRoot;
124916 /* Obtain a reference to the root node to initialise Rtree.iDepth */
124917 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
124919 /* Obtain a reference to the leaf node that contains the entry
124920 ** about to be deleted.
124922 if( rc==SQLITE_OK ){
124923 iDelete = sqlite3_value_int64(azData[0]);
124924 rc = findLeafNode(pRtree, iDelete, &pLeaf);
124927 /* Delete the cell in question from the leaf node. */
124928 if( rc==SQLITE_OK ){
124929 int rc2;
124930 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
124931 if( rc==SQLITE_OK ){
124932 rc = deleteCell(pRtree, pLeaf, iCell, 0);
124934 rc2 = nodeRelease(pRtree, pLeaf);
124935 if( rc==SQLITE_OK ){
124936 rc = rc2;
124940 /* Delete the corresponding entry in the <rtree>_rowid table. */
124941 if( rc==SQLITE_OK ){
124942 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
124943 sqlite3_step(pRtree->pDeleteRowid);
124944 rc = sqlite3_reset(pRtree->pDeleteRowid);
124947 /* Check if the root node now has exactly one child. If so, remove
124948 ** it, schedule the contents of the child for reinsertion and
124949 ** reduce the tree height by one.
124951 ** This is equivalent to copying the contents of the child into
124952 ** the root node (the operation that Gutman's paper says to perform
124953 ** in this scenario).
124955 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
124956 int rc2;
124957 RtreeNode *pChild;
124958 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
124959 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
124960 if( rc==SQLITE_OK ){
124961 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
124963 rc2 = nodeRelease(pRtree, pChild);
124964 if( rc==SQLITE_OK ) rc = rc2;
124965 if( rc==SQLITE_OK ){
124966 pRtree->iDepth--;
124967 writeInt16(pRoot->zData, pRtree->iDepth);
124968 pRoot->isDirty = 1;
124972 /* Re-insert the contents of any underfull nodes removed from the tree. */
124973 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
124974 if( rc==SQLITE_OK ){
124975 rc = reinsertNodeContent(pRtree, pLeaf);
124977 pRtree->pDeleted = pLeaf->pNext;
124978 sqlite3_free(pLeaf);
124981 /* Release the reference to the root node. */
124982 if( rc==SQLITE_OK ){
124983 rc = nodeRelease(pRtree, pRoot);
124984 }else{
124985 nodeRelease(pRtree, pRoot);
124989 /* If the azData[] array contains more than one element, elements
124990 ** (azData[2]..azData[argc-1]) contain a new record to insert into
124991 ** the r-tree structure.
124993 if( rc==SQLITE_OK && nData>1 ){
124994 /* Insert a new record into the r-tree */
124995 RtreeCell cell;
124996 int ii;
124997 RtreeNode *pLeaf;
124999 /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
125000 assert( nData==(pRtree->nDim*2 + 3) );
125001 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
125002 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125003 cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
125004 cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
125005 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
125006 rc = SQLITE_CONSTRAINT;
125007 goto constraint;
125010 }else{
125011 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125012 cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
125013 cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
125014 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
125015 rc = SQLITE_CONSTRAINT;
125016 goto constraint;
125021 /* Figure out the rowid of the new row. */
125022 if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
125023 rc = newRowid(pRtree, &cell.iRowid);
125024 }else{
125025 cell.iRowid = sqlite3_value_int64(azData[2]);
125026 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
125027 if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
125028 sqlite3_reset(pRtree->pReadRowid);
125029 rc = SQLITE_CONSTRAINT;
125030 goto constraint;
125032 rc = sqlite3_reset(pRtree->pReadRowid);
125034 *pRowid = cell.iRowid;
125036 if( rc==SQLITE_OK ){
125037 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
125039 if( rc==SQLITE_OK ){
125040 int rc2;
125041 pRtree->iReinsertHeight = -1;
125042 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
125043 rc2 = nodeRelease(pRtree, pLeaf);
125044 if( rc==SQLITE_OK ){
125045 rc = rc2;
125050 constraint:
125051 rtreeRelease(pRtree);
125052 return rc;
125056 ** The xRename method for rtree module virtual tables.
125058 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
125059 Rtree *pRtree = (Rtree *)pVtab;
125060 int rc = SQLITE_NOMEM;
125061 char *zSql = sqlite3_mprintf(
125062 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
125063 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
125064 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
125065 , pRtree->zDb, pRtree->zName, zNewName
125066 , pRtree->zDb, pRtree->zName, zNewName
125067 , pRtree->zDb, pRtree->zName, zNewName
125069 if( zSql ){
125070 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
125071 sqlite3_free(zSql);
125073 return rc;
125076 static sqlite3_module rtreeModule = {
125077 0, /* iVersion */
125078 rtreeCreate, /* xCreate - create a table */
125079 rtreeConnect, /* xConnect - connect to an existing table */
125080 rtreeBestIndex, /* xBestIndex - Determine search strategy */
125081 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
125082 rtreeDestroy, /* xDestroy - Drop a table */
125083 rtreeOpen, /* xOpen - open a cursor */
125084 rtreeClose, /* xClose - close a cursor */
125085 rtreeFilter, /* xFilter - configure scan constraints */
125086 rtreeNext, /* xNext - advance a cursor */
125087 rtreeEof, /* xEof */
125088 rtreeColumn, /* xColumn - read data */
125089 rtreeRowid, /* xRowid - read data */
125090 rtreeUpdate, /* xUpdate - write data */
125091 0, /* xBegin - begin transaction */
125092 0, /* xSync - sync transaction */
125093 0, /* xCommit - commit transaction */
125094 0, /* xRollback - rollback transaction */
125095 0, /* xFindFunction - function overloading */
125096 rtreeRename /* xRename - rename the table */
125099 static int rtreeSqlInit(
125100 Rtree *pRtree,
125101 sqlite3 *db,
125102 const char *zDb,
125103 const char *zPrefix,
125104 int isCreate
125106 int rc = SQLITE_OK;
125108 #define N_STATEMENT 9
125109 static const char *azSql[N_STATEMENT] = {
125110 /* Read and write the xxx_node table */
125111 "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
125112 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
125113 "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
125115 /* Read and write the xxx_rowid table */
125116 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
125117 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
125118 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
125120 /* Read and write the xxx_parent table */
125121 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
125122 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
125123 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
125125 sqlite3_stmt **appStmt[N_STATEMENT];
125126 int i;
125128 pRtree->db = db;
125130 if( isCreate ){
125131 char *zCreate = sqlite3_mprintf(
125132 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
125133 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
125134 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
125135 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
125136 zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
125138 if( !zCreate ){
125139 return SQLITE_NOMEM;
125141 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
125142 sqlite3_free(zCreate);
125143 if( rc!=SQLITE_OK ){
125144 return rc;
125148 appStmt[0] = &pRtree->pReadNode;
125149 appStmt[1] = &pRtree->pWriteNode;
125150 appStmt[2] = &pRtree->pDeleteNode;
125151 appStmt[3] = &pRtree->pReadRowid;
125152 appStmt[4] = &pRtree->pWriteRowid;
125153 appStmt[5] = &pRtree->pDeleteRowid;
125154 appStmt[6] = &pRtree->pReadParent;
125155 appStmt[7] = &pRtree->pWriteParent;
125156 appStmt[8] = &pRtree->pDeleteParent;
125158 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
125159 char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
125160 if( zSql ){
125161 rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
125162 }else{
125163 rc = SQLITE_NOMEM;
125165 sqlite3_free(zSql);
125168 return rc;
125172 ** The second argument to this function contains the text of an SQL statement
125173 ** that returns a single integer value. The statement is compiled and executed
125174 ** using database connection db. If successful, the integer value returned
125175 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
125176 ** code is returned and the value of *piVal after returning is not defined.
125178 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
125179 int rc = SQLITE_NOMEM;
125180 if( zSql ){
125181 sqlite3_stmt *pStmt = 0;
125182 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
125183 if( rc==SQLITE_OK ){
125184 if( SQLITE_ROW==sqlite3_step(pStmt) ){
125185 *piVal = sqlite3_column_int(pStmt, 0);
125187 rc = sqlite3_finalize(pStmt);
125190 return rc;
125194 ** This function is called from within the xConnect() or xCreate() method to
125195 ** determine the node-size used by the rtree table being created or connected
125196 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
125197 ** Otherwise, an SQLite error code is returned.
125199 ** If this function is being called as part of an xConnect(), then the rtree
125200 ** table already exists. In this case the node-size is determined by inspecting
125201 ** the root node of the tree.
125203 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
125204 ** This ensures that each node is stored on a single database page. If the
125205 ** database page-size is so large that more than RTREE_MAXCELLS entries
125206 ** would fit in a single node, use a smaller node-size.
125208 static int getNodeSize(
125209 sqlite3 *db, /* Database handle */
125210 Rtree *pRtree, /* Rtree handle */
125211 int isCreate /* True for xCreate, false for xConnect */
125213 int rc;
125214 char *zSql;
125215 if( isCreate ){
125216 int iPageSize;
125217 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
125218 rc = getIntFromStmt(db, zSql, &iPageSize);
125219 if( rc==SQLITE_OK ){
125220 pRtree->iNodeSize = iPageSize-64;
125221 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
125222 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
125225 }else{
125226 zSql = sqlite3_mprintf(
125227 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
125228 pRtree->zDb, pRtree->zName
125230 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
125233 sqlite3_free(zSql);
125234 return rc;
125238 ** This function is the implementation of both the xConnect and xCreate
125239 ** methods of the r-tree virtual table.
125241 ** argv[0] -> module name
125242 ** argv[1] -> database name
125243 ** argv[2] -> table name
125244 ** argv[...] -> column names...
125246 static int rtreeInit(
125247 sqlite3 *db, /* Database connection */
125248 void *pAux, /* One of the RTREE_COORD_* constants */
125249 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
125250 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
125251 char **pzErr, /* OUT: Error message, if any */
125252 int isCreate /* True for xCreate, false for xConnect */
125254 int rc = SQLITE_OK;
125255 Rtree *pRtree;
125256 int nDb; /* Length of string argv[1] */
125257 int nName; /* Length of string argv[2] */
125258 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
125260 const char *aErrMsg[] = {
125261 0, /* 0 */
125262 "Wrong number of columns for an rtree table", /* 1 */
125263 "Too few columns for an rtree table", /* 2 */
125264 "Too many columns for an rtree table" /* 3 */
125267 int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
125268 if( aErrMsg[iErr] ){
125269 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
125270 return SQLITE_ERROR;
125273 /* Allocate the sqlite3_vtab structure */
125274 nDb = strlen(argv[1]);
125275 nName = strlen(argv[2]);
125276 pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
125277 if( !pRtree ){
125278 return SQLITE_NOMEM;
125280 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
125281 pRtree->nBusy = 1;
125282 pRtree->base.pModule = &rtreeModule;
125283 pRtree->zDb = (char *)&pRtree[1];
125284 pRtree->zName = &pRtree->zDb[nDb+1];
125285 pRtree->nDim = (argc-4)/2;
125286 pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
125287 pRtree->eCoordType = eCoordType;
125288 memcpy(pRtree->zDb, argv[1], nDb);
125289 memcpy(pRtree->zName, argv[2], nName);
125291 /* Figure out the node size to use. */
125292 rc = getNodeSize(db, pRtree, isCreate);
125294 /* Create/Connect to the underlying relational database schema. If
125295 ** that is successful, call sqlite3_declare_vtab() to configure
125296 ** the r-tree table schema.
125298 if( rc==SQLITE_OK ){
125299 if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
125300 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
125301 }else{
125302 char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
125303 char *zTmp;
125304 int ii;
125305 for(ii=4; zSql && ii<argc; ii++){
125306 zTmp = zSql;
125307 zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
125308 sqlite3_free(zTmp);
125310 if( zSql ){
125311 zTmp = zSql;
125312 zSql = sqlite3_mprintf("%s);", zTmp);
125313 sqlite3_free(zTmp);
125315 if( !zSql ){
125316 rc = SQLITE_NOMEM;
125317 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
125318 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
125320 sqlite3_free(zSql);
125324 if( rc==SQLITE_OK ){
125325 *ppVtab = (sqlite3_vtab *)pRtree;
125326 }else{
125327 rtreeRelease(pRtree);
125329 return rc;
125334 ** Implementation of a scalar function that decodes r-tree nodes to
125335 ** human readable strings. This can be used for debugging and analysis.
125337 ** The scalar function takes two arguments, a blob of data containing
125338 ** an r-tree node, and the number of dimensions the r-tree indexes.
125339 ** For a two-dimensional r-tree structure called "rt", to deserialize
125340 ** all nodes, a statement like:
125342 ** SELECT rtreenode(2, data) FROM rt_node;
125344 ** The human readable string takes the form of a Tcl list with one
125345 ** entry for each cell in the r-tree node. Each entry is itself a
125346 ** list, containing the 8-byte rowid/pageno followed by the
125347 ** <num-dimension>*2 coordinates.
125349 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
125350 char *zText = 0;
125351 RtreeNode node;
125352 Rtree tree;
125353 int ii;
125355 UNUSED_PARAMETER(nArg);
125356 memset(&node, 0, sizeof(RtreeNode));
125357 memset(&tree, 0, sizeof(Rtree));
125358 tree.nDim = sqlite3_value_int(apArg[0]);
125359 tree.nBytesPerCell = 8 + 8 * tree.nDim;
125360 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
125362 for(ii=0; ii<NCELL(&node); ii++){
125363 char zCell[512];
125364 int nCell = 0;
125365 RtreeCell cell;
125366 int jj;
125368 nodeGetCell(&tree, &node, ii, &cell);
125369 sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
125370 nCell = strlen(zCell);
125371 for(jj=0; jj<tree.nDim*2; jj++){
125372 sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
125373 nCell = strlen(zCell);
125376 if( zText ){
125377 char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
125378 sqlite3_free(zText);
125379 zText = zTextNew;
125380 }else{
125381 zText = sqlite3_mprintf("{%s}", zCell);
125385 sqlite3_result_text(ctx, zText, -1, sqlite3_free);
125388 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
125389 UNUSED_PARAMETER(nArg);
125390 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
125391 || sqlite3_value_bytes(apArg[0])<2
125393 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
125394 }else{
125395 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
125396 sqlite3_result_int(ctx, readInt16(zBlob));
125401 ** Register the r-tree module with database handle db. This creates the
125402 ** virtual table module "rtree" and the debugging/analysis scalar
125403 ** function "rtreenode".
125405 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
125406 const int utf8 = SQLITE_UTF8;
125407 int rc;
125409 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
125410 if( rc==SQLITE_OK ){
125411 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
125413 if( rc==SQLITE_OK ){
125414 void *c = (void *)RTREE_COORD_REAL32;
125415 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
125417 if( rc==SQLITE_OK ){
125418 void *c = (void *)RTREE_COORD_INT32;
125419 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
125422 return rc;
125426 ** A version of sqlite3_free() that can be used as a callback. This is used
125427 ** in two places - as the destructor for the blob value returned by the
125428 ** invocation of a geometry function, and as the destructor for the geometry
125429 ** functions themselves.
125431 static void doSqlite3Free(void *p){
125432 sqlite3_free(p);
125436 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
125437 ** scalar user function. This C function is the callback used for all such
125438 ** registered SQL functions.
125440 ** The scalar user functions return a blob that is interpreted by r-tree
125441 ** table MATCH operators.
125443 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
125444 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
125445 RtreeMatchArg *pBlob;
125446 int nBlob;
125448 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
125449 pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
125450 if( !pBlob ){
125451 sqlite3_result_error_nomem(ctx);
125452 }else{
125453 int i;
125454 pBlob->magic = RTREE_GEOMETRY_MAGIC;
125455 pBlob->xGeom = pGeomCtx->xGeom;
125456 pBlob->pContext = pGeomCtx->pContext;
125457 pBlob->nParam = nArg;
125458 for(i=0; i<nArg; i++){
125459 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
125461 sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
125466 ** Register a new geometry function for use with the r-tree MATCH operator.
125468 SQLITE_API int sqlite3_rtree_geometry_callback(
125469 sqlite3 *db,
125470 const char *zGeom,
125471 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
125472 void *pContext
125474 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
125476 /* Allocate and populate the context object. */
125477 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
125478 if( !pGeomCtx ) return SQLITE_NOMEM;
125479 pGeomCtx->xGeom = xGeom;
125480 pGeomCtx->pContext = pContext;
125482 /* Create the new user-function. Register a destructor function to delete
125483 ** the context object when it is no longer required. */
125484 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
125485 (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
125489 #if !SQLITE_CORE
125490 SQLITE_API int sqlite3_extension_init(
125491 sqlite3 *db,
125492 char **pzErrMsg,
125493 const sqlite3_api_routines *pApi
125495 SQLITE_EXTENSION_INIT2(pApi)
125496 return sqlite3RtreeInit(db);
125498 #endif
125500 #endif
125502 /************** End of rtree.c ***********************************************/
125503 /************** Begin file icu.c *********************************************/
125505 ** 2007 May 6
125507 ** The author disclaims copyright to this source code. In place of
125508 ** a legal notice, here is a blessing:
125510 ** May you do good and not evil.
125511 ** May you find forgiveness for yourself and forgive others.
125512 ** May you share freely, never taking more than you give.
125514 *************************************************************************
125515 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
125517 ** This file implements an integration between the ICU library
125518 ** ("International Components for Unicode", an open-source library
125519 ** for handling unicode data) and SQLite. The integration uses
125520 ** ICU to provide the following to SQLite:
125522 ** * An implementation of the SQL regexp() function (and hence REGEXP
125523 ** operator) using the ICU uregex_XX() APIs.
125525 ** * Implementations of the SQL scalar upper() and lower() functions
125526 ** for case mapping.
125528 ** * Integration of ICU and SQLite collation seqences.
125530 ** * An implementation of the LIKE operator that uses ICU to
125531 ** provide case-independent matching.
125534 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
125536 /* Include ICU headers */
125537 #include <unicode/utypes.h>
125538 #include <unicode/uregex.h>
125539 #include <unicode/ustring.h>
125540 #include <unicode/ucol.h>
125543 #ifndef SQLITE_CORE
125544 SQLITE_EXTENSION_INIT1
125545 #else
125546 #endif
125549 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
125550 ** operator.
125552 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
125553 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
125554 #endif
125557 ** Version of sqlite3_free() that is always a function, never a macro.
125559 static void xFree(void *p){
125560 sqlite3_free(p);
125564 ** Compare two UTF-8 strings for equality where the first string is
125565 ** a "LIKE" expression. Return true (1) if they are the same and
125566 ** false (0) if they are different.
125568 static int icuLikeCompare(
125569 const uint8_t *zPattern, /* LIKE pattern */
125570 const uint8_t *zString, /* The UTF-8 string to compare against */
125571 const UChar32 uEsc /* The escape character */
125573 static const int MATCH_ONE = (UChar32)'_';
125574 static const int MATCH_ALL = (UChar32)'%';
125576 int iPattern = 0; /* Current byte index in zPattern */
125577 int iString = 0; /* Current byte index in zString */
125579 int prevEscape = 0; /* True if the previous character was uEsc */
125581 while( zPattern[iPattern]!=0 ){
125583 /* Read (and consume) the next character from the input pattern. */
125584 UChar32 uPattern;
125585 U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
125586 assert(uPattern!=0);
125588 /* There are now 4 possibilities:
125590 ** 1. uPattern is an unescaped match-all character "%",
125591 ** 2. uPattern is an unescaped match-one character "_",
125592 ** 3. uPattern is an unescaped escape character, or
125593 ** 4. uPattern is to be handled as an ordinary character
125595 if( !prevEscape && uPattern==MATCH_ALL ){
125596 /* Case 1. */
125597 uint8_t c;
125599 /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
125600 ** MATCH_ALL. For each MATCH_ONE, skip one character in the
125601 ** test string.
125603 while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
125604 if( c==MATCH_ONE ){
125605 if( zString[iString]==0 ) return 0;
125606 U8_FWD_1_UNSAFE(zString, iString);
125608 iPattern++;
125611 if( zPattern[iPattern]==0 ) return 1;
125613 while( zString[iString] ){
125614 if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
125615 return 1;
125617 U8_FWD_1_UNSAFE(zString, iString);
125619 return 0;
125621 }else if( !prevEscape && uPattern==MATCH_ONE ){
125622 /* Case 2. */
125623 if( zString[iString]==0 ) return 0;
125624 U8_FWD_1_UNSAFE(zString, iString);
125626 }else if( !prevEscape && uPattern==uEsc){
125627 /* Case 3. */
125628 prevEscape = 1;
125630 }else{
125631 /* Case 4. */
125632 UChar32 uString;
125633 U8_NEXT_UNSAFE(zString, iString, uString);
125634 uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
125635 uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
125636 if( uString!=uPattern ){
125637 return 0;
125639 prevEscape = 0;
125643 return zString[iString]==0;
125647 ** Implementation of the like() SQL function. This function implements
125648 ** the build-in LIKE operator. The first argument to the function is the
125649 ** pattern and the second argument is the string. So, the SQL statements:
125651 ** A LIKE B
125653 ** is implemented as like(B, A). If there is an escape character E,
125655 ** A LIKE B ESCAPE E
125657 ** is mapped to like(B, A, E).
125659 static void icuLikeFunc(
125660 sqlite3_context *context,
125661 int argc,
125662 sqlite3_value **argv
125664 const unsigned char *zA = sqlite3_value_text(argv[0]);
125665 const unsigned char *zB = sqlite3_value_text(argv[1]);
125666 UChar32 uEsc = 0;
125668 /* Limit the length of the LIKE or GLOB pattern to avoid problems
125669 ** of deep recursion and N*N behavior in patternCompare().
125671 if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
125672 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
125673 return;
125677 if( argc==3 ){
125678 /* The escape character string must consist of a single UTF-8 character.
125679 ** Otherwise, return an error.
125681 int nE= sqlite3_value_bytes(argv[2]);
125682 const unsigned char *zE = sqlite3_value_text(argv[2]);
125683 int i = 0;
125684 if( zE==0 ) return;
125685 U8_NEXT(zE, i, nE, uEsc);
125686 if( i!=nE){
125687 sqlite3_result_error(context,
125688 "ESCAPE expression must be a single character", -1);
125689 return;
125693 if( zA && zB ){
125694 sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
125699 ** This function is called when an ICU function called from within
125700 ** the implementation of an SQL scalar function returns an error.
125702 ** The scalar function context passed as the first argument is
125703 ** loaded with an error message based on the following two args.
125705 static void icuFunctionError(
125706 sqlite3_context *pCtx, /* SQLite scalar function context */
125707 const char *zName, /* Name of ICU function that failed */
125708 UErrorCode e /* Error code returned by ICU function */
125710 char zBuf[128];
125711 sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
125712 zBuf[127] = '\0';
125713 sqlite3_result_error(pCtx, zBuf, -1);
125717 ** Function to delete compiled regexp objects. Registered as
125718 ** a destructor function with sqlite3_set_auxdata().
125720 static void icuRegexpDelete(void *p){
125721 URegularExpression *pExpr = (URegularExpression *)p;
125722 uregex_close(pExpr);
125726 ** Implementation of SQLite REGEXP operator. This scalar function takes
125727 ** two arguments. The first is a regular expression pattern to compile
125728 ** the second is a string to match against that pattern. If either
125729 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
125730 ** is 1 if the string matches the pattern, or 0 otherwise.
125732 ** SQLite maps the regexp() function to the regexp() operator such
125733 ** that the following two are equivalent:
125735 ** zString REGEXP zPattern
125736 ** regexp(zPattern, zString)
125738 ** Uses the following ICU regexp APIs:
125740 ** uregex_open()
125741 ** uregex_matches()
125742 ** uregex_close()
125744 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
125745 UErrorCode status = U_ZERO_ERROR;
125746 URegularExpression *pExpr;
125747 UBool res;
125748 const UChar *zString = sqlite3_value_text16(apArg[1]);
125750 (void)nArg; /* Unused parameter */
125752 /* If the left hand side of the regexp operator is NULL,
125753 ** then the result is also NULL.
125755 if( !zString ){
125756 return;
125759 pExpr = sqlite3_get_auxdata(p, 0);
125760 if( !pExpr ){
125761 const UChar *zPattern = sqlite3_value_text16(apArg[0]);
125762 if( !zPattern ){
125763 return;
125765 pExpr = uregex_open(zPattern, -1, 0, 0, &status);
125767 if( U_SUCCESS(status) ){
125768 sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
125769 }else{
125770 assert(!pExpr);
125771 icuFunctionError(p, "uregex_open", status);
125772 return;
125776 /* Configure the text that the regular expression operates on. */
125777 uregex_setText(pExpr, zString, -1, &status);
125778 if( !U_SUCCESS(status) ){
125779 icuFunctionError(p, "uregex_setText", status);
125780 return;
125783 /* Attempt the match */
125784 res = uregex_matches(pExpr, 0, &status);
125785 if( !U_SUCCESS(status) ){
125786 icuFunctionError(p, "uregex_matches", status);
125787 return;
125790 /* Set the text that the regular expression operates on to a NULL
125791 ** pointer. This is not really necessary, but it is tidier than
125792 ** leaving the regular expression object configured with an invalid
125793 ** pointer after this function returns.
125795 uregex_setText(pExpr, 0, 0, &status);
125797 /* Return 1 or 0. */
125798 sqlite3_result_int(p, res ? 1 : 0);
125802 ** Implementations of scalar functions for case mapping - upper() and
125803 ** lower(). Function upper() converts its input to upper-case (ABC).
125804 ** Function lower() converts to lower-case (abc).
125806 ** ICU provides two types of case mapping, "general" case mapping and
125807 ** "language specific". Refer to ICU documentation for the differences
125808 ** between the two.
125810 ** To utilise "general" case mapping, the upper() or lower() scalar
125811 ** functions are invoked with one argument:
125813 ** upper('ABC') -> 'abc'
125814 ** lower('abc') -> 'ABC'
125816 ** To access ICU "language specific" case mapping, upper() or lower()
125817 ** should be invoked with two arguments. The second argument is the name
125818 ** of the locale to use. Passing an empty string ("") or SQL NULL value
125819 ** as the second argument is the same as invoking the 1 argument version
125820 ** of upper() or lower().
125822 ** lower('I', 'en_us') -> 'i'
125823 ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
125825 ** http://www.icu-project.org/userguide/posix.html#case_mappings
125827 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
125828 const UChar *zInput;
125829 UChar *zOutput;
125830 int nInput;
125831 int nOutput;
125833 UErrorCode status = U_ZERO_ERROR;
125834 const char *zLocale = 0;
125836 assert(nArg==1 || nArg==2);
125837 if( nArg==2 ){
125838 zLocale = (const char *)sqlite3_value_text(apArg[1]);
125841 zInput = sqlite3_value_text16(apArg[0]);
125842 if( !zInput ){
125843 return;
125845 nInput = sqlite3_value_bytes16(apArg[0]);
125847 nOutput = nInput * 2 + 2;
125848 zOutput = sqlite3_malloc(nOutput);
125849 if( !zOutput ){
125850 return;
125853 if( sqlite3_user_data(p) ){
125854 u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
125855 }else{
125856 u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
125859 if( !U_SUCCESS(status) ){
125860 icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
125861 return;
125864 sqlite3_result_text16(p, zOutput, -1, xFree);
125868 ** Collation sequence destructor function. The pCtx argument points to
125869 ** a UCollator structure previously allocated using ucol_open().
125871 static void icuCollationDel(void *pCtx){
125872 UCollator *p = (UCollator *)pCtx;
125873 ucol_close(p);
125877 ** Collation sequence comparison function. The pCtx argument points to
125878 ** a UCollator structure previously allocated using ucol_open().
125880 static int icuCollationColl(
125881 void *pCtx,
125882 int nLeft,
125883 const void *zLeft,
125884 int nRight,
125885 const void *zRight
125887 UCollationResult res;
125888 UCollator *p = (UCollator *)pCtx;
125889 res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
125890 switch( res ){
125891 case UCOL_LESS: return -1;
125892 case UCOL_GREATER: return +1;
125893 case UCOL_EQUAL: return 0;
125895 assert(!"Unexpected return value from ucol_strcoll()");
125896 return 0;
125900 ** Implementation of the scalar function icu_load_collation().
125902 ** This scalar function is used to add ICU collation based collation
125903 ** types to an SQLite database connection. It is intended to be called
125904 ** as follows:
125906 ** SELECT icu_load_collation(<locale>, <collation-name>);
125908 ** Where <locale> is a string containing an ICU locale identifier (i.e.
125909 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
125910 ** collation sequence to create.
125912 static void icuLoadCollation(
125913 sqlite3_context *p,
125914 int nArg,
125915 sqlite3_value **apArg
125917 sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
125918 UErrorCode status = U_ZERO_ERROR;
125919 const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
125920 const char *zName; /* SQL Collation sequence name (eg. "japanese") */
125921 UCollator *pUCollator; /* ICU library collation object */
125922 int rc; /* Return code from sqlite3_create_collation_x() */
125924 assert(nArg==2);
125925 zLocale = (const char *)sqlite3_value_text(apArg[0]);
125926 zName = (const char *)sqlite3_value_text(apArg[1]);
125928 if( !zLocale || !zName ){
125929 return;
125932 pUCollator = ucol_open(zLocale, &status);
125933 if( !U_SUCCESS(status) ){
125934 icuFunctionError(p, "ucol_open", status);
125935 return;
125937 assert(p);
125939 rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
125940 icuCollationColl, icuCollationDel
125942 if( rc!=SQLITE_OK ){
125943 ucol_close(pUCollator);
125944 sqlite3_result_error(p, "Error registering collation function", -1);
125949 ** Register the ICU extension functions with database db.
125951 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
125952 struct IcuScalar {
125953 const char *zName; /* Function name */
125954 int nArg; /* Number of arguments */
125955 int enc; /* Optimal text encoding */
125956 void *pContext; /* sqlite3_user_data() context */
125957 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
125958 } scalars[] = {
125959 {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
125961 {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
125962 {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
125963 {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
125964 {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
125966 {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
125967 {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
125968 {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
125969 {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
125971 {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
125972 {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
125974 {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
125977 int rc = SQLITE_OK;
125978 int i;
125980 for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
125981 struct IcuScalar *p = &scalars[i];
125982 rc = sqlite3_create_function(
125983 db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
125987 return rc;
125990 #if !SQLITE_CORE
125991 SQLITE_API int sqlite3_extension_init(
125992 sqlite3 *db,
125993 char **pzErrMsg,
125994 const sqlite3_api_routines *pApi
125996 SQLITE_EXTENSION_INIT2(pApi)
125997 return sqlite3IcuInit(db);
125999 #endif
126001 #endif
126003 /************** End of icu.c *************************************************/
126004 /************** Begin file fts3_icu.c ****************************************/
126006 ** 2007 June 22
126008 ** The author disclaims copyright to this source code. In place of
126009 ** a legal notice, here is a blessing:
126011 ** May you do good and not evil.
126012 ** May you find forgiveness for yourself and forgive others.
126013 ** May you share freely, never taking more than you give.
126015 *************************************************************************
126016 ** This file implements a tokenizer for fts3 based on the ICU library.
126018 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
126021 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126022 #ifdef SQLITE_ENABLE_ICU
126025 #include <unicode/ubrk.h>
126026 #include <unicode/utf16.h>
126028 typedef struct IcuTokenizer IcuTokenizer;
126029 typedef struct IcuCursor IcuCursor;
126031 struct IcuTokenizer {
126032 sqlite3_tokenizer base;
126033 char *zLocale;
126036 struct IcuCursor {
126037 sqlite3_tokenizer_cursor base;
126039 UBreakIterator *pIter; /* ICU break-iterator object */
126040 int nChar; /* Number of UChar elements in pInput */
126041 UChar *aChar; /* Copy of input using utf-16 encoding */
126042 int *aOffset; /* Offsets of each character in utf-8 input */
126044 int nBuffer;
126045 char *zBuffer;
126047 int iToken;
126051 ** Create a new tokenizer instance.
126053 static int icuCreate(
126054 int argc, /* Number of entries in argv[] */
126055 const char * const *argv, /* Tokenizer creation arguments */
126056 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
126058 IcuTokenizer *p;
126059 int n = 0;
126061 if( argc>0 ){
126062 n = strlen(argv[0])+1;
126064 p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
126065 if( !p ){
126066 return SQLITE_NOMEM;
126068 memset(p, 0, sizeof(IcuTokenizer));
126070 if( n ){
126071 p->zLocale = (char *)&p[1];
126072 memcpy(p->zLocale, argv[0], n);
126075 *ppTokenizer = (sqlite3_tokenizer *)p;
126077 return SQLITE_OK;
126081 ** Destroy a tokenizer
126083 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
126084 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
126085 sqlite3_free(p);
126086 return SQLITE_OK;
126090 ** Prepare to begin tokenizing a particular string. The input
126091 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
126092 ** used to incrementally tokenize this string is returned in
126093 ** *ppCursor.
126095 static int icuOpen(
126096 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
126097 const char *zInput, /* Input string */
126098 int nInput, /* Length of zInput in bytes */
126099 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
126101 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
126102 IcuCursor *pCsr;
126104 const int32_t opt = U_FOLD_CASE_DEFAULT;
126105 UErrorCode status = U_ZERO_ERROR;
126106 int nChar;
126108 UChar32 c;
126109 int iInput = 0;
126110 int iOut = 0;
126112 *ppCursor = 0;
126114 if( nInput<0 ){
126115 nInput = strlen(zInput);
126117 nChar = nInput+1;
126118 pCsr = (IcuCursor *)sqlite3_malloc(
126119 sizeof(IcuCursor) + /* IcuCursor */
126120 (nChar+1) * sizeof(int) + /* IcuCursor.aOffset[] */
126121 nChar * sizeof(UChar) /* IcuCursor.aChar[] */
126123 if( !pCsr ){
126124 return SQLITE_NOMEM;
126126 memset(pCsr, 0, sizeof(IcuCursor));
126127 pCsr->aOffset = (int *)&pCsr[1];
126128 pCsr->aChar = (UChar *)&pCsr->aOffset[nChar+1];
126130 pCsr->aOffset[iOut] = iInput;
126131 U8_NEXT(zInput, iInput, nInput, c);
126132 while( c>0 ){
126133 int isError = 0;
126134 c = u_foldCase(c, opt);
126135 U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
126136 if( isError ){
126137 sqlite3_free(pCsr);
126138 return SQLITE_ERROR;
126140 pCsr->aOffset[iOut] = iInput;
126142 if( iInput<nInput ){
126143 U8_NEXT(zInput, iInput, nInput, c);
126144 }else{
126145 c = 0;
126149 pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
126150 if( !U_SUCCESS(status) ){
126151 sqlite3_free(pCsr);
126152 return SQLITE_ERROR;
126154 pCsr->nChar = iOut;
126156 ubrk_first(pCsr->pIter);
126157 *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
126158 return SQLITE_OK;
126162 ** Close a tokenization cursor previously opened by a call to icuOpen().
126164 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
126165 IcuCursor *pCsr = (IcuCursor *)pCursor;
126166 ubrk_close(pCsr->pIter);
126167 sqlite3_free(pCsr->zBuffer);
126168 sqlite3_free(pCsr);
126169 return SQLITE_OK;
126173 ** Extract the next token from a tokenization cursor.
126175 static int icuNext(
126176 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
126177 const char **ppToken, /* OUT: *ppToken is the token text */
126178 int *pnBytes, /* OUT: Number of bytes in token */
126179 int *piStartOffset, /* OUT: Starting offset of token */
126180 int *piEndOffset, /* OUT: Ending offset of token */
126181 int *piPosition /* OUT: Position integer of token */
126183 IcuCursor *pCsr = (IcuCursor *)pCursor;
126185 int iStart = 0;
126186 int iEnd = 0;
126187 int nByte = 0;
126189 while( iStart==iEnd ){
126190 UChar32 c;
126192 iStart = ubrk_current(pCsr->pIter);
126193 iEnd = ubrk_next(pCsr->pIter);
126194 if( iEnd==UBRK_DONE ){
126195 return SQLITE_DONE;
126198 while( iStart<iEnd ){
126199 int iWhite = iStart;
126200 U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
126201 if( u_isspace(c) ){
126202 iStart = iWhite;
126203 }else{
126204 break;
126207 assert(iStart<=iEnd);
126211 UErrorCode status = U_ZERO_ERROR;
126212 if( nByte ){
126213 char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
126214 if( !zNew ){
126215 return SQLITE_NOMEM;
126217 pCsr->zBuffer = zNew;
126218 pCsr->nBuffer = nByte;
126221 u_strToUTF8(
126222 pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
126223 &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
126224 &status /* Output success/failure */
126226 } while( nByte>pCsr->nBuffer );
126228 *ppToken = pCsr->zBuffer;
126229 *pnBytes = nByte;
126230 *piStartOffset = pCsr->aOffset[iStart];
126231 *piEndOffset = pCsr->aOffset[iEnd];
126232 *piPosition = pCsr->iToken++;
126234 return SQLITE_OK;
126238 ** The set of routines that implement the simple tokenizer
126240 static const sqlite3_tokenizer_module icuTokenizerModule = {
126241 0, /* iVersion */
126242 icuCreate, /* xCreate */
126243 icuDestroy, /* xCreate */
126244 icuOpen, /* xOpen */
126245 icuClose, /* xClose */
126246 icuNext, /* xNext */
126250 ** Set *ppModule to point at the implementation of the ICU tokenizer.
126252 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
126253 sqlite3_tokenizer_module const**ppModule
126255 *ppModule = &icuTokenizerModule;
126258 #endif /* defined(SQLITE_ENABLE_ICU) */
126259 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126261 /************** End of fts3_icu.c ********************************************/